From fcbc64cea87e6443f2fa246f066b5a9ca02a99dd Mon Sep 17 00:00:00 2001 From: Surya Paolo Date: Fri, 29 Aug 2025 23:34:08 +0200 Subject: [PATCH] - Modifiche a ProductInfo... Continua --- .vscode/launch.json | 34 +- src/server/controllers/articleController.js | 31 +- src/server/models/catalog.js | 63 +- src/server/models/catprod.js | 10 +- src/server/models/collana.js | 4 +- src/server/models/order.js | 45 +- src/server/models/orderscart.js | 5 - src/server/models/product.js | 404 +++++++++- src/server/models/productInfo.js | 294 +------ src/server/models/publisher.js | 4 +- src/server/models/t_web_articolifatturati.js | 17 +- src/server/models/t_web_ordini.js | 16 +- src/server/modules/CronMod.js | 12 +- src/server/modules/Macro.js | 56 +- src/server/modules/Scraping.js | 27 +- src/server/router/admin_router.js | 117 ++- src/server/router/api_router.js | 34 +- src/server/router/cart_router.js | 19 +- src/server/router/index_router.js | 2 - src/server/router/users_router.js | 760 +++++++++---------- src/server/tools/general.js | 57 +- src/server/tools/globalTables.js | 2 - src/server/tools/shared_nodejs.js | 2 +- warnedUsers.json | 1 + 24 files changed, 1006 insertions(+), 1010 deletions(-) create mode 100644 warnedUsers.json diff --git a/.vscode/launch.json b/.vscode/launch.json index 36d3e5b..6d484af 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -1,7 +1,7 @@ { "version": "0.2.0", "configurations": [ - + { "type": "node", "request": "launch", @@ -61,5 +61,37 @@ "TESTING_ON": "1" } }, + { + "type": "node", + "request": "launch", + "name": "Debug CheckSmartBot", + "program": "${workspaceFolder}/../checksmartbot/bot.js", + "console": "integratedTerminal", + "outFiles": [ + "${workspaceFolder}/../**/*.js" + ], + "envFile": "${workspaceFolder}/.env", + "skipFiles": [ + "/**" + ], + "autoAttachChildProcesses": true, + "smartStep": true + }, + { + "type": "node", + "request": "launch", + "name": "Avvia bot con pm2 (attach)", + "runtimeExecutable": "pm2", + "runtimeArgs": [ + "start", + "bot.js", + "--name", + "checksmartbot" + ], + "console": "integratedTerminal", + "restart": true, + "port": 9229, + "attach": true + } ] } \ No newline at end of file diff --git a/src/server/controllers/articleController.js b/src/server/controllers/articleController.js index c10a86b..4138e85 100644 --- a/src/server/controllers/articleController.js +++ b/src/server/controllers/articleController.js @@ -237,7 +237,7 @@ exports.getTableContentBase = async (options) => { GROUP BY IdArticolo ) b ON T.IdArticolo = b.IdArticolo AND T.DataOra = b.data ` + (options.campispeciali - ? ` + ? ` RIGHT JOIN ( SELECT e.IdStatoProdotto, @@ -302,10 +302,9 @@ ON GROUP BY IdArgomento ) h ON g2.IdArgomento = h.IdArgomento AND g2.DataOra = h.data12 ) i2 ON T.ListaArgomenti = i2.IdArgomento - `+ - (options.showQtaDisponibile - - ? ` RIGHT JOIN( + ` + + (options.showQtaDisponibile + ? ` RIGHT JOIN( SELECT o.Codice, o.QtaDisponibile FROM T_WEB_Disponibile o JOIN( @@ -314,8 +313,8 @@ ON GROUP BY Codice ) p ON o.Codice = p.Codice AND o.DataOra = p.data1 ) q ON T.IdArticolo = q.Codice` - : ``) + - ` RIGHT JOIN( + : ``) + + ` RIGHT JOIN( SELECT a3.IdMarchioEditoriale, a3.Descrizione as CasaEditrice FROM T_WEB_MarchiEditoriali a3 JOIN( @@ -816,17 +815,17 @@ exports.viewTable = async (req, res) => { exports.updateLocalDb = async (tableContent, options) => { try { - const ProductInfo = require('../models/productInfo'); + const Product = require('../models/product'); const CatProd = require('../models/catprod'); - let recproductInfo = { - code: tableContent.Ean13.trim(), - }; + const code = tableContent.Ean13.trim(); let risrecUpdated = null; - const recfound = await ProductInfo.findOne({ code: recproductInfo.code }).lean(); + const recfound = await Product.findOne({ 'productInfo.code': code }).lean(); + if (recfound) { + const recproductInfo = recfound.productInfo; ListaArgomenti = tableContent.ListaArgomenti; let arrayPulito = ListaArgomenti.trim() // Rimuove gli spazi all'inizio e alla fine @@ -835,7 +834,7 @@ exports.updateLocalDb = async (tableContent, options) => { if (arrayPulito && arrayPulito.length > 0) { let aggiornacat = false; - const precCatProds = recfound.idCatProds; + const precCatProds = recfound.productInfo.idCatProds; let reccatprods = []; for (let i = 0; i < arrayPulito.length; i++) { const idArgomento = parseInt(arrayPulito[i]); @@ -882,9 +881,9 @@ exports.updateLocalDb = async (tableContent, options) => { } if (aggiorna) { - risrecUpdated = await ProductInfo.findOneAndUpdate( - { code: recproductInfo.code }, - { $set: recproductInfo }, + risrecUpdated = await Product.findOneAndUpdate( + { _id: recfound._id }, + { $set: { productInfo: recproductInfo } }, { new: true, upsert: true } ); } diff --git a/src/server/models/catalog.js b/src/server/models/catalog.js index 526570e..cbb9395 100755 --- a/src/server/models/catalog.js +++ b/src/server/models/catalog.js @@ -194,25 +194,29 @@ CatalogSchema.statics.getCatalogById = async function (id) { try { let arrrec = await Catalog.find({ _id: id }) .populate({ - path: 'lista_prodotti', // Popola il campo lista_prodotti - populate: { - path: 'idProductInfo', - model: 'ProductInfo', - populate: [ - { - path: 'idCatProds', - model: 'CatProd', - }, - { - path: 'idSubCatProds', - model: 'SubCatProd', - }, - { - path: 'idAuthors', - model: 'Author', - }, - ], - }, + path: 'lista_prodotti', + populate: [ + { + path: 'productInfo.idCatProds', + model: 'CatProd', + }, + { + path: 'productInfo.idSubCatProds', + model: 'SubCatProd', + }, + { + path: 'productInfo.idAuthors', + model: 'Author', + }, + { + path: 'productInfo.idCollana', + model: 'Collana', + }, + { + path: 'productInfo.idPublisher', + model: 'Publisher', + }, + ], }) .populate({ path: 'lista_prodotti', @@ -254,11 +258,11 @@ CatalogSchema.statics.getCatalogById = async function (id) { const originalLength = catalog.lista_prodotti.length; catalog.lista_prodotti = catalog.lista_prodotti.filter( (product) => - product.idProductInfo && - product.idProductInfo.code && - product.idProductInfo.code !== '' && - product.idProductInfo.imagefile && - product.idProductInfo.imagefile !== 'noimg.jpg' && + product.productInfo && + product.productInfo.code && + product.productInfo.code !== '' && + product.productInfo.imagefile && + product.productInfo.imagefile !== 'noimg.jpg' && !product.delete ); if (catalog.lista_prodotti.length !== originalLength) { @@ -272,17 +276,16 @@ CatalogSchema.statics.getCatalogById = async function (id) { lista_prodotti: catalog.lista_prodotti.map((product) => ({ ...product.toObject(), productInfo: { - ...product.idProductInfo.toObject(), // Copia tutti i campi di idProductInfo - catprods: product.idProductInfo.idCatProds, // Rinomina idCatProds in catprods - subcatprods: product.idProductInfo.idSubCatProds, - collana: product.idProductInfo.idCollana, - authors: product.idProductInfo.idAuthors, + ...product.productInfo, + catprods: product.productInfo.idCatProds, + subcatprods: product.productInfo.idSubCatProds, + collana: product.productInfo.idCollana, + authors: product.productInfo.idAuthors, }, producer: product.idProducer, storehouse: product.idStorehouses, scontisticas: product.idScontisticas, gasordine: product.idGasordine, - idProductInfo: product.idProductInfo._id, // CHECK })), })); diff --git a/src/server/models/catprod.js b/src/server/models/catprod.js index fd65f45..8c616ae 100755 --- a/src/server/models/catprod.js +++ b/src/server/models/catprod.js @@ -62,13 +62,13 @@ CatProdSchema.statics.findAllIdApp = async function (idapp) { return await CatProd.find(myfind).sort({ name: 1 }).lean(); }; -CatProdSchema.statics.updateCatDeleteEmpty = async function (idapp) { +/*CatProdSchema.statics.updateCatDeleteEmpty = async function (idapp) { try { const toDelete = await CatProd.aggregate([ { $match: { idapp } }, { $lookup: { - from: 'productinfos', + from: 'products', localField: '_id', foreignField: 'idCatProds', as: 'products' @@ -99,7 +99,7 @@ CatProdSchema.statics.updateCatDeleteEmpty = async function (idapp) { return error; } -}; +};*/ CatProdSchema.statics.getCatProdWithTitleCount = async function (idapp, updatedata) { try { @@ -108,9 +108,9 @@ CatProdSchema.statics.getCatProdWithTitleCount = async function (idapp, updateda { $match: { idapp } }, { $lookup: { - from: 'productinfos', // Nome della tua collezione productInfo + from: 'products', // Nome della tua collezione productInfo localField: '_id', - foreignField: 'idCatProds', + foreignField: 'productInfo.idCatProds', as: 'products' } }, diff --git a/src/server/models/collana.js b/src/server/models/collana.js index 62a44b2..8dc30cf 100755 --- a/src/server/models/collana.js +++ b/src/server/models/collana.js @@ -63,9 +63,9 @@ module.exports.getCollaneWithTitleCount = async function (idapp, updatedata) { { $match: { idapp } }, { $lookup: { - from: 'productinfos', // Nome della tua collezione productInfo + from: 'products', // Nome della tua collezione productInfo localField: '_id', - foreignField: 'idCollana', + foreignField: 'productInfo.idCollana', as: 'products' } }, diff --git a/src/server/models/order.js b/src/server/models/order.js index 00e51c9..685fc1f 100755 --- a/src/server/models/order.js +++ b/src/server/models/order.js @@ -168,20 +168,6 @@ module.exports.findAllIdApp = async function (idapp) { as: 'product', }, }, - { - $lookup: { - from: 'productinfos', - localField: 'product.idProduct', - foreignField: '_id', - as: 'product.productInfo', - }, - }, - { - $unwind: { - path: '$product.productInfo', - preserveNullAndEmptyArrays: true, - }, - }, { $lookup: { from: 'producers', @@ -358,20 +344,6 @@ module.exports.getTotalOrderById = async function (id) { preserveNullAndEmptyArrays: true, }, }, - { - $lookup: { - from: 'productinfos', - localField: 'product.idProductInfo', - foreignField: '_id', - as: 'product.productInfo', - }, - }, - { - $unwind: { - path: '$product.productInfo', - preserveNullAndEmptyArrays: true, - }, - }, { $lookup: { from: 'producers', @@ -637,19 +609,6 @@ module.exports.GeneraCSVOrdineProdotti = async function () { preserveNullAndEmptyArrays: true, }, }, - { - $lookup: { - from: 'productinfos', - localField: 'product.idProductInfo', - foreignField: '_id', - as: 'productInfo', - }, - }, - { - $unwind: { - path: '$productInfo', - }, - }, { $lookup: { from: 'gasordines', @@ -682,8 +641,8 @@ module.exports.GeneraCSVOrdineProdotti = async function () { { $group: { _id: '$product._id', - name: { $first: '$productInfo.name' }, - weight: { $first: '$productInfo.weight' }, + name: { $first: '$product.productInfo.name' }, + weight: { $first: '$product.productInfo.weight' }, price_acquistato: { $first: '$product.price_acquistato' }, totalQuantity: { $sum: { $add: ['$quantity', '$quantitypreordered'] } }, totalPrice_acquistato: { diff --git a/src/server/models/orderscart.js b/src/server/models/orderscart.js index da5f722..0d39923 100755 --- a/src/server/models/orderscart.js +++ b/src/server/models/orderscart.js @@ -10,7 +10,6 @@ const Storehouse = require('../models/storehouse'); const Provider = require('../models/provider'); const Gasordine = require('../models/gasordine'); const Product = require('../models/product'); -const ProductInfo = require('../models/productInfo'); const { Circuit } = require('../models/circuit'); @@ -225,10 +224,6 @@ module.exports.getOrdersCartByQuery = async function (query) { populate: { path: 'idProduct', model: 'Product', - populate: { - path: 'idProductInfo', - model: 'ProductInfo' - } } }) .populate({ diff --git a/src/server/models/product.js b/src/server/models/product.js index 0c0faa5..59a3390 100755 --- a/src/server/models/product.js +++ b/src/server/models/product.js @@ -39,7 +39,181 @@ const productSchema = new Schema({ isbn: { type: String, }, - idProductInfo: { type: Schema.Types.ObjectId, ref: 'ProductInfo', index: true }, + idProductInfo: { type: Schema.Types.ObjectId, ref: 'ProductInfo', index: true }, //@@@ DA CANCELLARE DOPO DELLA CONVERSIONE + productInfo: { + department: { + type: String, ref: 'Department' + }, + sku: { + type: String, + }, + code: { + type: String, + required: true, + }, + codice: { + type: String, + }, // codice interno prodotto + id_wp: { + type: String, + }, // id in wordpress + codice_EAN: { + type: String, + }, + barcode: { + type: String, + }, + name: { + type: String, + index: true, + }, + description: { + type: String, + }, + short_descr: { + type: String, + }, + idCatProds: [{ + type: Schema.Types.ObjectId, ref: 'CatProd', index: true + }], + idSubCatProds: [{ + type: Schema.Types.ObjectId, ref: 'SubCatProd' + }], + idStatoProdotto: { + type: Number, index: true + }, + color: { + type: String + }, + size: { + type: String // 11x4x3 + }, + weight: { + type: Number + }, + weight_lordo: { + type: Number + }, + unit: { + type: Number, + }, + unit_lordo: { + type: Number, + }, + sfuso: { + type: Boolean + }, // serve se moltiplicare le qta (es: 12 kg) oppure fare (2 x 20 ml) + vegan: { + type: Boolean + }, + icon: { + type: String, + }, + img: { + type: String, + }, + imagefile: { + type: String, + }, + image_not_found: { + type: Boolean, + }, + vers_img: { + type: Number, + }, + image_link: { + type: String, + }, + link_scheda: { + type: String, + }, + link: { + type: String, + }, + checkout_link: { + type: String, + }, + versioneGM: { + type: String, + }, + img2: { + type: String, + }, + img3: { + type: String, + }, + img4: { + type: String, + }, + ingredienti: { + type: String, + }, + valori_nutrizionali: { + type: String, + }, + note: { + type: String, + }, + idAuthors: [{ + type: Schema.Types.ObjectId, ref: 'Author', index: true + }], + idCollana: { + type: Schema.Types.ObjectId, ref: 'Collana', index: true + }, + idPublisher: { + type: Schema.Types.ObjectId, ref: 'Publisher', index: true + }, + collezione: { + type: String, + }, + ListaArgomenti: { + type: String, + }, + date_pub: { + type: Date, + index: 1, + }, + date_pub_ts: { + type: Number, + }, + productTypes: [{ + type: Number, + }], + + date_updated: { + type: Date, + }, + + date_updated_fromGM: { + type: Date, + }, + + totVen: Number, + totFat: Number, + vLast3M: Number, + fatLast3M: Number, + fatLast6M: Number, + fatLast1Y: Number, + fatLast2Y: Number, + vLast6M: { + type: Number, + index: true, + }, + vLast1Y: { + type: Number, index: true + }, + vLast2Y: Number, + dataUltimoOrdine: Date, + rank3M: Number, + rank6M: Number, + rank1Y: Number, + + descrizione_breve_macro: String, + descrizione_completa_macro: String, + descr_trafiletto_catalogo: String, + sottotitolo: String, + link_macro: String, + }, idProducer: { type: Schema.Types.ObjectId, ref: 'Producer', index: true }, idStorehouses: [{ type: Schema.Types.ObjectId, ref: 'Storehouse', index: true }], idGasordine: { type: Schema.Types.ObjectId, ref: 'Gasordine', index: true }, @@ -367,20 +541,6 @@ module.exports.executeQueryPickup = async function (idapp, params) { } let aggr2 = [ - { - $lookup: { - from: 'productinfos', - localField: 'idProductInfo', - foreignField: '_id', - as: 'productInfo', - }, - }, - { - $unwind: { - path: '$productInfo', - preserveNullAndEmptyArrays: true, - }, - }, { $lookup: { from: 'authors', @@ -606,15 +766,6 @@ module.exports.findAllIdApp = async function (idapp, code, id, all, isbn) { }, { $unwind: { path: '$producer', preserveNullAndEmptyArrays: true } }, - { - $lookup: { - from: 'productinfos', - localField: 'idProductInfo', - foreignField: '_id', - as: 'productInfo', - }, - }, - { $unwind: { path: '$productInfo', preserveNullAndEmptyArrays: true } }, { $match: { 'productInfo.code': { $exists: true, $ne: '' }, @@ -1054,3 +1205,208 @@ module.exports.singlerecconvert_AfterImport_AndSave = async function (idapp, pro console.error('Err', e); } }; + +// --------------------------------------------- + +module.exports.replaceProductImgToImageFile = async function (abilitaserver) { + const Product = this; + + if (abilitaserver) { + // const result = await ProductInfo.updateMany({ "img": { $exists: true } }, { $rename: { 'img': 'imagefile' } }); + + // Trova tutti i documenti con il campo 'img' che esiste + const documents = await Product.find({ "productInfo.img": { $exists: true } }); + + // Aggiorna ciascun documento + for (let doc of documents) { + if (doc.img && doc.img.startsWith('upload/products/')) { + // Rimuovi il prefisso '/upload/products' dal campo `img` + doc.imagefile = doc.img.replace(/^\upload\/products\//, ''); + doc.img = undefined; // Può anche rimuovere il campo img corrente se desiderato + await doc.save(); // Salva il documento aggiornato + } + } + + console.log(`Updated ${documents.length} document(s) with new imagefile paths.`); + + } else { + const documents = await Product.find({ "productInfo.imagefile": { $exists: true } }); + + // Aggiorna ciascun documento + for (let doc of documents) { + if (doc.imagefile && doc.imagefile.startsWith('upload/products/')) { + // Rimuovi il prefisso '/upload/products' dal campo `img` + doc.imagefile = doc.imagefile.replace(/^\upload\/products\//, ''); + await doc.save(); // Salva il documento aggiornato + } + } + + console.log(`Updated ${documents.length} document(s) with new imagefile paths.`); + + + } + + + // await Product.updateMany({}, { 'vers_img': 0 }); + + console.log(`Updated ${result.modifiedCount} document(s).`); + +}; + + + +module.exports.correggiProductTypes = async function () { + const Product = this; + const bulkOps = []; + + try { + // Fase di aggregazione + const cursor = Product.aggregate([ + { + $project: { + _id: 1, + 'productInfo.productType': 1, + 'productInfo.productTypes': [{ $ifNull: ['$productType', 10] }] + } + } + ]).cursor({ batchSize: 1000 }).exec(); + + // Itera attraverso ogni documento utilizzando il cursore + for await (const doc of cursor) { + bulkOps.push({ + updateOne: { + filter: { _id: doc._id }, + update: { + $set: { 'productInfo.productTypes': doc.productTypes }, + $unset: { 'productInfo.productType': "" } + } + } + }); + + // Scrivi i batch di operazioni ogni 1000 documenti + if (bulkOps.length === 1000) { + await Product.bulkWrite(bulkOps); + bulkOps.length = 0; + } + } + + // Scrivi eventuali operazioni rimanenti + if (bulkOps.length > 0) { + await Produc.bulkWrite(bulkOps); + } + + console.log('ProductInfo.productType converted to productTypes array and saved'); + } catch (err) { + console.error('Error converting ProductInfo.productType:', err); + } +} + +module.exports.updateProductInfoByStats = async function (idapp) { + let mylog = ''; + let mylog2 = ''; + let mylogtot = ''; + try { + const Product = this; + + const T_WEB_ArticoliFatturati = require('./t_web_articolifatturati'); + const T_WEB_Ordini = require('./t_web_ordini'); + + mylog = "Inizio Aggiornamento Statistiche... \n"; + mylogtot += mylog; + console.log(mylog); + + let countUpdate = 0; + + countUpdate = await T_WEB_ArticoliFatturati.updateStatisticsFatt('', idapp, true); + + // Itera sui risultati e aggiorna productInfo + + mylog = `Aggiornati ${countUpdate} record di productInfo`; + mylogtot += mylog; + console.log(mylog); + + mylog2 = "Inizio Aggiornamento Statistiche Ordini ... \n"; + mylogtot += mylog2; + console.log(mylog2); + + countUpdate = await T_WEB_Ordini.updateStatisticsOrders('', idapp, true); + + mylog2 = `Aggiornati ${countUpdate} record di productInfo`; + mylogtot += mylog2; + + console.log(mylog2); + + } catch (error) { + mylog = "Errore durante l'aggiornamento di productInfo:" + error; + console.error(mylog); + } + + return mylogtot; +} + +// crea setImgNotFound + +module.exports.setImgNotFound = async function (id) { + // set sul record id il flag image_not_found + try { + const Product = this; + + await Product.updateOne( + { _id: id }, + { $set: { 'productInfo.image_not_found': true } } + ); + console.log(`Flag image_not_found set for record with id: ${id}`); + } catch (error) { + console.error(`Error setting image_not_found flag for id ${id}:`, error); + } + +} + +// imposta tutti i record con image_not_found: false +module.exports.resetImageNotFound = async function () { + try { + const Product = this; + + await Product.updateMany( + { 'productInfo.image_not_found': true }, + { $set: { image_not_found: false } } + ); + console.log('Flag image_not_found reset to false for all records'); + return true; + } catch (error) { + console.error('Error resetting image_not_found flag:', error); + } + +} + +// crea una funzione che mi rimuove il record "product" che utilizza productInfo, nel caso in cui date_updated_fromGM non esista +module.exports.removeProductInfoWithoutDateUpdatedFromGM = async function (idapp) { + const Product = this; + + const globalTables = require('../tools/globalTables'); + + let mylog; + + try { + const arrproduct = await Product.find({ idapp, 'productInfo.date_updated_fromGM': { $exists: false } }); + + if (arrproduct.length > 0 && arrproduct.length < 1000) { + mylog = `Rimuovo ${arrproduct.length} productInfo senza date_updated_fromGM !!` + console.log(mylog); + + for (const product of arrproduct) { + await Product.updateOne( + { _id: product._id }, + { $set: { deleted: true } } + ); + } + } + + return mylog; + } catch (error) { + mylog += 'Error removing productInfo without date_updated_fromGM:' + error; + console.error(mylog); + } + + return mylog; +}; diff --git a/src/server/models/productInfo.js b/src/server/models/productInfo.js index c60e0f5..cc27d8e 100755 --- a/src/server/models/productInfo.js +++ b/src/server/models/productInfo.js @@ -202,7 +202,7 @@ module.exports.executeQueryTable = function (idapp, params) { return tools.executeQueryTable(this, idapp, params); }; -module.exports.findAllIdApp = async function (idapp, code, id) { +/*module.exports.findAllIdApp = async function (idapp, code, id) { let myfind = {}; let myqueryadd = {}; let query = []; @@ -295,299 +295,9 @@ module.exports.findAllIdApp = async function (idapp, code, id) { console.error('E', e); } -}; - -module.exports.getProductByCode = function (idapp, code) { - return productInfo.findAllIdApp(idapp, code); -} -module.exports.replaceProductImgToImageFile = async function (abilitaserver) { - const ProductInfo = this; - - if (abilitaserver) { - // const result = await ProductInfo.updateMany({ "img": { $exists: true } }, { $rename: { 'img': 'imagefile' } }); - - // Trova tutti i documenti con il campo 'img' che esiste - const documents = await ProductInfo.find({ "img": { $exists: true } }); - - // Aggiorna ciascun documento - for (let doc of documents) { - if (doc.img && doc.img.startsWith('upload/products/')) { - // Rimuovi il prefisso '/upload/products' dal campo `img` - doc.imagefile = doc.img.replace(/^\upload\/products\//, ''); - doc.img = undefined; // Può anche rimuovere il campo img corrente se desiderato - await doc.save(); // Salva il documento aggiornato - } - } - - console.log(`Updated ${documents.length} document(s) with new imagefile paths.`); - - } else { - const documents = await ProductInfo.find({ "imagefile": { $exists: true } }); - - // Aggiorna ciascun documento - for (let doc of documents) { - if (doc.imagefile && doc.imagefile.startsWith('upload/products/')) { - // Rimuovi il prefisso '/upload/products' dal campo `img` - doc.imagefile = doc.imagefile.replace(/^\upload\/products\//, ''); - await doc.save(); // Salva il documento aggiornato - } - } - - console.log(`Updated ${documents.length} document(s) with new imagefile paths.`); +};*/ - } - - - await ProductInfo.updateMany({}, { 'vers_img': 0 }); - - console.log(`Updated ${result.modifiedCount} document(s).`); - -}; - -/** - * @typedef {Object} Article - * @property {bigint} Id - * @property {number} IdArticolo - * @property {string} Ean13 - * @property {string} Titolo - * @property {string} ListaAutori - * @property {string} ListaArgomenti - * @property {number} IdStatoProdotto - * @property {number} PrezzoIvato - * @property {number} IdMarchioEditoriale - * @property {number} IdCollana - * @property {Date} DataPubblicazione - * @property {number} IdTipologia - * @property {number} IdTipoFormato - * @property {string} Misure - * @property {string} Pagine - * @property {string} Sottotitolo - * @property {string} Durata - * @property {string} Numero - * @property {string} Edizione - * @property {string} Ristampa - * @property {Date} DataInizioCampagna - * @property {Date} DataFineCampagna - * @property {number} ScontoCampagna - * @property {number} PrezzoIvatoScontatoCampagna - * @property {Date} DataOra - * @property {boolean} Enabled - * @property {number} IDTagGruppo - * @property {string} Utente - * @property {number} PercIva - * @property {number} IdTitoloOriginale - * @property {boolean} EnabledAlFresco - * @property {number} CodEdizione - * @property {string} FasciaEta - * @property {string} DescrizioneStatoProdotto - * @property {string} DescrizioneTipologia - * @property {string} DescrizioneFormato - * @property {string} DescrizioneCollana - * @property {string} DescrArgomento - * @property {string} AutoriCompleti - * @property {string} CasaEditrice - */ - -/** - * Aggiorna il prodotto basandosi su un articolo - * @param {Article} article - Dati dell'articolo da aggiornare - * @param {boolean} creanew - * @returns {Promise} - */ -module.exports.aggiornaProductFromGMArticle = async function (article, creanew) { - - const ProductInfo = this; - - try { - if (article) { - // cerca se esiste sul db locale - - let findrec = this.find({ sku: article.IdArticolo }).lean(); - if (findrec) { - // Articolo Trovato ! - } else { - // articolo inesistente, lo vuoi creare ? - if (creanew) { - findrec = null; - } - } - - if (findrec) { - - } - } - - } catch (e) { - console.error('Error aggiornaProductFromGMArticle:', err); - } -}; - -module.exports.correggiProductTypes = async function () { - const ProductInfo = this; - const bulkOps = []; - - try { - // Fase di aggregazione - const cursor = ProductInfo.aggregate([ - { - $project: { - _id: 1, - productType: 1, - productTypes: [{ $ifNull: ['$productType', 10] }] - } - } - ]).cursor({ batchSize: 1000 }).exec(); - - // Itera attraverso ogni documento utilizzando il cursore - for await (const doc of cursor) { - bulkOps.push({ - updateOne: { - filter: { _id: doc._id }, - update: { - $set: { productTypes: doc.productTypes }, - $unset: { productType: "" } - } - } - }); - - // Scrivi i batch di operazioni ogni 1000 documenti - if (bulkOps.length === 1000) { - await ProductInfo.bulkWrite(bulkOps); - bulkOps.length = 0; - } - } - - // Scrivi eventuali operazioni rimanenti - if (bulkOps.length > 0) { - await ProductInfo.bulkWrite(bulkOps); - } - - console.log('ProductInfo.productType converted to productTypes array and saved'); - } catch (err) { - console.error('Error converting ProductInfo.productType:', err); - } -} - -module.exports.updateProductInfoByStats = async function (idapp) { - let mylog = ''; - let mylog2 = ''; - let mylogtot = ''; - try { - const ProductInfo = this; - - const T_WEB_ArticoliFatturati = require('./t_web_articolifatturati'); - const T_WEB_Ordini = require('./t_web_ordini'); - - mylog = "Inizio Aggiornamento Statistiche... \n"; - mylogtot += mylog; - console.log(mylog); - - let countUpdate = 0; - - countUpdate = await T_WEB_ArticoliFatturati.updateStatisticsFatt('', idapp, true); - - // Itera sui risultati e aggiorna productInfo - - mylog = `Aggiornati ${countUpdate} record di productInfo`; - mylogtot += mylog; - console.log(mylog); - - mylog2 = "Inizio Aggiornamento Statistiche Ordini ... \n"; - mylogtot += mylog2; - console.log(mylog2); - - countUpdate = await T_WEB_Ordini.updateStatisticsOrders('', idapp, true); - - mylog2 = `Aggiornati ${countUpdate} record di productInfo`; - mylogtot += mylog2; - - console.log(mylog2); - - } catch (error) { - mylog = "Errore durante l'aggiornamento di productInfo:" + error; - console.error(mylog); - } - - return mylogtot; -} - -// crea setImgNotFound - -module.exports.setImgNotFound = async function (id) { - // set sul record id il flag image_not_found - try { - const ProductInfo = this; - - await ProductInfo.updateOne( - { _id: id }, - { $set: { image_not_found: true } } - ); - console.log(`Flag image_not_found set for record with id: ${id}`); - } catch (error) { - console.error(`Error setting image_not_found flag for id ${id}:`, error); - } - -} - -// imposta tutti i record con image_not_found: false -module.exports.resetImageNotFound = async function () { - try { - const ProductInfo = this; - - await ProductInfo.updateMany( - { image_not_found: true }, - { $set: { image_not_found: false } } - ); - console.log('Flag image_not_found reset to false for all records'); - return true; - } catch (error) { - console.error('Error resetting image_not_found flag:', error); - } - -} - -// crea una funzione che mi rimuove il record "product" che utilizza productInfo, nel caso in cui date_updated_fromGM non esista -module.exports.removeProductInfoWithoutDateUpdatedFromGM = async function (idapp) { - const ProductInfo = this; - - const globalTables = require('../tools/globalTables'); - const Product = globalTables.getTableByTableName('Product'); - - let mylog; - - try { - const arrproductInfo = await ProductInfo.find({ idapp, date_updated_fromGM: { $exists: false } }); - - if (arrproductInfo.length > 0 && arrproductInfo.length < 1000) { - mylog = `Rimuovo ${arrproductInfo.length} productInfo senza date_updated_fromGM !!` - console.log(mylog); - - for (const productinfo of arrproductInfo) { - // cerca nella tabella Product se esiste idProductInfo = _id e cancella tutti i record che hanno questa corrispondenza - if (Product) { - await Product.updateMany( - { idProductInfo: productinfo._id }, - { $set: { deleted: true } } - ); - } - - // Ora rimuovi anche questo productInfo - await ProductInfo.updateOne( - { _id: productinfo._id }, - { $set: { deleted: true } } - ); - } - } - - return mylog; - } catch (error) { - mylog += 'Error removing productInfo without date_updated_fromGM:' + error; - console.error(mylog); - } - - return mylog; -}; module.exports.createIndexes() .then(() => { }) diff --git a/src/server/models/publisher.js b/src/server/models/publisher.js index f6fafef..893ac2c 100755 --- a/src/server/models/publisher.js +++ b/src/server/models/publisher.js @@ -55,9 +55,9 @@ module.exports.getEditoriWithTitleCount = async function (idapp, updatedata) { { $match: { idapp } }, { $lookup: { - from: 'productinfos', // Nome della tua collezione productInfo + from: 'products', // Nome della tua collezione productInfo localField: '_id', - foreignField: 'idPublisher', + foreignField: 'productInfo.idPublisher', as: 'products' } }, diff --git a/src/server/models/t_web_articolifatturati.js b/src/server/models/t_web_articolifatturati.js index eeddeee..2d3f5aa 100755 --- a/src/server/models/t_web_articolifatturati.js +++ b/src/server/models/t_web_articolifatturati.js @@ -1,6 +1,5 @@ const mongoose = require('mongoose'); -const ProductInfo = require('../models/productInfo'); // Definizione dello schema const articoliFatturatiSchema = new mongoose.Schema({ @@ -166,18 +165,18 @@ module.exports.updateStatisticsFatt = async function (CodArticolo, idapp, update if (update) { for (const stat of statistics) { - const result = await ProductInfo.updateOne( + const result = await Product.updateOne( { - sku: stat.sku, - idapp + idapp, + 'productInfo.sku': stat.sku, }, // Cerca il documento con lo stesso sku { $set: { - fatLast3M: stat.fatLast3M, - fatLast6M: stat.fatLast6M, - fatLast1Y: stat.fatLast1Y, - fatLast2Y: stat.fatLast2Y, - totFat: stat.totFat, + 'productInfo.fatLast3M': stat.fatLast3M, + 'productInfo.fatLast6M': stat.fatLast6M, + 'productInfo.fatLast1Y': stat.fatLast1Y, + 'productInfo.fatLast2Y': stat.fatLast2Y, + 'productInfo.totFat': stat.totFat, } }, { upsert: false } // Non crea il documento se non esiste diff --git a/src/server/models/t_web_ordini.js b/src/server/models/t_web_ordini.js index 29274b0..ea15d11 100755 --- a/src/server/models/t_web_ordini.js +++ b/src/server/models/t_web_ordini.js @@ -18,8 +18,6 @@ PrimaCopiaDaSpedire - int () const mongoose = require('mongoose'); -const ProductInfo = require('../models/productInfo'); - // Definizione dello schema const ordiniSchema = new mongoose.Schema({ Codice: { @@ -168,18 +166,18 @@ module.exports.updateStatisticsOrders = async function (CodArticoloGM, idapp, up if (update) { for (const stat of statistics) { - const result = await ProductInfo.updateOne( + const result = await Product.updateOne( { - sku: stat.sku, + 'productInfo.sku': stat.sku, idapp, }, // Cerca il documento con lo stesso sku { $set: { - totVen: stat.totVen, - vLast3M: stat.vLast3M, - vLast6M: stat.vLast6M, - vLast1Y: stat.vLast1Y, - vLast2Y: stat.vLast2Y, + 'productInfo.totVen': stat.totVen, + 'productInfo.vLast3M': stat.vLast3M, + 'productInfo.vLast6M': stat.vLast6M, + 'productInfo.vLast1Y': stat.vLast1Y, + 'productInfo.vLast2Y': stat.vLast2Y, } }, { upsert: false } // Non crea il documento se non esiste diff --git a/src/server/modules/CronMod.js b/src/server/modules/CronMod.js index c1bdd43..928d0ad 100644 --- a/src/server/modules/CronMod.js +++ b/src/server/modules/CronMod.js @@ -108,10 +108,10 @@ class CronMod { await CatProd.deleteMany({ idapp }); await SubCatProd.deleteMany({ idapp }); } else if (mydata.dbop === 'removeProductInfoWithoutDateUpdatedFromGM') { - mystr = await ProductInfo.removeProductInfoWithoutDateUpdatedFromGM(idapp); + mystr = await Product.removeProductInfoWithoutDateUpdatedFromGM(idapp); ris = { mystr }; } else if (mydata.dbop === 'resetImageNotFound') { - mystr = await ProductInfo.resetImageNotFound(); + mystr = await Product.resetImageNotFound(); ris = { mystr }; } else if (mydata.dbop === 'StatMacro') { const macro = new Macro(idapp, {}); @@ -220,7 +220,7 @@ class CronMod { mystr = await CatProd.updateCatDeleteEmpty(req.body.idapp); ris = { mystr }; } else if (mydata.dbop === 'UpdateStatFatturato') { - mystr = await ProductInfo.updateProductInfoByStats(req.body.idapp); + mystr = await Product.updateProductInfoByStats(req.body.idapp); ris = { mystr }; } else if (mydata.dbop === 'MigrateMSSQLToMongoDb') { const { mssqlmigrateTables } = require('../controllers/articleController'); @@ -464,11 +464,11 @@ class CronMod { await Circuit.createCircuitIfNotExist(req, idapp, recprov.prov); } } else if (mydata.dbop === 'correggiProductTypes') { - await ProductInfo.correggiProductTypes(); + await Product.correggiProductTypes(); } else if (mydata.dbop === 'replaceProductImgToImageFile') { - await ProductInfo.replaceProductImgToImageFile(true); + await Product.replaceProductImgToImageFile(true); } else if (mydata.dbop === 'removeUploadProducts_Path') { - await ProductInfo.replaceProductImgToImageFile(false); + await Product.replaceProductImgToImageFile(false); } else if (mydata.dbop === 'correggiCircuitiANull') { await User.updateMany({}, { $pull: { 'profile.mycircuits': { circuitname: null } } }); } else if (mydata.dbop === 'ImpostaMinMaxPersonali') { diff --git a/src/server/modules/Macro.js b/src/server/modules/Macro.js index 023aabf..8a3028a 100644 --- a/src/server/modules/Macro.js +++ b/src/server/modules/Macro.js @@ -1,6 +1,5 @@ const Importamacro = require('../models/importamacro'); // Assicurati di avere i modelli corretti const ImportaIsbn = require('../models/importaisbn'); -const ProductInfo = require('../models/productInfo'); const Product = require('../models/product'); const CatProd = require('../models/catprod'); const SubCatProd = require('../models/subcatprod'); @@ -444,13 +443,13 @@ class Macro { let count = 0; if (Array.isArray(recproducts)) { if (recproducts.length > 10 && lavoromassivo && options.rimuovieventualiCancellati) { - // rimuovi dalla tabella productInfo tutti i campi date_updated_fromGM - const result = await ProductInfo.updateMany( + // disattiva dalla tabella productInfo tutti i campi date_updated_fromGM + const result = await Product.updateMany( { idapp: options.idapp }, - { $unset: { date_updated_fromGM: null } } + { $unset: { 'productInfo.date_updated_fromGM': null } } ); let quanti_rimossi = result.modifiedCount; - console.log(`Sbianca date_updated_fromGM da ProductInfo: (${quanti_rimossi} su ${result.matchedCount})`); + console.log(`Sbianca date_updated_fromGM da Product: (${quanti_rimossi} su ${result.matchedCount})`); rimuoviTabellePerIniziare = true; } @@ -634,7 +633,7 @@ class Macro { if (!product.title || !product.sku) importa = false; if (importa) { - const productInfo = this.preparaProductInfo(product); + product.productInfo = this.preparaProductInfo(product); if (this.localoptions?.importadaFDV) { const recrankingisbn = await ImportaIsbn.findOne({ sku: product.sku }).lean(); @@ -647,12 +646,12 @@ class Macro { product.active = true; } - await this.gestisciCategorie(productInfo, product); - await this.gestisciAutori(productInfo, product); - await this.gestisciEditore(productInfo, product); - await this.gestisciCollana(productInfo, product); + await this.gestisciCategorie(product); + await this.gestisciAutori(product); + await this.gestisciEditore(product); + await this.gestisciCollana(product); - const risrecInfo = await ProductInfo.findOneAndUpdate( + const risrecInfo = await Product.findOneAndUpdate( { code: productInfo.code }, { $set: productInfo }, { new: true, upsert: true, returnOriginal: false } @@ -705,7 +704,6 @@ class Macro { preparaProductInfo(product) { try { return { - idapp: product.idapp, code: product.isbn, id_wp: product._id || undefined, sku: product.sku, @@ -869,10 +867,10 @@ class Macro { /** * Gestisce le categorie e sottocategorie del prodotto. */ - async gestisciCategorie(productInfo, product) { + async gestisciCategorie(product) { try { if (product.DescrArgomento) { - productInfo.idCatProds = []; + product.productInfo.idCatProds = []; const reccateg = await CatProd.findOne({ idapp: this.idapp, name: product.DescrArgomento }); let nuovaCategoria = null; if (!reccateg) { @@ -892,12 +890,12 @@ class Macro { const myriscat = reccateg?._id || (nuovaCategoria ? nuovaCategoria._id : null); - if (myriscat) productInfo.idCatProds.push(myriscat); + if (myriscat) product.productInfo.idCatProds.push(myriscat); } else { if (product.categories) { // const arrcat = product.categories.trim().split(','); const arrcat = product.categories.trim().split(','); - productInfo.idCatProds = []; + product.productInfo.idCatProds = []; for (const mycat of arrcat) { const mycatstr = mycat.trim(); @@ -910,7 +908,7 @@ class Macro { } const myriscat = reccateg?._id || (nuovaCategoria ? nuovaCategoria._id : null); - if (myriscat) productInfo.idCatProds.push(myriscat); + if (myriscat) product.productInfo.idCatProds.push(myriscat); } } } @@ -922,13 +920,13 @@ class Macro { /** * Gestisce gli autori del prodotto. */ - async gestisciAutori(productInfo, product) { + async gestisciAutori(product) { if (product.Autore) { let arrAuthor = []; if (product.id_wp) arrAuthor = this.estraiAutori_FDV(product.Autore); else arrAuthor = this.estraiAutori(product.Autore); - productInfo.idAuthors = []; + product.productInfo.idAuthors = []; for (const author of arrAuthor) { const recauthor = await Author.findOne({ @@ -944,7 +942,7 @@ class Macro { } const myrisautore = recauthor?._id || (nuovoAutore ? nuovoAutore._id : ''); - if (myrisautore) productInfo.idAuthors.push(myrisautore); + if (myrisautore) product.productInfo.idAuthors.push(myrisautore); } } } @@ -995,9 +993,9 @@ class Macro { /** * Gestisce l'editore del prodotto. */ - async gestisciEditore(productInfo, product) { - if (productInfo.publisher) { - const publisher = productInfo.publisher.trim(); + async gestisciEditore(product) { + if (product.productInfo.publisher) { + const publisher = product.productInfo.publisher.trim(); const recpublisher = await Publisher.findOne({ idapp: this.idapp, name: publisher }).lean(); let nuovoEditore = null; @@ -1009,14 +1007,14 @@ class Macro { return; } } - if (recpublisher?._id || nuovoEditore?._id) productInfo.idPublisher = recpublisher?._id || nuovoEditore._id; + if (recpublisher?._id || nuovoEditore?._id) product.productInfo.idPublisher = recpublisher?._id || nuovoEditore._id; } } /** * Gestisce la collana del prodotto. */ - async gestisciCollana(productInfo, product) { + async gestisciCollana(product) { if (product.collezione && product.numCollana) { const collana = product.collezione.trim(); const reccollana = await Collana.findOne({ idapp: this.idapp, title: collana }).lean(); @@ -1030,17 +1028,17 @@ class Macro { return; } } - if (reccollana?._id || nuovaCollana?._id) productInfo.idCollana = reccollana?._id || nuovaCollana._id; + if (reccollana?._id || nuovaCollana?._id) product.productInfo.idCollana = reccollana?._id || nuovaCollana._id; } } /** * Aggiorna l'immagine se necessario. */ - async aggiornaImmagineSeNecessario(productInfo) { - const { prodInfo, aggiornatoimg } = await tools.downloadImgIfMissing(productInfo); + async aggiornaImmagineSeNecessario(product) { + const { prodInfo, aggiornatoimg } = await tools.downloadImgIfMissing(product); if (aggiornatoimg) { - await ProductInfo.findOneAndUpdate({ code: productInfo.code }, { $set: prodInfo }); + await Product.findOneAndUpdate({ _id: product._id }, { $set: { productInfo: prodInfo } }); } return aggiornatoimg; diff --git a/src/server/modules/Scraping.js b/src/server/modules/Scraping.js index 23e49cc..b983c4f 100644 --- a/src/server/modules/Scraping.js +++ b/src/server/modules/Scraping.js @@ -2,7 +2,6 @@ const axios = require('axios'); const cheerio = require('cheerio'); const Product = require('../models/product'); -const ProductInfo = require('../models/productInfo'); const tools = require('../tools/general'); const shared_consts = require('../tools/shared_nodejs'); @@ -96,9 +95,9 @@ class AmazonBookScraper { } } - getTitleByProductInfo(productInfo) { + getTitleByProduct(product) { try { - return productInfo?.name.trim(); + return product?.productInfo.name.trim(); } catch (e) { return ''; } @@ -107,9 +106,9 @@ class AmazonBookScraper { async extractData(myproduct, html, url, isbn10) { const $ = cheerio.load(html); - const productInfo = await ProductInfo.findOne({ _id: myproduct.idProductInfo }).lean(); + const product = await Product.findOne({ _id: myproduct._id }).lean(); - const title_ondb = this.getTitleByProductInfo(productInfo); + const title_ondb = this.getTitleByProduct(product); // Titolo let title = $('#productTitle').text().trim() || null; @@ -247,6 +246,7 @@ class AmazonBookScraper { async scrapeISBN(myproduct, isbn, options) { try { + const product = await Product.findOne({ _id: myproduct._id }).lean(); const datastored = await this.findRecordMyScrapingBookByIsbn(isbn); let data = null; @@ -289,7 +289,6 @@ class AmazonBookScraper { if (index < 0) index = 0; } - const productInfo = {}; let aggiornaDataPubb = false; let aggiornaPages = false; @@ -325,17 +324,17 @@ class AmazonBookScraper { } // Determina se aggiornare data pubblicazione - const currentDatePub = myproduct.idProductInfo.date_pub; + const currentDatePub = myproduct.productInfo.date_pub; aggiornaDataPubb = (!options.aggiornasoloSeVuoti || !tools.isDateValid(currentDatePub)) && tools.isDateValid(data.data_pubblicazione); if (aggiornaDataPubb && data.data_pubblicazione) { - productInfo.date_pub = new Date(data.data_pubblicazione); + product.productInfo.date_pub = new Date(data.data_pubblicazione); } - aggiornaSottotitolo = (!options.aggiornasoloSeVuoti || !myproduct.idProductInfo.sottotitolo) && data.sottotitolo; + aggiornaSottotitolo = (!options.aggiornasoloSeVuoti || !myproduct.productInfo.sottotitolo) && data.sottotitolo; if (aggiornaSottotitolo && data.sottotitolo) { - productInfo.sottotitolo = data.sottotitolo; + product.productInfo.sottotitolo = data.sottotitolo; } aggiornaSottotitolo = false; // !! PER ORA LO DISATTIVO PERCHE' non esiste sempre il sottotitolo in un libro. @@ -373,9 +372,9 @@ class AmazonBookScraper { if (aggiornaProductInfo) { // Aggiorna productInfo se contiene dati if (!tools.isObjectEmpty(productInfo)) { - risupdate = await ProductInfo.findOneAndUpdate( - { _id: myproduct.idProductInfo }, - { $set: productInfo }, + risupdate = await Product.findOneAndUpdate( + { _id: myproduct._id }, + { $set: { productInfo: product.productInfo } }, { new: true, upsert: true, includeResultMetadata: true } ).lean(); } @@ -384,7 +383,7 @@ class AmazonBookScraper { const concatenatedProduct = { ...recModificato, - ...productInfo, + ...product.productInfo, }; if (updated) { diff --git a/src/server/router/admin_router.js b/src/server/router/admin_router.js index 1dcedd8..5c3a129 100755 --- a/src/server/router/admin_router.js +++ b/src/server/router/admin_router.js @@ -17,7 +17,6 @@ const Inventariogm = require('../models/inventariogm'); const Importamacro = require('../models/importamacro'); const ImportaDescr = require('../models/importadescr'); const ImportaIsbn = require('../models/importaisbn'); -const ProductInfo = require('../models/productInfo'); const CatProd = require('../models/catprod'); const Collana = require('../models/collana'); const Author = require('../models/author'); @@ -72,7 +71,7 @@ function launchGenPdfIfNeeded() { } } -async function updateProductInfo(recproductInfoAttuale, product, idapp, mycatstr) { +/*async function updateProductInfo(recproductInfoAttuale, product, idapp, mycatstr) { if (!recproductInfoAttuale || !mycatstr) return recproductInfoAttuale; let idArgomentoNum = null; @@ -93,7 +92,7 @@ async function updateProductInfo(recproductInfoAttuale, product, idapp, mycatstr } return productInfo; -} +}*/ async function findOrCreateCatProd(idapp, idArgomento, DescrArgomento) { let reccatprod = null; @@ -1240,28 +1239,28 @@ router.post('/import', authenticate, async (req, res) => { code: product.code, }; - const myproductInfo = await ProductInfo.findOne({ code: productInfo.code }); + const myproduct = await Product.findOne({ 'productInfo.code': productInfo.code }); // IMPOSTA I VALORI SOLO SE NON ESISTONO ! ALTRIMENTI LASCIA QUELLI GIA' IMPORTATI (O MODIFICATI) if (getvalueByJsonText(product.url)) { - if ((myproductInfo && !myproductInfo.link_macro) || !myproductInfo) + if ((myproduct && !myproduct.productInfo.link_macro) || !myproduct.productInfo) productInfo.link_macro = getvalueByJsonText(product.url); } if (getvalueByJsonText(product.descrizione)) { - if ((myproductInfo && !myproductInfo.descrizione_breve_macro) || !myproductInfo) + if ((myproduct && !myproduct.productInfo.descrizione_breve_macro) || !myproduct.productInfo) productInfo.descrizione_breve_macro = getvalueByJsonText(product.descrizione); } if (getvalueByJsonText(product.descrizione_completa)) { - if ((myproductInfo && !myproductInfo.descrizione_completa_macro) || !myproductInfo) + if ((myproduct && !myproduct.productInfo.descrizione_completa_macro) || !myproduct.productInfo) productInfo.descrizione_completa_macro = getvalueByJsonText(product.descrizione_completa); } if (getvalueByJsonText(product.sottotitolo)) { - if ((myproductInfo && !myproductInfo.sottotitolo) || !myproductInfo) + if ((myproduct && !myproduct.productInfo.sottotitolo) || !myproduct.productInfo) productInfo.sottotitolo = getvalueByJsonText(product.sottotitolo); } if (getvalueByJsonText(product.titolo)) { - if ((myproductInfo && !myproductInfo.name) || !myproductInfo) + if ((myproduct && !myproduct.productInfo.name) || !myproduct.productInfo) productInfo.name = getvalueByJsonText(product.titolo); } @@ -1520,27 +1519,27 @@ router.post('/import', authenticate, async (req, res) => { let imported = 0; let errors = 0; - for (const product of dataObjects) { + for (const productImported of dataObjects) { let isnuovo = false; let setta = false; let productInfo = { - idapp: product.idapp, - code: product.code, - name: product.name, - link: product.link, + idapp: productImported.idapp, + code: productImported.code, + name: productImported.name, + link: productImported.link, idCatProds: [], idSubCatProds: [], // img: 'upload/products/' + product.code + '.jpg', - imagefile: product.code + '.jpg', - weight: product.weight, - unit: tools.getIdUnitsByText(product.unit), + imagefile: productImported.code + '.jpg', + weight: productImported.weight, + unit: tools.getIdUnitsByText(productImported.unit), productTypes: shared_consts.PRODUCTTYPE.PRODUCT, }; let reccateg = null; - if (product.cat_name) { - arrcat = product.cat_name.trim().split(','); + if (productImported.cat_name) { + arrcat = productImported.cat_name.trim().split(','); for (const mycat of arrcat) { let mycatstr = mycat.trim(); @@ -1559,8 +1558,8 @@ router.post('/import', authenticate, async (req, res) => { } } - if (product.subcat_name) { - arrsubcat = product.subcat_name.trim().split(','); + if (productImported.subcat_name) { + arrsubcat = productImported.subcat_name.trim().split(','); productInfo.idSubCatProds = []; for (const mysubcat of arrsubcat) { let mysubcatstr = mysubcat.trim(); @@ -1581,24 +1580,26 @@ router.post('/import', authenticate, async (req, res) => { } } - if (!product.hasOwnProperty('active')) { - product.active = true; + if (!productImported.hasOwnProperty('active')) { + productImported.active = true; } - if (product.code) delete product.code; + /*if (product.code) delete product.code; if (product.name) delete product.name; - if (product.link) delete product.link; + if (product.link) delete product.link;*/ - let esisteindb = await ProductInfo.findOne({ code: productInfo.code }).lean(); + let esisteindb = await Product.findOne({ 'productInfo.code': productInfo.code }).lean(); // Update ProductInfo - let risrecInfo = await ProductInfo.findOneAndUpdate( - { code: productInfo.code }, - { $set: productInfo }, + let risrecInfo = await Product.findOneAndUpdate( + { 'productInfo.code': productInfo.code }, + { $set: { productInfo: productInfo } }, { new: true, upsert: true } ); + + // .... ANDARE AVANTI DA QUI... .productInfo.... SISTEMARE! if (risrecInfo) { - product.idProductInfo = risrecInfo._id; + productImported.productInfo = risrecInfo._id; recnewInfo = await ProductInfo.findOne({ code: productInfo.code }).lean(); @@ -1613,20 +1614,20 @@ router.post('/import', authenticate, async (req, res) => { // Cerca il GAS let recGas = null; - if (product.gas_name) { + if (productImported.gas_name) { // Cerca il GAS - recGas = await Gasordine.findOne({ idapp, name: product.gas_name }).lean(); + recGas = await Gasordine.findOne({ idapp, name: productImported.gas_name }).lean(); } - if (!recGas && !!product.gas_name) { - recGas = new Gasordine({ idapp, name: product.gas_name, active: true }); + if (!recGas && !!productImported.gas_name) { + recGas = new Gasordine({ idapp, name: productImported.gas_name, active: true }); // Non esiste questo GAS, quindi lo creo ! ris = await recGas.save(); - recGas = await Gasordine.findOne({ idapp, name: product.gas_name }).lean(); + recGas = await Gasordine.findOne({ idapp, name: productImported.gas_name }).lean(); } let recProductExist = null; - let queryprod = { idProductInfo: product.idProductInfo }; + let queryprod = { idProductInfo: productImported.idProductInfo }; if (recGas) { queryprod = { ...queryprod, idGasordine: recGas._id }; @@ -1639,22 +1640,22 @@ router.post('/import', authenticate, async (req, res) => { } if (!options.aggiornaStockQty && esisteindb && !isnuovo) { - delete product.stockQty; - delete product.maxbookableGASQty; + delete productImported.stockQty; + delete productImported.maxbookableGASQty; } // AGGIORNA PRODUCT - let risrec = await Product.findOneAndUpdate(queryprod, { $set: product }, { new: true, upsert: true }); + let risrec = await Product.findOneAndUpdate(queryprod, { $set: productImported }, { new: true, upsert: true }); let recnew = await Product.findOne(queryprod).lean(); if (risrec) { if (risrec._id) { // Record existed, so it was updated - let arrfieldchange = tools.differentObjects(product, recnew); + let arrfieldchange = tools.differentObjects(productImported, recnew); if (arrfieldchange.length > 0) { updated++; - console.log('Changed:', product.idProductInfo + ': ' + arrfieldchange); + console.log('Changed:', productImported.idProductInfo + ': ' + arrfieldchange); } } else { // Record didn't exist, so it was created @@ -1662,13 +1663,13 @@ router.post('/import', authenticate, async (req, res) => { } } else { // risrec is null or undefined, indicating an error - console.error('Error: ', product.productInfo.name); + console.error('Error: ', productImported.productInfo.name); errors++; } await Product.singlerecconvert_AfterImport_AndSave(idapp, recnew, isnuovo); } else { - console.error('Error ProductInfo: ', product.code); + console.error('Error ProductInfo: ', productImported.code); errors++; } } @@ -1871,6 +1872,7 @@ router.post('/import', authenticate, async (req, res) => { return res.status(400).send(); }); +/* async function importaCatalogo(data) { let updated = 0; let imported = 0; @@ -2059,11 +2061,6 @@ async function importaCatalogo(data) { productInfo.productTypes.push(vers); } - /*if (product.Data) { - productInfo.date_pub = new Date(product.Data * 1000); - // convert data to timestamp - productInfo.date_pub_ts = productInfo.date_pub.getTime(); - }*/ productInfo.name = productInfo.name.replace( / - Usato$| - Nuovo$| - Epub$| - Ebook$| - Mobi$| - DVD$| - Streaming$| - Download$/, @@ -2113,7 +2110,7 @@ async function importaCatalogo(data) { } if (reccateg) { - productInfo.idCatProds.push(reccateg._id); + product.productInfo.idCatProds.push(reccateg._id); } } } @@ -2149,7 +2146,7 @@ async function importaCatalogo(data) { } catch (e) {} } } - productInfo.idAuthors = []; + product.productInfo.idAuthors = []; for (const myauthor of arrAuthor) { // Cerca l'Autore @@ -2162,7 +2159,7 @@ async function importaCatalogo(data) { } if (recauthor) { - productInfo.idAuthors.push(recauthor._id); + product.productInfo.idAuthors.push(recauthor._id); } } } catch (e) { @@ -2173,7 +2170,7 @@ async function importaCatalogo(data) { if (product.subcat_name) { arrsubcat = product.subcat_name.trim().split(','); - productInfo.idSubCatProds = []; + product.productInfo.idSubCatProds = []; for (const mysubcat of arrsubcat) { let mysubcatstr = mysubcat.trim(); @@ -2188,13 +2185,13 @@ async function importaCatalogo(data) { } if (recsubcateg) { - productInfo.idSubCatProds.push(recsubcateg._id); + product.productInfo.idSubCatProds.push(recsubcateg._id); } } } - if (productInfo.publisher) { + if (product.productInfo.publisher) { try { - publisher = productInfo.publisher.trim(); + publisher = product.productInfo.publisher.trim(); // Cerca la Sotto Categoria let recpublisher = await Publisher.findOne({ idapp, name: publisher }).lean(); if (!recpublisher) { @@ -2205,7 +2202,7 @@ async function importaCatalogo(data) { } if (recpublisher) { - productInfo.idPublisher = recpublisher._id; + product.productInfo.idPublisher = recpublisher._id; } } catch (e) { console.error(e); @@ -2213,19 +2210,19 @@ async function importaCatalogo(data) { } // Aggiorna la collana solo se non è stata già impostata nel record attuale //if (recproductInfoAttuale && !recproductInfoAttuale.idCollana && product.DescrizioneCollana) { - if (productInfo.collezione && productInfo.numCollana) { + if (product.productInfo.collezione && product.productInfo.numCollana) { reccollana = await Collana.findOne({ idapp, title: collezione }).lean(); if (!reccollana) { try { // Non esiste questa collana, quindi la creo ! - reccollana = new Collana({ idapp, idCollana: productInfo.numCollana, title: product.DescrizioneCollana }); + reccollana = new Collana({ idapp, idCollana: product.productInfo.numCollana, title: product.DescrizioneCollana }); ris = await reccoll.save(); } catch (e) { console.error('Err', e); } } - if (reccollana) productInfo.idCollana = reccollana._id; + if (reccollana) product.productInfo.idCollana = reccollana._id; } if (!product.hasOwnProperty('active')) { @@ -2497,7 +2494,7 @@ async function importaCatalogo(data) { console.log(e.message); return res.status(400).send(e); } -} +}*/ router.post('/exec', authenticate, async (req, res) => { try { diff --git a/src/server/router/api_router.js b/src/server/router/api_router.js index d7bf709..d7bdd05 100644 --- a/src/server/router/api_router.js +++ b/src/server/router/api_router.js @@ -10,7 +10,6 @@ const XLSX = require('xlsx'); const upload = multer({ dest: 'uploads/' }); const Product = require('../models/product'); -const ProductInfo = require('../models/productInfo'); const Author = require('../models/author'); const tools = require('../tools/general'); @@ -370,8 +369,8 @@ router.post('/search-books', authenticate, async (req, res) => { // Cerca il primo record che corrisponde per ISBN o titolo if (true) { if (!trovatoISBN) { - let productInfoarrISBN = await ProductInfo.find({ - code: field.toUpperCase(), + let productInfoarrISBN = await Product.find({ + 'productInfo.code': field.toUpperCase(), $or: [{ deleted: false }, { deleted: { $exists: false } }], }).exec(); @@ -384,33 +383,33 @@ router.post('/search-books', authenticate, async (req, res) => { } if (!trovatoISBN && !trovato) { // Prima cerca se è esattamente cosi - let productInfoarrTitle = await ProductInfo.find({ + let productarrTitle = await Product.find({ $or: [{ deleted: false }, { deleted: { $exists: false } }], - name: field, + 'productInfo.name': field, }).exec(); - if (productInfoarrTitle.length === 1) { - productInfo = productInfoarrTitle[0]; + if (productarrTitle.length === 1) { + productInfo = productarrTitle[0]; trovato = true; } else { - if (productInfoarrTitle.length > 1) { + if (productarrTitle.length > 1) { // Prendi l'Ultimo ! - productInfo = productInfoarrTitle[productInfoarrTitle.length - 1]; + productInfo = productarrTitle[productarrTitle.length - 1]; trovato = true; } } if (!trovato) { // Altrimenti per Titolo - productInfoarrTitle = await ProductInfo.find({ + productarrTitle = await Product.find({ $or: [{ deleted: false }, { deleted: { $exists: false } }], - name: new RegExp(`.*${escapeRegExp(tools.removeAccents(field.toUpperCase()))}.*`, 'i'), + 'productInfo.name': new RegExp(`.*${escapeRegExp(tools.removeAccents(field.toUpperCase()))}.*`, 'i'), }).exec(); - if (productInfoarrTitle.length === 1) { - productInfo = productInfoarrTitle[0]; + if (productarrTitle.length === 1) { + productInfo = productarrTitle[0]; trovato = true; } else { - if (productInfoarrTitle.length > 1) { + if (productarrTitle.length > 1) { // Prendi l'Ultimo ! - productInfo = productInfoarrTitle[productInfoarrTitle.length - 1]; + productInfo = productarrTitle[productarrTitle.length - 1]; trovato = true; } } @@ -426,15 +425,14 @@ router.post('/search-books', authenticate, async (req, res) => { if (product) { const existingResult = results.find((r) => r._id.toString() === product._id.toString()); if (!existingResult) { - let titolo = productInfo.name; + let titolo = product.productInfo.name; results.push({ ...product, - productInfo, _id: product._id, title: titolo, isbn: product.isbn, authors: await Promise.all( - productInfo.idAuthors.map(async (authorId) => { + product.productInfo.idAuthors.map(async (authorId) => { const author = await Author.findById(authorId).exec(); return author ? `${author.name} ${author.surname}`.trim() : ''; }) diff --git a/src/server/router/cart_router.js b/src/server/router/cart_router.js index 99b9f88..86063f0 100755 --- a/src/server/router/cart_router.js +++ b/src/server/router/cart_router.js @@ -526,19 +526,6 @@ router.post('/:userId/gestord', authenticate, async function (req, res, next) { preserveNullAndEmptyArrays: true, }, }, - { - $lookup: { - from: 'productinfos', - localField: 'product.idProductInfo', - foreignField: '_id', - as: 'productInfo', - }, - }, - { - $unwind: { - path: '$productInfo', - }, - }, { $lookup: { from: 'gasordines', @@ -588,13 +575,13 @@ router.post('/:userId/gestord', authenticate, async function (req, res, next) { $group: { _id: '$product._id', name: { - $first: '$productInfo.name', + $first: '$product.productInfo.name', }, weight: { - $first: '$productInfo.weight', + $first: '$product.productInfo.weight', }, unit: { - $first: '$productInfo.unit', + $first: '$product.productInfo.unit', }, price_acquistato: { $first: '$product.price_acquistato', diff --git a/src/server/router/index_router.js b/src/server/router/index_router.js index 7a29c55..34b7181 100755 --- a/src/server/router/index_router.js +++ b/src/server/router/index_router.js @@ -84,7 +84,6 @@ const Collana = require('../models/collana'); const { Catalog } = require('../models/catalog'); const { RaccoltaCataloghi } = require('../models/raccoltacataloghi'); const Publisher = require('../models/publisher'); -const ProductInfo = require('../models/productInfo'); const Scontistica = require('../models/scontistica'); const Department = require('../models/department'); const { Category } = require('../models/category'); @@ -1953,7 +1952,6 @@ async function load(req, res, version = '0') { ? Product.findAllIdApp(idapp, undefined, undefined, req.user ? User.isManager(req.user.perm) : false) : Promise.resolve([]),*/ products: Promise.resolve([]), - // productInfos: version >= 91 ? ProductInfo.findAllIdApp(idapp) : Promise.resolve([]), productInfos: Promise.resolve([]), catprods: version >= 91 ? Product.getArrCatProds(idapp, shared_consts.PROD.BOTTEGA) : Promise.resolve([]), subcatprods: version >= 91 ? SubCatProd.findAllIdApp(idapp) : Promise.resolve([]), diff --git a/src/server/router/users_router.js b/src/server/router/users_router.js index 0ff7ac2..d1e5654 100755 --- a/src/server/router/users_router.js +++ b/src/server/router/users_router.js @@ -34,7 +34,6 @@ const reg = require('../reg/registration'); const { authenticate, authenticate_noerror, authenticate_withUser } = require('../middleware/authenticate'); - const Cart = require('../models/cart'); const CartClass = require('../modules/Cart'); const Product = require('../models/product'); @@ -76,15 +75,12 @@ function getMobileComplete(user) { } router.post('/test1', async (req, res) => { - const user = await User.findOne({ idapp: 1, username: 'paoloar77', }); - await sendemail.sendEmail_Registration(user.lang, user.email, user, - user.idapp, user.linkreg); - + await sendemail.sendEmail_Registration(user.lang, user.email, user, user.idapp, user.linkreg); }); // POST /users @@ -102,7 +98,8 @@ router.post('/', async (req, res) => { 'keyappid', 'lang', 'profile', - 'aportador_solidario']); + 'aportador_solidario', + ]); body.email = body.email.toLowerCase(); const user = new User(body); @@ -113,24 +110,25 @@ router.post('/', async (req, res) => { user.name = user.name.trim(); user.surname = user.surname.trim(); - if ((user.aportador_solidario === 'tuo_username') || (user.aportador_solidario === '{username}')) { + if (user.aportador_solidario === 'tuo_username' || user.aportador_solidario === '{username}') { user.aportador_solidario = 'surya1977'; } // tools.mylog("LANG PASSATO = " + user.lang, "IDAPP", user.idapp); - if (!tools.isAlphaNumericAndSpecialCharacter(body.username) || + if ( + !tools.isAlphaNumericAndSpecialCharacter(body.username) || body.email.length < 6 || - body.username.length < 4 || body.password.length < 5) { + body.username.length < 4 || + body.password.length < 5 + ) { await tools.snooze(5000); console.log('Username non valido in Registrazione: ' + body.username); - res.status(400). - send({ code: server_constants.RIS_CODE_USERNAME_NOT_VALID, msg: '' }); + res.status(400).send({ code: server_constants.RIS_CODE_USERNAME_NOT_VALID, msg: '' }); return 1; } - if (tools.blockwords(body.username) || tools.blockwords(body.name) || - tools.blockwords(body.surname)) { + if (tools.blockwords(body.username) || tools.blockwords(body.name) || tools.blockwords(body.surname)) { // tools.writeIPToBan(user.ipaddr + ': [' + user.username + '] ' + user.name + ' ' + user.surname); await tools.snooze(5000); return res.status(404).send(); @@ -148,8 +146,7 @@ router.post('/', async (req, res) => { nonchiedereverifica = await User.getifRegTokenIsValid(body.idapp, regexpire); } - if (!nonchiedereverifica) - regexpire = ''; + if (!nonchiedereverifica) regexpire = ''; if (!tools.getAskToVerifyReg(body.idapp) || nonchiedereverifica) { // Se non devo chiedere di verificare all'Invitato, allora lo verifico direttamente @@ -169,8 +166,7 @@ router.post('/', async (req, res) => { if (lastrec.date_reg) { let ris = tools.isdiffSecDateLess(lastrec.date_reg, 3); if (ris) { - const msg = user.ipaddr + ': [' + user.username + '] ' + user.name + ' ' + - user.surname; + const msg = user.ipaddr + ': [' + user.username + '] ' + user.name + ' ' + user.surname; tools.writeIPToBan(msg); await User.findOneAndUpdate({ _id: user._id }, { $set: { banIp: true } }); @@ -178,8 +174,7 @@ router.post('/', async (req, res) => { await telegrambot.sendMsgTelegramToTheAdmin(body.idapp, '‼️ BAN: ' + msg, true); await tools.snooze(5000); - res.status(400). - send({ code: server_constants.RIS_CODE_BANIP, msg: '' }); + res.status(400).send({ code: server_constants.RIS_CODE_BANIP, msg: '' }); return 1; } } @@ -204,73 +199,57 @@ router.post('/', async (req, res) => { const trovarec = await User.findByCredentials(user.idapp, user.username, user.password, true); // Check if already esist email or username - exit = await User.findByUsername(user.idapp, user.username). - then((useralreadyexist) => { - if (useralreadyexist) { - - if (tools.getAskToVerifyReg(useralreadyexist.idapp)) { - if (!useralreadyexist.verified_by_aportador && useralreadyexist.profile.teleg_id > 0) { - if (trovarec) { - utentenonancoraVerificato = true; - } + exit = await User.findByUsername(user.idapp, user.username).then((useralreadyexist) => { + if (useralreadyexist) { + if (tools.getAskToVerifyReg(useralreadyexist.idapp)) { + if (!useralreadyexist.verified_by_aportador && useralreadyexist.profile.teleg_id > 0) { + if (trovarec) { + utentenonancoraVerificato = true; } - - } - - if (!utentenonancoraVerificato) { - res.status(400). - send({ - code: server_constants.RIS_CODE_USERNAME_ALREADY_EXIST, - msg: '', - }); - return 1; } } - }); + if (!utentenonancoraVerificato) { + res.status(400).send({ + code: server_constants.RIS_CODE_USERNAME_ALREADY_EXIST, + msg: '', + }); + return 1; + } + } + }); if (!utentenonancoraVerificato) { + if (exit === 1) return; - if (exit === 1) - return; + exit = await User.findByEmail(user.idapp, user.email).then((useralreadyexist) => { + if (useralreadyexist) { + res.status(400).send({ + code: server_constants.RIS_CODE_EMAIL_ALREADY_EXIST, + msg: '', + }); + return 1; + } + }); - exit = await User.findByEmail(user.idapp, user.email). - then((useralreadyexist) => { - if (useralreadyexist) { - res.status(400). - send({ - code: server_constants.RIS_CODE_EMAIL_ALREADY_EXIST, - msg: '', - }); - return 1; - } - - }); - - if (exit === 1) - return; + if (exit === 1) return; let recuser = null; - recuser = await User.findByCellAndNameSurname(user.idapp, user.profile.cell, - user.name, user.surname); - if (recuser && user.name !== '' && user.surname !== '' && - user.profile.cell !== '') { + recuser = await User.findByCellAndNameSurname(user.idapp, user.profile.cell, user.name, user.surname); + if (recuser && user.name !== '' && user.surname !== '' && user.profile.cell !== '') { console.log('UTENTE GIA ESISTENTE:\n'); console.log(user); // User already registered! - res.status(400). - send({ code: server_constants.RIS_CODE_USER_ALREADY_EXIST, msg: '' }); + res.status(400).send({ code: server_constants.RIS_CODE_USER_ALREADY_EXIST, msg: '' }); return 1; } - } let recextra = null; user.aportador_solidario = user.aportador_solidario.trim(); - user.aportador_solidario = user.aportador_solidario.replace('@', ''); let id_aportador = await User.getIdByUsername(user.idapp, user.aportador_solidario); @@ -283,7 +262,6 @@ router.post('/', async (req, res) => { } } - let idMyGroupSite = tools.getidMyGroupBySite(body.idapp); user.idMyGroup = idMyGroupSite ? idMyGroupSite : ''; @@ -294,36 +272,32 @@ router.post('/', async (req, res) => { if (!id_aportador && tools.getAskToVerifyReg(body.idapp)) { // Si sta tentando di registrare una persona sotto che non corrisponde! - let msg = 'Il link di registrazione non sembra risultare valido.
invitante: ' + - user.aportador_solidario + '
username: ' + user.username; + let msg = + 'Il link di registrazione non sembra risultare valido.
invitante: ' + + user.aportador_solidario + + '
username: ' + + user.username; await telegrambot.sendMsgTelegramToTheManagers(user.idapp, msg); - res.status(400). - send({ - code: server_constants.RIS_CODE_USER_APORTADOR_NOT_VALID, - msg: '', - }); + res.status(400).send({ + code: server_constants.RIS_CODE_USER_APORTADOR_NOT_VALID, + msg: '', + }); return 1; } - if (utentenonancoraVerificato) { if (id_aportador) { // Se mi sono registrato ma l'invitante non mi abilita, allora il posso registrarmi nuovamente, con lo stesso username e password, // con un'altro link di un'altro invitante ! - await User.setaportador_solidario(user.idapp, user.username, - user.aportador_solidario); + await User.setaportador_solidario(user.idapp, user.username, user.aportador_solidario); const myuser = await User.findOne({ _id: trovarec._id }); if (myuser) { - await telegrambot.askConfirmationUser(myuser.idapp, shared_consts.CallFunz.REGISTRATION, myuser); const { token, refreshToken } = await myuser.generateAuthToken(req); - res - .header('x-auth', token) - .header('x-refrtok', refreshToken) - .send(myuser); + res.header('x-auth', token).header('x-refrtok', refreshToken).send(myuser); return true; } } @@ -345,57 +319,61 @@ router.post('/', async (req, res) => { return 1; } */ - return user.save().then(async () => { - return User.findByUsername(user.idapp, user.username, false). - then((usertrovato) => { + return user + .save() + .then(async () => { + return User.findByUsername(user.idapp, user.username, false) + .then((usertrovato) => { + // tools.mylog("TROVATO USERNAME ? ", user.username, usertrovato); + if (usertrovato !== null) { + return user.generateAuthToken(req); + } else { + res.status(400).send(); + return 0; + } + }) + .then(async (ris) => { + // tools.mylog("passo il TOKEN: ", token); - // tools.mylog("TROVATO USERNAME ? ", user.username, usertrovato); - if (usertrovato !== null) { - return user.generateAuthToken(req); - } else { - res.status(400).send(); - return 0; - } - }). - then(async (ris) => { - // tools.mylog("passo il TOKEN: ", token); + if (recextra) { + recextra.registered = true; + recextra.username = user.username; + await recextra.save(); - if (recextra) { - recextra.registered = true; - recextra.username = user.username; - await recextra.save(); + // await User.fixUsername(user.idapp, user.ind_order, user.username); + } + return ris; + }) + .then(async (ris) => { + // tools.mylog("LINKREG = " + user.linkreg); + // Invia un'email all'utente + // tools.mylog('process.env.TESTING_ON', process.env.TESTING_ON); + console.log('res.locale', res.locale); - // await User.fixUsername(user.idapp, user.ind_order, user.username); - } - return ris; - }). - then(async (ris) => { + await telegrambot.askConfirmationUser( + user.idapp, + shared_consts.CallFunz.REGISTRATION, + user, + '', + '', + '', + regexpire + ); - // tools.mylog("LINKREG = " + user.linkreg); - // Invia un'email all'utente - // tools.mylog('process.env.TESTING_ON', process.env.TESTING_ON); - console.log('res.locale', res.locale); - - await telegrambot.askConfirmationUser(user.idapp, shared_consts.CallFunz.REGISTRATION, user, '', '', '', regexpire); - - // if (!tools.testing()) { - await sendemail.sendEmail_Registration(user.lang, user.email, user, - user.idapp, user.linkreg); - // } - res - .header('x-auth', ris.token) - .header('x-refrtok', ris.refreshToken) - .send(user); - return true; - }); - }).catch((e) => { - console.error(e.message); - res.status(400).send(e); - }); + // if (!tools.testing()) { + await sendemail.sendEmail_Registration(user.lang, user.email, user, user.idapp, user.linkreg); + // } + res.header('x-auth', ris.token).header('x-refrtok', ris.refreshToken).send(user); + return true; + }); + }) + .catch((e) => { + console.error(e.message); + res.status(400).send(e); + }); } catch (e) { console.error('Error: /users REG: ' + e.message); } - }); router.get('/:idapp/:username', async (req, res) => { @@ -406,18 +384,18 @@ router.get('/:idapp/:username', async (req, res) => { // return res.status(200).send(); // } - await User.findByUsername(idapp, username, false, true).then(async (user) => { - if (!user) { - user = await User.findByUsernameTelegram(idapp, username, false, true); - if (!user) - return res.status(404).send(); - } - // console.log('TROVATO!') - return res.status(200).send(); - }).catch((e) => { - return res.status(400).send(); - }); - + await User.findByUsername(idapp, username, false, true) + .then(async (user) => { + if (!user) { + user = await User.findByUsernameTelegram(idapp, username, false, true); + if (!user) return res.status(404).send(); + } + // console.log('TROVATO!') + return res.status(200).send(); + }) + .catch((e) => { + return res.status(400).send(); + }); }); router.patch('/:id', authenticate, (req, res) => { @@ -428,22 +406,22 @@ router.patch('/:id', authenticate, (req, res) => { if (!User.isAdmin(req.user.perm)) { // If without permissions, exit - return res.status(404). - send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' }); + return res.status(404).send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' }); } - User.findByIdAndUpdate(id, { $set: body }).then((user) => { - tools.mylogshow(' USER TO MODIFY: ', user); - if (!user) { - return res.status(404).send(); - } else { - res.send({ code: server_constants.RIS_CODE_OK, msg: '' }); - } - - }).catch((e) => { - tools.mylogserr('Error patch USER: ', e); - res.status(400).send(); - }); + User.findByIdAndUpdate(id, { $set: body }) + .then((user) => { + tools.mylogshow(' USER TO MODIFY: ', user); + if (!user) { + return res.status(404).send(); + } else { + res.send({ code: server_constants.RIS_CODE_OK, msg: '' }); + } + }) + .catch((e) => { + tools.mylogserr('Error patch USER: ', e); + res.status(400).send(); + }); }); router.post('/lastmovs', authenticate, async (req, res) => { @@ -462,40 +440,38 @@ router.post('/lastmovs', authenticate, async (req, res) => { tools.mylogserr('Error lastmovs: ', e); res.status(400).send(); } - }); - router.post('/receiveris', authenticate, (req, res) => { const username = req.user ? req.user.username : ''; const groupname = req.body.groupname; const idapp = req.body.idapp; try { - if (!username) - return res.send({ code: server_constants.RIS_CODE_ERR }); + if (!username) return res.send({ code: server_constants.RIS_CODE_ERR }); if (groupname) { return MyGroup.setReceiveRisGroup(idapp, groupname) - .then(risult => { + .then((risult) => { res.send({ code: server_constants.RIS_CODE_OK }); - }).catch((err) => { + }) + .catch((err) => { tools.mylog('ERRORE IN receiveris: ' + err.message); res.status(400).send(); }); } else if (username) { return User.setReceiveRis(idapp, username) - .then(risult => { + .then((risult) => { res.send({ code: server_constants.RIS_CODE_OK }); - }).catch((err) => { + }) + .catch((err) => { tools.mylog('ERRORE IN receiveris: ' + err.message); res.status(400).send(); }); } } catch (e) { res.status(400).send(); - - }; + } }); router.post('/listlinkreg', authenticate, (req, res) => { @@ -504,20 +480,19 @@ router.post('/listlinkreg', authenticate, (req, res) => { const idapp = req.body.idapp; try { - if (!username) - return res.send({ code: server_constants.RIS_CODE_ERR }); + if (!username) return res.send({ code: server_constants.RIS_CODE_ERR }); return User.setLinkReg(idapp, username) - .then(risult => { + .then((risult) => { res.send({ code: server_constants.RIS_CODE_OK }); - }).catch((err) => { + }) + .catch((err) => { tools.mylog('ERRORE IN listlinkreg: ' + err.message); res.status(400).send(); }); } catch (e) { res.status(400).send(); - - }; + } }); router.post('/profile', authenticate, (req, res) => { @@ -533,24 +508,22 @@ router.post('/profile', authenticate, (req, res) => { const idnotif = req.body['idnotif'] ? req.body['idnotif'] : ''; SendNotif.setNotifAsRead(idapp, usernameOrig, idnotif); - return User.getUserProfileByUsername(idapp, username, usernameOrig, - false, perm). - then((ris) => { - - return User.getFriendsByUsername(idapp, usernameOrig). - then(async (friends) => { + return User.getUserProfileByUsername(idapp, username, usernameOrig, false, perm) + .then((ris) => { + return User.getFriendsByUsername(idapp, usernameOrig) + .then(async (friends) => { if (username === usernameOrig) { const userprofile = await User.getExtraInfoByUsername(idapp, ris.username); ris.profile = userprofile; } return { ris, friends }; - - }).then(tot => { + }) + .then((tot) => { return res.send({ user: tot.ris, friends: tot.friends }); }); - - }).catch((e) => { + }) + .catch((e) => { tools.mylog('ERRORE IN Profile: ' + e.message); res.status(400).send(); }); @@ -558,7 +531,6 @@ router.post('/profile', authenticate, (req, res) => { tools.mylogserr('Error profile: ', e); res.status(400).send(); } - }); router.post('/activities', authenticate_noerror, (req, res) => { @@ -575,12 +547,10 @@ router.post('/activities', authenticate_noerror, (req, res) => { const idnotif = req.body['idnotif'] ? req.body['idnotif'] : ''; SendNotif.setNotifAsRead(idapp, usernameOrig, idnotif); - return User.getUserProfileByUsername(idapp, username, usernameOrig, - false, perm). - then((ris) => { - - return User.getFriendsByUsername(idapp, usernameOrig). - then(async (friends) => { + return User.getUserProfileByUsername(idapp, username, usernameOrig, false, perm) + .then((ris) => { + return User.getFriendsByUsername(idapp, usernameOrig) + .then(async (friends) => { let userprofile = null; if (req.user) { userprofile = await User.getExtraInfoByUsername(idapp, ris.username); @@ -593,12 +563,12 @@ router.post('/activities', authenticate_noerror, (req, res) => { ris.profile = userprofile; return { ris, friends }; - - }).then(tot => { + }) + .then((tot) => { return res.send({ user: tot.ris, friends: tot.friends }); }); - - }).catch((e) => { + }) + .catch((e) => { tools.mylog('ERRORE IN Profile: ' + e.message); res.status(400).send(); }); @@ -606,7 +576,6 @@ router.post('/activities', authenticate_noerror, (req, res) => { tools.mylogserr('Error profile: ', e); res.status(400).send(); } - }); router.post('/panel', authenticate, async (req, res) => { @@ -616,12 +585,12 @@ router.post('/panel', authenticate, async (req, res) => { if (!User.isAdmin(req.user.perm) && !User.isManager(req.user.perm)) { // If without permissions, exit - return res.status(404). - send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' }); + return res.status(404).send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' }); } try { - const myuser = await User.findOne({ idapp, username }, + const myuser = await User.findOne( + { idapp, username }, { username: 1, name: 1, @@ -637,7 +606,8 @@ router.post('/panel', authenticate, async (req, res) => { username_who_report: 1, date_report: 1, profile: 1, - }).lean(); + } + ).lean(); if (!!myuser) { res.send(myuser); } else { @@ -648,7 +618,6 @@ router.post('/panel', authenticate, async (req, res) => { tools.mylogserr('Error profile: ', e); res.status(400).send(); } - }); router.post('/notifs', authenticate, async (req, res) => { @@ -677,7 +646,6 @@ router.post('/notifs', authenticate, async (req, res) => { } */ - }); router.post('/newtok', async (req, res) => { @@ -706,7 +674,7 @@ router.post('/newtok', async (req, res) => { console.error('Errore durante il refresh token:', e); return res.status(500).send({ error: 'Errore interno del server' }); } -}) +}); // Dizionario per tenere traccia dei tentativi di accesso falliti per ogni utente const failedLoginAttempts = {}; @@ -737,8 +705,7 @@ function checkBlocked(req, res, next) { } router.post('/login', checkBlocked, async (req, res) => { - const body = _.pick(req.body, - ['username', 'password', 'idapp', 'keyappid', 'lang']); + const body = _.pick(req.body, ['username', 'password', 'idapp', 'keyappid', 'lang']); const userpass = new User(body); // const subs = _.pick(req.body, ['subs']); @@ -746,8 +713,7 @@ router.post('/login', checkBlocked, async (req, res) => { // tools.mylog("user REC:", user); - if (body.keyappid !== process.env.KEY_APP_ID) - return res.status(400).send(); + if (body.keyappid !== process.env.KEY_APP_ID) return res.status(400).send(); let resalreadysent = false; @@ -758,7 +724,13 @@ router.post('/login', checkBlocked, async (req, res) => { const rislogin = await User.tooManyLoginWrong(body.idapp, body.username, true); if (rislogin.troppilogin) { - let text = 'Troppe richieste di Login ERRATE: ' + body.username + ' [IP: ' + tools.getiPAddressUser(req) + '] Tentativi: ' + rislogin.retry_pwd; + let text = + 'Troppe richieste di Login ERRATE: ' + + body.username + + ' [IP: ' + + tools.getiPAddressUser(req) + + '] Tentativi: ' + + rislogin.retry_pwd; telegrambot.sendMsgTelegramToTheManagers(body.idapp, text); console.log('/login', text); res.status(400).send({ code: server_constants.RIS_CODE_ERR, msg: text }); @@ -776,7 +748,16 @@ router.post('/login', checkBlocked, async (req, res) => { let numvolteerrati = failedLoginAttempts[body.username]; if (numvolteerrati > 2) { - const msg = 'Tentativo (' + numvolteerrati + ') di Login ERRATO [' + body.username + ' , ' + ']\n' + '[IP: ' + tools.getiPAddressUser(req) + ']'; + const msg = + 'Tentativo (' + + numvolteerrati + + ') di Login ERRATO [' + + body.username + + ' , ' + + ']\n' + + '[IP: ' + + tools.getiPAddressUser(req) + + ']'; tools.mylogshow(msg); await telegrambot.sendMsgTelegramToTheAdmin(req.body.idapp, msg, true); tools.writeErrorLog(msg); @@ -784,7 +765,13 @@ router.post('/login', checkBlocked, async (req, res) => { if (failedLoginAttempts[body.username] >= MAX_FAILED_ATTEMPTS) { blockUser(body.username); - text = 'Troppi tentativi di accesso falliti. Utente bloccato (' + body.username + ')' + ' [IP: ' + tools.getiPAddressUser(req) + ']'; + text = + 'Troppi tentativi di accesso falliti. Utente bloccato (' + + body.username + + ')' + + ' [IP: ' + + tools.getiPAddressUser(req) + + ']'; tools.mylogshow(text); telegrambot.sendMsgTelegramToTheManagers(req.body.idapp, text); res.status(403).json({ message: text }); @@ -803,34 +790,29 @@ router.post('/login', checkBlocked, async (req, res) => { const subsExistonDb = await existSubScribe(usertosend._id, 'auth', req.get('User-Agent')); - res - .header('x-auth', myris.token) - .header('x-refrtok', myris.refreshToken) - .send({ - usertosend, - code: server_constants.RIS_CODE_OK, - subsExistonDb, - }); - + res.header('x-auth', myris.token).header('x-refrtok', myris.refreshToken).send({ + usertosend, + code: server_constants.RIS_CODE_OK, + subsExistonDb, + }); } - - } catch (e) { console.error('ERRORE IN LOGIN: ' + e.message); - if (!resalreadysent) - res.status(400). - send({ code: server_constants.RIS_CODE_LOGIN_ERR_GENERIC, msgerr: e.message }); + if (!resalreadysent) res.status(400).send({ code: server_constants.RIS_CODE_LOGIN_ERR_GENERIC, msgerr: e.message }); } }); router.delete('/me/token', authenticate_withUser, (req, res) => { // tools.mylog("TOKENREM = " + req.token); try { - req.user.removeToken(req.token).then(() => { - res.status(200).send(); - }, () => { - res.status(400).send(); - }); + req.user.removeToken(req.token).then( + () => { + res.status(200).send(); + }, + () => { + res.status(400).send(); + } + ); } catch (e) { console.log('delete(/me/token', e.message); } @@ -840,15 +822,17 @@ router.post('/setperm', authenticate, (req, res) => { const body = _.pick(req.body, ['idapp', 'username', 'perm']); tools.mylog('SETPERM = ' + req.token); - User.setPermissionsById(req.user._id, body).then(() => { - res.status(200).send(); - }, () => { - res.status(400).send(); - }); + User.setPermissionsById(req.user._id, body).then( + () => { + res.status(200).send(); + }, + () => { + res.status(400).send(); + } + ); }); router.post('/import_extralist', async (req, res) => { - const strdata = req.body.strdata; idapp = req.body.idapp; locale = req.body.locale; @@ -864,13 +848,14 @@ router.post('/friends', authenticate, (req, res) => { idapp = req.body.idapp; locale = req.body.locale; - return User.getFriendsByUsername(idapp, username).then((ris) => { - res.send(ris); - }).catch((e) => { - tools.mylog('ERRORE IN Profile: ' + e.message); - res.status(400).send(); - }); - + return User.getFriendsByUsername(idapp, username) + .then((ris) => { + res.send(ris); + }) + .catch((e) => { + tools.mylog('ERRORE IN Profile: ' + e.message); + res.status(400).send(); + }); }); router.post('/groups', authenticate, (req, res) => { @@ -878,13 +863,14 @@ router.post('/groups', authenticate, (req, res) => { idapp = req.body.idapp; locale = req.body.locale; - return MyGroup.getGroupsByUsername(idapp, username, req).then((ris) => { - res.send(ris); - }).catch((e) => { - tools.mylog('ERRORE IN groups: ' + e.message); - res.status(400).send(); - }); - + return MyGroup.getGroupsByUsername(idapp, username, req) + .then((ris) => { + res.send(ris); + }) + .catch((e) => { + tools.mylog('ERRORE IN groups: ' + e.message); + res.status(400).send(); + }); }); router.post('/circuits', authenticate_withUser, (req, res) => { @@ -893,13 +879,14 @@ router.post('/circuits', authenticate_withUser, (req, res) => { locale = req.body.locale; nummovTodownload = req.body.nummovTodownload; - return Circuit.getCircuitsByUsername(idapp, username, req.user, nummovTodownload).then((ris) => { - res.send(ris); - }).catch((e) => { - tools.mylog('ERRORE IN circuits: ' + e.message); - res.status(400).send(); - }); - + return Circuit.getCircuitsByUsername(idapp, username, req.user, nummovTodownload) + .then((ris) => { + res.send(ris); + }) + .catch((e) => { + tools.mylog('ERRORE IN circuits: ' + e.message); + res.status(400).send(); + }); }); router.post('/updatesaldo', authenticate, async (req, res) => { @@ -913,19 +900,29 @@ router.post('/updatesaldo', authenticate, async (req, res) => { try { const userprofile = await User.getExtraInfoByUsername(idapp, username); let ris = { - userprofile - } + userprofile, + }; - ris.arrrecnotif = await SendNotif.findAllNotifByUsernameIdAndIdApp(username, lastdr, idapp, shared_consts.LIMIT_NOTIF_FOR_USER, shared_consts.QualiNotifs.OTHERS); - ris.arrrecnotifcoins = await SendNotif.findAllNotifByUsernameIdAndIdApp(username, lastdr, idapp, shared_consts.LIMIT_NOTIFCOINS_FOR_USER, shared_consts.QualiNotifs.CIRCUITS); + ris.arrrecnotif = await SendNotif.findAllNotifByUsernameIdAndIdApp( + username, + lastdr, + idapp, + shared_consts.LIMIT_NOTIF_FOR_USER, + shared_consts.QualiNotifs.OTHERS + ); + ris.arrrecnotifcoins = await SendNotif.findAllNotifByUsernameIdAndIdApp( + username, + lastdr, + idapp, + shared_consts.LIMIT_NOTIFCOINS_FOR_USER, + shared_consts.QualiNotifs.CIRCUITS + ); return res.send({ ris }); - } catch (e) { tools.mylog('ERRORE IN updatesaldo: ' + e); res.status(400).send(); - }; - + } }); router.post('/friends/cmd', authenticate, async (req, res) => { @@ -939,29 +936,26 @@ router.post('/friends/cmd', authenticate, async (req, res) => { if (!User.isAdmin(req.user.perm) || !User.isManager(req.user.perm)) { // If without permissions, exit - if ((usernameOrig !== usernameLogged) && ( - (usernameDest !== usernameLogged) && - ((cmd === shared_consts.FRIENDSCMD.SETFRIEND) || - (cmd === shared_consts.FRIENDSCMD.SETHANDSHAKE)) - - )) { - return res.status(404). - send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' }); + if ( + usernameOrig !== usernameLogged && + usernameDest !== usernameLogged && + (cmd === shared_consts.FRIENDSCMD.SETFRIEND || cmd === shared_consts.FRIENDSCMD.SETHANDSHAKE) + ) { + return res.status(404).send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' }); } } usernameOrig = await User.getRealUsernameByUsername(idapp, usernameOrig); usernameDest = await User.getRealUsernameByUsername(idapp, usernameDest); - return User.setFriendsCmd(req, idapp, usernameOrig, usernameDest, cmd, value). - then((ris) => { + return User.setFriendsCmd(req, idapp, usernameOrig, usernameDest, cmd, value) + .then((ris) => { res.send(ris); - }). - catch((e) => { + }) + .catch((e) => { tools.mylog('ERRORE IN Friends/cmd: ' + e.message); res.status(400).send(); }); - }); router.post('/sendcmd', authenticate, async (req, res) => { @@ -976,15 +970,14 @@ router.post('/sendcmd', authenticate, async (req, res) => { usernameOrig = await User.getRealUsernameByUsername(idapp, usernameOrig); usernameDest = await User.getRealUsernameByUsername(idapp, usernameDest); - return User.sendCmd(req, idapp, usernameOrig, usernameDest, cmd, value). - then((ris) => { + return User.sendCmd(req, idapp, usernameOrig, usernameDest, cmd, value) + .then((ris) => { res.send(ris); - }). - catch((e) => { + }) + .catch((e) => { tools.mylog('ERRORE IN sendcmd: ' + e.message); res.status(400).send(); }); - }); router.post('/groups/cmd', authenticate, (req, res) => { @@ -1004,15 +997,14 @@ router.post('/groups/cmd', authenticate, (req, res) => { } }*/ - return User.setGroupsCmd(idapp, usernameOrig, groupnameDest, cmd, value, usernameLogged). - then((ris) => { + return User.setGroupsCmd(idapp, usernameOrig, groupnameDest, cmd, value, usernameLogged) + .then((ris) => { res.send(ris); - }). - catch((e) => { + }) + .catch((e) => { tools.mylog('ERRORE IN groups/cmd: ' + e.message); res.status(400).send(); }); - }); router.post('/circuits/cmd', authenticate, async (req, res) => { @@ -1025,7 +1017,6 @@ router.post('/circuits/cmd', authenticate, async (req, res) => { const value = req.body.value; const extrarec = req.body.extrarec; - /*if (!User.isAdmin(req.user.perm) || !User.isManager(req.user.perm)) { // If without permissions, exit if (usernameOrig !== usernameLogged) { @@ -1034,9 +1025,8 @@ router.post('/circuits/cmd', authenticate, async (req, res) => { } }*/ - return await User.setCircuitCmd(idapp, usernameOrig, circuitname, cmd, value, usernameLogged, extrarec). - then(async (ris) => { - + return await User.setCircuitCmd(idapp, usernameOrig, circuitname, cmd, value, usernameLogged, extrarec) + .then(async (ris) => { // Check if ìs a Notif to read if (extrarec && extrarec.hasOwnProperty('idnotif')) { const idnotif = extrarec['idnotif'] ? extrarec['idnotif'] : ''; @@ -1044,63 +1034,52 @@ router.post('/circuits/cmd', authenticate, async (req, res) => { } return res.send(ris); - }). - catch((e) => { + }) + .catch((e) => { tools.mylog('ERRORE IN circuits/cmd: ' + e.message); res.status(400).send(); }); - }); - async function ConvertiDaIntAStr(mytable) { try { console.log('INIZIO - ConvertiDaIntAStr ', mytable.modelName); - return await mytable.find({ '_id': { $type: 16 } }) - .then(async (arr) => { - console.log('num record ', arr.length) + return await mytable.find({ _id: { $type: 16 } }).then(async (arr) => { + console.log('num record ', arr.length); - let ind = 0; - for (let x of arr) { + let ind = 0; + for (let x of arr) { + const idnew = x._id; - const idnew = x._id; + if (idnew < 10000) { + const idint = parseInt(x._id, 10) + 10000; - if (idnew < 10000) { + const myrec = new mytable(x._doc); - const idint = parseInt(x._id, 10) + 10000; + myrec._doc.date_created = x._doc.date_created; + myrec._doc.date_updated = x._doc.date_updated; - const myrec = new mytable(x._doc); - - myrec._doc.date_created = x._doc.date_created; - myrec._doc.date_updated = x._doc.date_updated; - - if (!myrec._doc.date_updated) { - if (myrec.hasOwnProperty('date_created')) - myrec._doc.date_updated = myrec._doc.date_created; - } - if ((myrec.hasOwnProperty('date_updated') && !myrec._doc.date_created)) - myrec._doc.date_created = myrec._doc.date_updated; - myrec._doc._id = idint + ''; - - try { - const doc = await myrec.save(); - ind++; - console.log('++Add (', ind, ')', doc._id); - } catch (err) { - const myid = parseInt(err.keyValue._id, 10) + 0; - const canc = await mytable.findOneAndDelete({ _id: myid }); - if (canc) - console.log('err', err.message, 'canc', canc._doc._id); - }; + if (!myrec._doc.date_updated) { + if (myrec.hasOwnProperty('date_created')) myrec._doc.date_updated = myrec._doc.date_created; } + if (myrec.hasOwnProperty('date_updated') && !myrec._doc.date_created) + myrec._doc.date_created = myrec._doc.date_updated; + myrec._doc._id = idint + ''; + try { + const doc = await myrec.save(); + ind++; + console.log('++Add (', ind, ')', doc._id); + } catch (err) { + const myid = parseInt(err.keyValue._id, 10) + 0; + const canc = await mytable.findOneAndDelete({ _id: myid }); + if (canc) console.log('err', err.message, 'canc', canc._doc._id); + } } - console.log('FINE - ConvertiDaIntAStr ', mytable.modelName); - }); - - - + } + console.log('FINE - ConvertiDaIntAStr ', mytable.modelName); + }); } catch (err) { console.error(err); } @@ -1109,20 +1088,18 @@ async function RimuoviInteri(mytable) { try { console.log('INIZIO - RimuoviInteri ', mytable.modelName); - const arr = await mytable.find({ '_id': { $lte: 10000 } }) + const arr = await mytable.find({ _id: { $lte: 10000 } }); console.log(' search interi...', arr.length); - const ris = await mytable.deleteMany({ '_id': { $lte: 10000 } }) + const ris = await mytable.deleteMany({ _id: { $lte: 10000 } }); console.log('FINE - RimuoviInteri ', mytable.modelName, ris); - } catch (err) { console.error(err); } } async function eseguiDbOpUser(idapp, mydata, locale, req, res) { - let ris = await User.DbOp(idapp, mydata); const populate = require('../populate/populate'); @@ -1132,43 +1109,47 @@ async function eseguiDbOpUser(idapp, mydata, locale, req, res) { let mystr = ''; try { - if (mydata.dbop === 'CreateAccountCircuits') { - const allcirc = await Circuit.find({ idapp }); for (const mycirc of allcirc) { // Il Conto Comunitario prende il nome del circuito ! await Account.createAccount(idapp, '', mycirc.name, true, '', mycirc.path); - } - } else if (mydata.dbop === 'saveStepTut') { - await User.findOneAndUpdate({ _id: mydata._id }, - { $set: { 'profile.stepTutorial': mydata.value } }); + await User.findOneAndUpdate({ _id: mydata._id }, { $set: { 'profile.stepTutorial': mydata.value } }); } else if (mydata.dbop === 'noNameSurname') { - await User.findOneAndUpdate({ _id: mydata._id }, - { $set: { 'profile.noNameSurname': mydata.value } }); + await User.findOneAndUpdate({ _id: mydata._id }, { $set: { 'profile.noNameSurname': mydata.value } }); } else if (mydata.dbop === 'noCircuit') { - await User.findOneAndUpdate({ _id: mydata._id }, - { $set: { 'profile.noCircuit': mydata.value } }); + await User.findOneAndUpdate({ _id: mydata._id }, { $set: { 'profile.noCircuit': mydata.value } }); } else if (mydata.dbop === 'noCircIta') { - await User.findOneAndUpdate({ _id: mydata._id }, - { $set: { 'profile.noCircIta': mydata.value } }); + await User.findOneAndUpdate({ _id: mydata._id }, { $set: { 'profile.noCircIta': mydata.value } }); } else if (mydata.dbop === 'noFoto') { - await User.findOneAndUpdate({ _id: mydata._id }, - { $set: { 'profile.noFoto': mydata.value } }); - + await User.findOneAndUpdate({ _id: mydata._id }, { $set: { 'profile.noFoto': mydata.value } }); + } else if (mydata.dbop === 'convertProductInfos') { + const products = await Product.find({ idProductInfo: { $exists: true } }); + for (const product of products) { + const productInfo = await ProductInfo.findById(product.idProductInfo); + if (productInfo) { + const productInfoObj = productInfo.toObject(); + delete productInfoObj._id; + delete productInfoObj.__v; + await Product.updateOne( + { _id: product._id }, + { + $set: { productInfo: productInfoObj }, + $unset: { idProductInfo: 1 }, + } + ); + } + } } - } catch (e) { console.log(e.message); } - -}; +} router.post('/dbop', authenticate, async (req, res) => { - const mydata = req.body.mydata; idapp = req.body.idapp; locale = req.body.locale; @@ -1178,21 +1159,17 @@ router.post('/dbop', authenticate, async (req, res) => { } try { - const cronMod = new CronMod(); - const risOp = await cronMod.eseguiDbOp(idapp, mydata, req, res); - - return res.send({ code: server_constants.RIS_CODE_OK, data: risOp }); + const risOp = await cronMod.eseguiDbOp(idapp, mydata, req, res); + return res.send({ code: server_constants.RIS_CODE_OK, data: risOp }); } catch (e) { console.log(e.message); return res.status(400).send({ code: server_constants.RIS_CODE_ERR, msg: e.message }); } - }); router.post('/dbopuser', authenticate, async (req, res) => { - const mydata = req.body.mydata; idapp = req.body.idapp; locale = req.body.locale; @@ -1207,17 +1184,14 @@ router.post('/dbopuser', authenticate, async (req, res) => { ris = await User.updateMyData(ris, idapp, req.user.username); res.send({ code: server_constants.RIS_CODE_OK, ris }); - } catch (e) { res.status(400).send({ code: server_constants.RIS_CODE_ERR, msg: e }); console.log(e.message); } - }); router.post('/infomap', authenticate, async (req, res) => { - const idapp = req.body.idapp; const raggruppa = true; @@ -1226,24 +1200,21 @@ router.post('/infomap', authenticate, async (req, res) => { { $match: { idapp, - $or: [ - { deleted: { $exists: false } }, - { deleted: { $exists: true, $eq: false } } - ] - } + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], + }, }, { $lookup: { - from: "provinces", // Collezione delle province - localField: "profile.resid_province", // Campo nella collezione User che contiene l'ID della provincia - foreignField: "prov", // Campo nella collezione Province che identifica l'ID della provincia - as: "provinceInfo" // Nome del campo in cui verranno memorizzate le informazioni della provincia - } + from: 'provinces', // Collezione delle province + localField: 'profile.resid_province', // Campo nella collezione User che contiene l'ID della provincia + foreignField: 'prov', // Campo nella collezione Province che identifica l'ID della provincia + as: 'provinceInfo', // Nome del campo in cui verranno memorizzate le informazioni della provincia + }, }, { $addFields: { - "provinceInfo": { $arrayElemAt: ["$provinceInfo", 0] } // Estrae il primo elemento dell'array provinceInfo - } + provinceInfo: { $arrayElemAt: ['$provinceInfo', 0] }, // Estrae il primo elemento dell'array provinceInfo + }, }, { $project: { @@ -1256,10 +1227,10 @@ router.post('/infomap', authenticate, async (req, res) => { lasttimeonline: 1, 'profile.img': 1, 'profile.resid_province': 1, - lat: "$provinceInfo.lat", // Aggiunge il campo lat preso dalla provincia - long: "$provinceInfo.long" // Aggiunge il campo long preso dalla provincia - } - } + lat: '$provinceInfo.lat', // Aggiunge il campo lat preso dalla provincia + long: '$provinceInfo.long', // Aggiunge il campo long preso dalla provincia + }, + }, ]; let ris = null; @@ -1268,40 +1239,40 @@ router.post('/infomap', authenticate, async (req, res) => { const myquery = [ { $lookup: { - from: "users", // Collezione degli utenti - localField: "prov", // Campo nella collezione Province che identifica l'ID della provincia - foreignField: "profile.resid_province", // Campo nella collezione User che contiene l'ID della provincia - as: "users" // Nome del campo in cui verranno memorizzati gli utenti della provincia - } + from: 'users', // Collezione degli utenti + localField: 'prov', // Campo nella collezione Province che identifica l'ID della provincia + foreignField: 'profile.resid_province', // Campo nella collezione User che contiene l'ID della provincia + as: 'users', // Nome del campo in cui verranno memorizzati gli utenti della provincia + }, }, { $addFields: { - userCount: { $size: "$users" } // Aggiunge il numero di utenti nella provincia - } + userCount: { $size: '$users' }, // Aggiunge il numero di utenti nella provincia + }, }, { $lookup: { - from: "provinces", // Collezione delle province - localField: "prov", // Campo nella collezione Province che identifica l'ID della provincia - foreignField: "prov", // Campo nella collezione Province che identifica l'ID della provincia - as: "provinceInfo" // Nome del campo in cui verranno memorizzate le informazioni della provincia - } + from: 'provinces', // Collezione delle province + localField: 'prov', // Campo nella collezione Province che identifica l'ID della provincia + foreignField: 'prov', // Campo nella collezione Province che identifica l'ID della provincia + as: 'provinceInfo', // Nome del campo in cui verranno memorizzate le informazioni della provincia + }, }, { $addFields: { - provinceDescr: { $arrayElemAt: ["$provinceInfo.descr", 0] } // Aggiunge il campo descr preso dalla provincia - } + provinceDescr: { $arrayElemAt: ['$provinceInfo.descr', 0] }, // Aggiunge il campo descr preso dalla provincia + }, }, { $project: { _id: 0, // Esclude il campo _id - province: "$prov", // Rinomina il campo prov come province - descr: "$provinceDescr", + province: '$prov', // Rinomina il campo prov come province + descr: '$provinceDescr', userCount: 1, lat: 1, // Include il campo lat - long: 1 // Include il campo long - } - } + long: 1, // Include il campo long + }, + }, ]; ris = await Province.aggregate(myquery); @@ -1314,33 +1285,32 @@ router.post('/infomap', authenticate, async (req, res) => { } res.send({ code: server_constants.RIS_CODE_OK, ris }); - } catch (e) { res.status(400).send({ code: server_constants.RIS_CODE_ERR, msg: e }); console.log(e.message); } - }); router.post('/mgt', authenticate_withUser, async (req, res) => { - const mydata = req.body.mydata; idapp = req.body.idapp; locale = req.body.locale; try { - const { nummsgsent, numrec, textsent, text } = await telegrambot.sendMsgFromSiteToBotTelegram(idapp, req.user, mydata); + const { nummsgsent, numrec, textsent, text } = await telegrambot.sendMsgFromSiteToBotTelegram( + idapp, + req.user, + mydata + ); return res.send({ numrec, nummsgsent, textsent, text }); - } catch (e) { res.status(400).send(); res.send({ code: server_constants.RIS_CODE_ERR, msg: e }); console.log(e.message); } - }); module.exports = router; diff --git a/src/server/tools/general.js b/src/server/tools/general.js index ce36981..7c6a664 100755 --- a/src/server/tools/general.js +++ b/src/server/tools/general.js @@ -5935,8 +5935,7 @@ module.exports = { return mydate2; }, - async downloadImgIfMissing(productInfo) { - const ProductInfo = require('../models/productInfo'); + async downloadImgIfMissing(product) { const Product = require('../models/product'); try { @@ -5953,33 +5952,33 @@ module.exports = { const vecchiomodo = false; - if (productInfo.image_link && vecchiomodo) { - const relativeimg = productInfo.image_link.split('/').pop(); + if (product.productInfo.image_link && vecchiomodo) { + const relativeimg = product.productInfo.image_link.split('/').pop(); const img = - this.getdirByIdApp(productInfo.idapp) + + this.getdirByIdApp(product.productInfo.idapp) + dirmain + server_constants.DIR_UPLOAD + '/products/' + - productInfo.image_link.split('/').pop(); + product.productInfo.image_link.split('/').pop(); const savePath = path.resolve(__dirname, img); // Sostituisci con il percorso dove salvare l'immagine - let scaricaimg = !productInfo.imagefile || !(await this.isFileExistsAsync(savePath)); + let scaricaimg = !product.productInfo.imagefile || !(await this.isFileExistsAsync(savePath)); - if (!productInfo.imagefile && (await this.isFileExistsAsync(savePath))) { + if (!product.productInfo.imagefile && (await this.isFileExistsAsync(savePath))) { // esiste il file, ma sul DB non è corretto const stats = fs.statSync(savePath); // Ottieni informazioni sul file if (stats.size > 0) { // Controlla se la dimensione del file è maggiore di zero // Esiste il file ed è non vuoto, ma sul DB non è corretto - productInfo.imagefile = relativeimg; - return { prodInfo: productInfo, aggiornatoimg: true }; + product.productInfo.imagefile = relativeimg; + return { prodInfo: product.productInfo, aggiornatoimg: true }; } else { scaricaimg = true; } } - if (productInfo.imagefile && (await this.isFileExistsAsync(savePath))) { + if (product.productInfo.imagefile && (await this.isFileExistsAsync(savePath))) { // esiste il file, ma sul DB non è corretto const stats = fs.statSync(savePath); // Ottieni informazioni sul file @@ -5991,12 +5990,12 @@ module.exports = { if (scaricaimg && vecchiomodo) { // Download image from the URL productInfo.image_link - productInfo.imagefile = relativeimg; + product.productInfo.imagefile = relativeimg; const downloader = new ImageDownloader(); const aggiornatoimg = await downloader - .downloadImage(productInfo.image_link, savePath, { + .downloadImage(product.productInfo.image_link, savePath, { maxRetries: 1, initialDelay: 300, timeout: 15000, @@ -6010,44 +6009,44 @@ module.exports = { return result; }); - return { prodInfo: productInfo, aggiornatoimg: aggiornatoimg.ris }; + return { prodInfo: product.productInfo, aggiornatoimg: aggiornatoimg.ris }; } } let fileesistente = false; - if (productInfo.imagefile && productInfo.imagefile !== 'noimg.jpg') { + if (product.productInfo.imagefile && product.productInfo.imagefile !== 'noimg.jpg') { // controlla se esiste il file const img = - this.getdirByIdApp(productInfo.idapp) + + this.getdirByIdApp(product.productInfo.idapp) + dirmain + server_constants.DIR_UPLOAD + '/products/' + - productInfo.imagefile.split('/').pop(); + product.productInfo.imagefile.split('/').pop(); const filecompleto = path.resolve(__dirname, img); // Sostituisci con il percorso dove salvare l'immagine // Se non esiste lo scarico ! fileesistente = await this.isFileExistsAsync(filecompleto); } - if (!vecchiomodo && (!productInfo.image_link || !fileesistente)) { - let scarica_da_sito = !productInfo.imagefile || productInfo.imagefile === 'noimg.jpg'; + if (!vecchiomodo && (!product.productInfo.image_link || !fileesistente)) { + let scarica_da_sito = !product.productInfo.imagefile || product.productInfo.imagefile === 'noimg.jpg'; - if (!scarica_da_sito && productInfo.imagefile) { + if (!scarica_da_sito && product.productInfo.imagefile) { scarica_da_sito = !fileesistente; // Se non esiste lo scarico ! } - if (scarica_da_sito && !productInfo.image_not_found) { + if (scarica_da_sito && !product.productInfo.image_not_found) { // date and time - productInfo.imagefile = 'img_' + new Date().toISOString().replace(/T/, ' ').replace(/\..+/, ''); + product.productInfo.imagefile = 'img_' + new Date().toISOString().replace(/T/, ' ').replace(/\..+/, ''); const img = - this.getdirByIdApp(productInfo.idapp) + + this.getdirByIdApp(product.productInfo.idapp) + dirmain + server_constants.DIR_UPLOAD + '/products/' + - productInfo.imagefile.split('/').pop(); + product.productInfo.imagefile.split('/').pop(); let savePath = path.resolve(__dirname, img); // Sostituisci con il percorso dove salvare l'immagine - let link = 'https://www.gruppomacro.com/copertine.php?id_gm=' + productInfo.sku; + let link = 'https://www.gruppomacro.com/copertine.php?id_gm=' + product.productInfo.sku; const downloader = new ImageDownloader(); @@ -6067,12 +6066,12 @@ module.exports = { (aggiornatoimg?.filepath && aggiornatoimg?.filepath?.includes('noimg.jpg')) ) { // non trovato quindi la prossima volta non richiederlo - await ProductInfo.setImgNotFound(productInfo._id); + await Product.setImgNotFound(product._id); } if (aggiornatoimg?.filepath?.includes('noimg.jpg')) { // nascondi il prodotto se non trovo l'immagine ! - await Product.updateOne({ idProductInfo: productInfo._id }, { $set: { deleted: true } }); + await Product.updateOne({ _id: product._id }, { $set: { deleted: true } }); aggiornatoimg = { ris: false, deleted: true }; } @@ -6080,10 +6079,10 @@ module.exports = { if (aggiornatoimg?.filepath) { const filenamebase = path.basename(aggiornatoimg.filepath); // const img = '/upload/products/' + filenamebase; - productInfo.imagefile = filenamebase; + product.productInfo.imagefile = filenamebase; } - return { prodInfo: productInfo, aggiornatoimg: aggiornatoimg.ris }; + return { prodInfo: product.productInfo, aggiornatoimg: aggiornatoimg.ris }; } else { return { prodInfo: null, aggiornatoimg: false }; } diff --git a/src/server/tools/globalTables.js b/src/server/tools/globalTables.js index 9037e6e..1ea1614 100755 --- a/src/server/tools/globalTables.js +++ b/src/server/tools/globalTables.js @@ -66,7 +66,6 @@ const { MsgTemplate } = require('../models/msg_template'); const { Graduatoria } = require('../models/graduatoria'); const Product = require('../models/product'); -const ProductInfo = require('../models/productInfo'); const Producer = require('../models/producer'); const Cart = require('../models/cart'); const OrdersCart = require('../models/orderscart'); @@ -116,7 +115,6 @@ module.exports = { else if (tablename === 'operators') mytable = Operator; else if (tablename === 'products') mytable = Product; else if (tablename === 'arrvariazioni') mytable = Product; - else if (tablename === 'productinfos') mytable = ProductInfo; else if (tablename === 'storehouses') mytable = Storehouse; else if (tablename === 'providers') mytable = Provider; else if (tablename === 'gasordines') mytable = Gasordine; diff --git a/src/server/tools/shared_nodejs.js b/src/server/tools/shared_nodejs.js index c20db01..5c2ba8d 100755 --- a/src/server/tools/shared_nodejs.js +++ b/src/server/tools/shared_nodejs.js @@ -258,7 +258,7 @@ module.exports = { ], TABLES_USER_ID: ['mygroups', 'myskills', 'mybachecas', 'myhosps', 'mygoods'], TABLES_CREATEDBY: ['mygroups', 'circuits', 'attivitas'], - TABLES_UPDATE_LASTMODIFIED: ['myskills', 'mybachecas', 'myhosps', 'mygoods', 'bots', 'mygroups', 'circuits', 'attivitas', 'myelems', 'mypages', 'productinfos', 'products', 'catalogs', 'crons'], + TABLES_UPDATE_LASTMODIFIED: ['myskills', 'mybachecas', 'myhosps', 'mygoods', 'bots', 'mygroups', 'circuits', 'attivitas', 'myelems', 'mypages', 'products', 'catalogs', 'crons'], TABLES_FIELDS_DESCR_AND_CITY_AND_USER: ['myskills', 'mybachecas', 'myhosps', 'mygoods'], diff --git a/warnedUsers.json b/warnedUsers.json new file mode 100644 index 0000000..4fa30cb --- /dev/null +++ b/warnedUsers.json @@ -0,0 +1 @@ +[5356627050] \ No newline at end of file