From fba2ebd710b57e1394489bd81cf8321bda61ef2d Mon Sep 17 00:00:00 2001 From: Surya Paolo Date: Wed, 16 Apr 2025 23:28:29 +0200 Subject: [PATCH] - Aggiornamento dal DB di GM al DB Locale --- src/server/controllers/articleController.js | 75 +- src/server/models/catalog.js | 4 +- src/server/models/productInfo.js | 4 + src/server/modules/Macro.js | 574 ++++++++ src/server/router/admin_router.js | 1343 +++++++++---------- src/server/router/articleRoutes.js | 5 +- src/server/router/products_router.js | 2 +- src/server/tools/general.js | 144 +- src/server/tools/shared_nodejs.js | 1 + 9 files changed, 1409 insertions(+), 743 deletions(-) create mode 100644 src/server/modules/Macro.js diff --git a/src/server/controllers/articleController.js b/src/server/controllers/articleController.js index 0e95820..3bf81c1 100644 --- a/src/server/controllers/articleController.js +++ b/src/server/controllers/articleController.js @@ -1,11 +1,11 @@ -const axios = require('axios'); - const server_constants = require('../tools/server_constants'); const shared_consts = require('../tools/shared_nodejs'); const tools = require('../tools/general'); +const axios = require('axios'); + const SERVER_A_URL = process.env.SERVER_A_URL || "http://IP_DI_SERVER_A:3000"; const API_KEY = process.env.API_KEY_MSSQL; @@ -21,7 +21,7 @@ const getArticlesSales = async () => { COALESCE(p.rank3M, 0) as rank3M, COALESCE(t.fatrank3M, 0) as fatrank3M, COALESCE(q.rank6M, 0) as rank6M, COALESCE(r.rank1Y, 0) as rank1Y, COALESCE(t.fat3mesi, 0) as fatLast3M, - COALESCE(t.fat6mesi, 0) as fatLast6M, + COALESCE(t2.fat6mesi, 0) as fatLast6M, COALESCE(p.venduti3mesi, 0) as vLast3M, COALESCE(q.venduti6mesi, 0) as vLast6M, COALESCE(r.venduti1anno, 0) as vLastY, s.ultimoOrdine as dataUltimoOrdine @@ -71,6 +71,24 @@ exports.exportArticlesSalesByJSON = async (req, res) => { } }; +exports.getTableContent = async (options) => { + try { + // Chiama getTableContent, se ritorna errore hangup, allora attendi 2 secondi e poi richiamala. + const tableContent = await getTableContentBase(options); + return tableContent; + } catch (error) { + console.error('Error: ', error); + if (error.message === 'socket hang up') { + console.log('Error: hangup, waiting 2 seconds and retrying...'); + await new Promise(resolve => setTimeout(resolve, 2000)); + return await this.getTableContent(options); + } else { + throw error; + } + } +}; + + const formatDate = (dateValue) => { const date = new Date(dateValue); const day = String(date.getDate()).padStart(2, '0'); @@ -79,7 +97,7 @@ const formatDate = (dateValue) => { return `${day}/${month}/${year}`; }; -const getTableContent = async (options) => { +const getTableContentBase = async (options) => { try { // Verifica se la tabella esiste const checkTableQuery = `SELECT COUNT(*) as tableExists FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '${options.nameTable}'`; @@ -351,9 +369,26 @@ const getTableContent = async (options) => { records.forEach(record => { let myrec = {} - displayColumns.forEach(column => { - myrec[column] = `${getDisplayValue(record, column)} `; - }); + if (options.recordraw) { + myrec = record; + } else { + + displayColumns.forEach(column => { + const value = record[column]; + if (value !== undefined && value !== null) { + const type = typeof value; + if (type === 'number' && !mergedMapping[column]) { + myrec[column] = value; + } else if (type === 'boolean') { + myrec[column] = value; + } else if (value instanceof Date) { + myrec[column] = formatDate(value); + } else { + myrec[column] = `${getDisplayValue(record, column)}`.trim(); + } + } + }); + } output.push(myrec) }); } @@ -614,7 +649,7 @@ const checkPermissions = async (options) => { exports.viewTable = async (req, res) => { try { const options = req.body.options; - const tableContent = await getTableContent(options); + const tableContent = await this.getTableContent(options); let out = {}; @@ -665,7 +700,7 @@ exports.updateLocalDb = async (tableContent, options) => { .trim() // Rimuove gli spazi all'inizio e alla fine .replace(/[\(\)]/g, '') // Rimuove le parentesi tonde .split(','); // Divide la stringa in un array usando la virgola come separatore - + if (arrayPulito && arrayPulito.length > 0) { let aggiornacat = false; const precCatProds = recfound.idCatProds; @@ -703,7 +738,7 @@ exports.updateLocalDb = async (tableContent, options) => { if (tableContent.DataPubblicazione.trim()) { recproductInfo.date_pub = new Date(tools.convertiDataItaliana(tableContent.DataPubblicazione.trim()).date); // convert data to timestamp - recproductInfo.date_pub_ts = recproductInfo.date_pub.getTime(); + recproductInfo.date_pub_ts = recproductInfo.date_pub.getTime(); aggiorna = true; } @@ -724,7 +759,7 @@ exports.updateLocalDb = async (tableContent, options) => { exports.queryTable = async (req, res) => { try { const options = req.body.options; - const tableContent = await getTableContent(options); + const tableContent = await this.getTableContent(options); let out = {}; @@ -772,3 +807,21 @@ exports.saveTable = async (req, res) => { return res.send({ code: server_constants.RIS_CODE_ERR, error }); } }; + +exports.updateAllBook = async (req, res) => { + + const Macro = require('../modules/Macro'); // Importa la classe Macro + + try { + const idapp = req.body.idapp; + const options = req.body.options; + const macro = new Macro(idapp); // Crea un'istanza della classe Macro + + const result = await macro.updateLocalDbFromGM_T_Web_Articoli(options); + + return res.status(200).send({ data: result }); + } catch (e) { + console.error(e.message); + return res.status(400).send(e); + } +} diff --git a/src/server/models/catalog.js b/src/server/models/catalog.js index 641ddbe..bb23c7c 100755 --- a/src/server/models/catalog.js +++ b/src/server/models/catalog.js @@ -99,7 +99,7 @@ CatalogSchema.statics.executeQueryTable = function (idapp, params, user) { return tools.executeQueryTable(this, idapp, params, user); }; -CatalogSchema.statics.OLD_findAllIdApp = async function (idapp) { +/*CatalogSchema.statics.OLD_findAllIdApp = async function (idapp) { const Catalog = this; const arrrec = await Catalog.aggregate([ @@ -122,7 +122,7 @@ CatalogSchema.statics.OLD_findAllIdApp = async function (idapp) { ]); return arrrec; -}; +};*/ CatalogSchema.statics.findAllIdApp = async function (idapp) { const Catalog = this; diff --git a/src/server/models/productInfo.js b/src/server/models/productInfo.js index 27c36af..c84c96f 100755 --- a/src/server/models/productInfo.js +++ b/src/server/models/productInfo.js @@ -50,6 +50,9 @@ const productInfoSchema = new Schema({ }, idCatProds: [{ type: Schema.Types.ObjectId, ref: 'CatProd' }], idSubCatProds: [{ type: Schema.Types.ObjectId, ref: 'SubCatProd' }], + idStatoProdotto: { + type: Number + }, color: { type: String }, @@ -148,6 +151,7 @@ const productInfoSchema = new Schema({ totFat: Number, vLast3M: Number, fatLast3M: Number, + fatLast6M: Number, vLast6M: Number, vLastY: Number, vLast2Y: Number, diff --git a/src/server/modules/Macro.js b/src/server/modules/Macro.js new file mode 100644 index 0000000..0371959 --- /dev/null +++ b/src/server/modules/Macro.js @@ -0,0 +1,574 @@ +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'); +const Author = require('../models/author'); +const Publisher = require('../models/publisher'); +const Gasordine = require('../models/gasordine'); +const tools = require('../tools/general'); // Assicurati di avere il file delle utility +const shared_consts = require('../tools/shared_nodejs'); // Assicurati di avere le costanti condivise + +const { getTableContent } = require('../controllers/articleController'); + +class Macro { + constructor(idapp) { + this.idapp = idapp; + } + + async updateLocalDbFromGM_T_Web_Articoli(params) { + + const options = { + idapp: params.idapp, + nameTable: 'T_Web_Articoli', + campispeciali: true, + recordraw: true, + query: '', + showQtaDisponibile: true, + outhtml: false, + cmd: shared_consts.CmdQueryMs.GET, + inputdaGM: true, + } + + if (params.caricatutti) { + options.where = ''; + } else { + // Singolo + options.where = 'T.IdArticolo =' + params.sku; + } + + let updated = 0, + imported = 0, + errors = 0; + + const recproducts = await getTableContent(options); + + if (Array.isArray(recproducts)) { + for (const recproduct of recproducts) { + await this.elaboraProdotto(recproduct, { updated, imported, errors, inputdaGM: options.inputdaGM, idapp: options.idapp }); + } + } + console.log( + '*** IMPORTATI: ', + imported, + 'AGGIORNATI = ' + updated + ' (su ' + dataObjects.length + ' RECORD)' + ); + return { updated, imported, errors }; + + } + + /** + * Funzione principale per importare il catalogo. + */ + async importaCatalogo(data) { + let updated = 0, + imported = 0, + errors = 0; + + try { + const ripopola = true; //++MODIFICARE! + if (ripopola) { + await this.pulisciECaricaDati(data); + } + + const dataObjects = await Importamacro.find({ idapp: this.idapp }).lean(); + console.log('*** INIZIO IMPORT PRODOTTI ... '); + + for (const product of dataObjects) { + await this.elaboraProdotto(product, { updated, imported, errors }); + } + + console.log( + '*** IMPORTATI: ', + imported, + 'AGGIORNATI = ' + updated + ' (su ' + dataObjects.length + ' RECORD)' + ); + return { updated, imported, error }; + } catch (e) { + console.error(e.message); + throw e; + } + } + + /** + * Pulisce i dati esistenti e carica nuovi dati in Importamacro. + */ + async pulisciECaricaDati(data) { + let dataObjects = null; + try { + dataObjects = JSON.parse(`[${data.arrdata}]`); + } catch (e) { + console.error('Errore nel parsing dei dati:', e); + return; + } + + if (dataObjects && dataObjects[0]) { + await Importamacro.deleteMany({ idapp: this.idapp }); + + for (const recinv of dataObjects[0]) { + const recmacro = this.preparaRecordMacro(recinv); + const recrankingisbn = await ImportaIsbn.findOne({ sku: recmacro.sku }).lean(); + + if (recrankingisbn) { + this.aggiornaCampiDaIsbn(recmacro, recrankingisbn); + } + + try { + await Importamacro.findOneAndUpdate( + { idapp: this.idapp, _id: recmacro._id }, + { $set: recmacro }, + { new: true, upsert: true, strict: false } + ); + } catch (e) { + console.error('Errore durante l\'inserimento:', e); + } + } + } + } + + /** + * Prepara un record macro per l'inserimento. + */ + preparaRecordMacro(recinv) { + const recmacro = { ...recinv }; + recmacro.idapp = this.idapp; + recmacro._id = recmacro.id; + delete recmacro.id; + return recmacro; + } + + /** + * Aggiorna i campi del record macro con i dati da ImportaIsbn. + */ + aggiornaCampiDaIsbn(recmacro, recrankingisbn) { + if (!recmacro.isbn) recmacro.isbn = recrankingisbn.isbn; + if ((!recmacro.Pagine || recmacro.Pagine === 0) && recrankingisbn.Pagine) + recmacro.Pagine = recrankingisbn.Pagine; + if (!recmacro.misure && recrankingisbn.misure) recmacro.misure = recrankingisbn.misure; + } + + /** + * Elabora un singolo prodotto. + */ + async elaboraProdotto(productInput, { updated, imported, errors, inputdaGM, idapp }) { + let isnuovo = false, + setta = false, + importa = true; + + let product = { ...productInput }; + + + if (inputdaGM) + product = this.convertiDaCampiGMACampoFDV_ProductInfo(idapp, product); + + if (!product.title || !product.sku) importa = false; + + if (importa) { + const productInfo = this.preparaProductInfo(product); + + const recrankingisbn = await ImportaIsbn.findOne({ sku: product.sku }).lean(); + if (recrankingisbn) { + this.aggiornaCampiDaIsbn(productInfo, recrankingisbn); + } + + if (!product.hasOwnProperty('active')) { + product.active = true; + } + + await this.gestisciCategorie(productInfo, product); + await this.gestisciAutori(productInfo, product); + await this.gestisciEditore(productInfo, product); + + const risrecInfo = await ProductInfo.findOneAndUpdate( + { code: productInfo.code }, + { $set: productInfo }, + { new: true, upsert: true } + ); + + if (risrecInfo) { + await this.aggiornaImmagineSeNecessario(risrecInfo); + await this.gestisciGasOrdine(product, risrecInfo); + await this.gestisciVariazioni(product, risrecInfo, { updated, imported, errors }); + } else { + console.error('Errore ProductInfo:', product.code); + errors++; + } + } + } + + async gestisciGasOrdine(product) { + // Cerca il GAS + let recGas = null; + if (product.gas_name) { + // Cerca il GAS + recGas = await Gasordine.findOne({ idapp, name: product.gas_name }).lean(); + } + + if (!recGas && !!product.gas_name) { + recGas = new Gasordine({ idapp, name: product.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(); + } + + let recProductExist = null; + let queryprod = { idProductInfo: product.idProductInfo }; + + if (recGas) { + queryprod = { ...queryprod, idGasordine: recGas._id }; + } + + recProductExist = await Product.findOne(queryprod).lean(); + + if (!recProductExist) { + product.idGasordine = recGas ? recGas._id : null; + } + + } + + preparaProductInfo(product) { + try { + return { + idapp: product.idapp, + code: product.isbn, + id_wp: product._id || undefined, + sku: product.sku, + name: product.title, + description: product.description, + short_descr: product.short_descr, + publisher: product.editore, + collezione: product.Collezione, + link: product.link || undefined, + idCatProds: [], + idSubCatProds: [], + img2: product.img2 || undefined, + img3: product.img3 || undefined, + img4: product.img4 || undefined, + checkout_link: product.checkout_link || undefined, + idStatoProdotto: product.idStatoProdotto || undefined, + date_pub: product.date_pub || undefined, + sottotitolo: product.Sottotitolo || undefined, + }; + } catch (e) { + console.error('Errore preparaProductInfo:', e); + return {}; + } + } + + getStatusByIdStatoProdotto(idStatoProdotto) { + switch (idStatoProdotto) { + case 1: + case 4: + case 34: + case 45: + case 46: + return 'publish'; + default: + return 'out_of_stock'; + } + } + + convertiDaCampiGMACampoFDV_ProductInfo(idapp, productGM) { + let productFDV = {}; + + /* productGM CAMPI + { + Id: "257825", + IdArticolo: 20923, + Ean13: "9788828508991", + Titolo: "Fervìda: Fermenti di vita", + ListaAutori: "3453", + ListaArgomenti: "12", + IdStatoProdotto: 46, + PrezzoIvato: 13.9, + IdMarchioEditoriale: 1, + IdCollana: 175, + DataPubblicazione: "2024-03-26T00:00:00.000Z", + IdTipologia: 1, + IdTipoFormato: 1, + Misure: "cm 17x24", + Pagine: "80", + Sottotitolo: "", + Durata: "", + Numero: "", + Edizione: "Marzo 2024", + Ristampa: "", + DataInizioCampagna: "2024-12-03T00:00:00.000Z", + DataFineCampagna: "2099-12-31T00:00:00.000Z", + ScontoCampagna: 5, + PrezzoIvatoScontatoCampagna: 13.205, + DataOra: "2024-12-03T09:56:21.540Z", + Enabled: false, + IDTagGruppo: 0, + Utente: "LENOVO-I5", + PercIva: 0, + IdTitoloOriginale: 12272, + EnabledAlFresco: true, + CodEdizione: 0, + FasciaEta: null, + FasciaEta2: null, + DescrizioneStatoProdotto: "In commercio", + DescrizioneTipologia: "Libri", + DescrizioneFormato: "Brossura", + DescrizioneCollana: "Il Filo Verde di Arianna", + AutoriCompleti: "Stefano Abbruzzese", + DescrArgomento: "Autosufficienza, Autoproduzione e Vita Naturale", + CasaEditrice: "MACRO EDIZIONI", + } + */ + + const recproduct = { + idapp: idapp, + isbn: productGM.Ean13, + // id_wp: '', + sku: productGM.IdArticolo, + title: productGM.Titolo, // productInfo.name.replace(/ - Usato$| - Nuovo$| - Epub$| - Ebook$| - Mobi$| - DVD$| - Streaming$| - Download$/, ""); + description: '', + short_descr: '', + editore: productGM.CasaEditrice, + collezione: productGM.DescrizioneCollana, + Autore: productGM.AutoriCompleti, + publisher: productGM.CasaEditrice, + DescrArgomento: productGM.DescrArgomento, + idStatoProdotto: productGM.IdStatoProdotto, + Stato: this.getStatusByIdStatoProdotto(productGM.IdStatoProdotto), + price: productGM.PrezzoIvato, + sale_price: productGM.PrezzoIvatoScontatoCampagna, + formato: productGM.DescrizioneFormato, + Tipologia: productGM.DescrizioneTipologia, + Edizione: productGM.Edizione, + Pagine: productGM.Pagine, + misure: productGM.Misure, + eta: productGM.FasciaEta, + // addtocart_link: '', + Quantita: productGM.QtaDisponibile || undefined, + date_pub: tools.getDateFromISOString(productGM.DataPubblicazione), + sottotitolo: productGM.Sottotitolo, + productTypes: [shared_consts.PRODUCTTYPE.PRODUCT], + } + + let vers = 0; + + if (productGM.DescrizioneTipologia === 'Usato') + vers = shared_consts.PRODUCTTYPE.USATO; + else if (productGM.DescrizioneTipologia === 'Download') + vers = shared_consts.PRODUCTTYPE.DOWNLOAD; + else if (productGM.DescrizioneTipologia === 'DVD') + vers = shared_consts.PRODUCTTYPE.DVD; + else if (productGM.DescrizioneTipologia === 'Epub') + vers = shared_consts.PRODUCTTYPE.EPUB; + else if (productGM.DescrizioneTipologia === 'Mobi') + vers = shared_consts.PRODUCTTYPE.MOBI; + else if (productGM.DescrizioneTipologia === 'PDF') + vers = shared_consts.PRODUCTTYPE.PDF; + else if (productGM.DescrizioneTipologia === 'Streaming') + vers = shared_consts.PRODUCTTYPE.STREAMING; + else + vers = shared_consts.PRODUCTTYPE.NUOVO; + + recproduct.Versione = vers; + + + return recproduct + } + + /** + * Gestisce le categorie e sottocategorie del prodotto. + */ + async gestisciCategorie(productInfo, product) { + if (product.DescrArgomento) { + productInfo.idCatProds = []; + const reccateg = await CatProd.findOne({ idapp: this.idapp, name: product.DescrArgomento }).lean(); + let nuovaCategoria = null; + if (!reccateg) { + nuovaCategoria = new CatProd({ idapp: this.idapp, name: product.DescrArgomento }); + await nuovaCategoria.save(); + + } + const myriscat = reccateg?._id || (nuovaCategoria ? nuovaCategoria._id : null) + if (myriscat) + productInfo.idCatProds.push(myriscat); + + } else { + if (product.categories) { + // const arrcat = product.categories.trim().split(','); + const arrcat = product.categories.trim().split(','); + productInfo.idCatProds = []; + + for (const mycat of arrcat) { + const mycatstr = mycat.trim(); + const reccateg = await CatProd.findOne({ idapp: this.idapp, name: mycatstr }).lean(); + + let nuovaCategoria = null; + if (!reccateg) { + nuovaCategoria = new CatProd({ idapp: this.idapp, name: mycatstr }); + await nuovaCategoria.save(); + } + + const myriscat = reccateg?._id || (nuovaCategoria ? nuovaCategoria._id : null) + if (myriscat) + productInfo.idCatProds.push(myriscat); + } + } + } + } + + /** + * Gestisce gli autori del prodotto. + */ + async gestisciAutori(productInfo, product) { + if (product.Autore) { + let arrAuthor = [] + if (product.id_wp) + arrAuthor = this.estraiAutori_FDV(product.Autore); + else + arrAuthor = this.estraiAutori(product.Autore); + + productInfo.idAuthors = []; + + for (const author of arrAuthor) { + const recauthor = await Author.findOne({ idapp: this.idapp, name: author.name, surname: author.surname }).lean(); + let nuovoAutore = null; + + if (!recauthor) { + nuovoAutore = new Author({ idapp: this.idapp, name: author.name, surname: author.surname }); + await nuovoAutore.save(); + } + + const myrisautore = recauthor?._id || (nuovoAutore ? nuovoAutore._id : ''); + if (myrisautore) + productInfo.idAuthors.push(myrisautore); + } + } + } + + estraiAutori(autoreString) { + const arrrecauthor = autoreString.trim().split(','); + const arrAuthor = []; + + for (let i = 0; i < arrrecauthor.length; i += 2) { + const nomecognome = arrrecauthor[i].trim(); + let arrrecns = nomecognome.trim().split(' '); + let name = ''; + let surname = ''; + + if (arrrecns && arrrecns.length === 4) { + name = arrrecns[0].trim() + ' ' + arrrecns[1].trim(); + surname = arrrecns[2].trim() + ' ' + arrrecns[3].trim();; + } else { + + if (arrrecns && arrrecns.length === 1) { + name = arrrecns[0].trim(); + } else { + name = arrrecns[0].trim(); + surname = arrrecns.slice(1).join(' ').trim(); + } + } + arrAuthor.push({ name, surname }); + } + + return arrAuthor; + } + + /** + * Estrae gli autori dal campo "Autore". + */ + estraiAutori_FDV(autoreString) { + const arrrecauthor = autoreString.trim().split(','); + const arrAuthor = []; + + for (let i = 0; i < arrrecauthor.length; i += 2) { + const name = arrrecauthor[i].trim(); + const surname = arrrecauthor[i + 1]?.trim() || ''; + arrAuthor.push({ name, surname }); + } + + return arrAuthor; + } + + /** + * Gestisce l'editore del prodotto. + */ + async gestisciEditore(productInfo, product) { + if (product.publisher) { + const publisher = product.publisher.trim(); + const recpublisher = await Publisher.findOne({ idapp: this.idapp, name: publisher }).lean(); + + if (!recpublisher) { + const nuovoEditore = new Publisher({ idapp: this.idapp, name: publisher }); + await nuovoEditore.save(); + } + + productInfo.idPublisher = recpublisher?._id || nuovoEditore._id; + } + } + + /** + * Aggiorna l'immagine se necessario. + */ + async aggiornaImmagineSeNecessario(productInfo) { + const { prodInfo, aggiornatoimg } = await tools.downloadImgIfMissing(productInfo); + if (aggiornatoimg) { + await ProductInfo.findOneAndUpdate({ code: productInfo.code }, { $set: prodInfo }); + } + } + + /** + * Prepara una variazione del prodotto. + */ + preparaVariazione(product) { + return { + active: true, + versione: product.Versione, + status: product.Stato || null, + price: product.price ? parseFloat(tools.convertPriceEurToValue(product.price)) : null, + sale_price: product.sale_price ? parseFloat(tools.convertPriceEurToValue(product.sale_price)) : null, + formato: product.formato || '', + tipologia: product.Tipologia || '', + edizione: product.Edizione || '', + pagine: tools.isValidNumber(product.Pagine) ? tools.convstrToInt(product.Pagine) : 0, + misure: product.misure || '', + eta: product.eta || '', + addtocart_link: product.addtocart_link || '', + quantita: product.Quantita ? parseInt(product.Quantita) : 0, + preOrderDate: product.preOrderDate || null, + }; + } + + /** + * Aggiorna l'array delle variazioni. + */ + aggiornaVariazioni(arrvariazioni, nuovaVariazione) { + const ind = arrvariazioni.findIndex((x) => x.versione === nuovaVariazione.versione); + if (ind >= 0) { + arrvariazioni[ind] = nuovaVariazione; + } else { + arrvariazioni.push(nuovaVariazione); + } + return arrvariazioni.sort((a, b) => a.versione - b.versione); + } + /** + * Gestisce le variazioni del prodotto. + */ + async gestisciVariazioni(product, risrecInfo, { updated, imported, errors }) { + const queryprod = { idProductInfo: risrecInfo._id }; + const recold = await Product.findOne(queryprod).lean(); + const variazione = this.preparaVariazione(product); + + let risultupdate = null; + + if (recold) { + const arrvariazioni = this.aggiornaVariazioni(recold.arrvariazioni, variazione); + risultupdate = await Product.findOneAndUpdate(queryprod, { $set: { arrvariazioni } }); + } else { + const myproduct = { ...queryprod, arrvariazioni: [variazione] }; + risultupdate = await Product.findOneAndUpdate(queryprod, { $set: myproduct }, { new: true, upsert: true }); + imported++; + } + + console.log('risultupdate', risultupdate); + } +} + +module.exports = Macro; \ No newline at end of file diff --git a/src/server/router/admin_router.js b/src/server/router/admin_router.js index 191cab4..554fada 100755 --- a/src/server/router/admin_router.js +++ b/src/server/router/admin_router.js @@ -7,6 +7,9 @@ const shared_consts = require('../tools/shared_nodejs'); const tools = require('../tools/general'); +const Macro = require('../modules/Macro'); // Importa la classe Macro + + const fs = require('fs'); const { City } = require('../models/city'); @@ -407,141 +410,6 @@ function fixURL(url) { return url.replace(/https:\//g, 'https://'); } -async function downloadImgIfMissing(productInfo) { - - try { - if (tools.sulServer()) { - dirmain = ''; - } else { - dirmain = server_constants.DIR_PUBLIC_LOCALE; - } - - const vecchiomodo = false; - - if (productInfo.image_link && vecchiomodo) { - - const relativeimg = productInfo.image_link.split('/').pop(); - const img = tools.getdirByIdApp(productInfo.idapp) + dirmain + - server_constants.DIR_UPLOAD + '/products/' + productInfo.image_link.split('/').pop(); - const savePath = path.resolve(__dirname, img); // Sostituisci con il percorso dove salvare l'immagine - - let scaricaimg = !productInfo.imagefile || !fs.existsSync(savePath); - - if (!productInfo.imagefile && fs.existsSync(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 }; - } else { - scaricaimg = true; - } - } - - if (productInfo.imagefile && fs.existsSync(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 - scaricaimg = true; - } - } - - - if (scaricaimg && vecchiomodo) { - // Download image from the URL productInfo.image_link - productInfo.imagefile = relativeimg; - - const downloader = new ImageDownloader(); - - const aggiornatoimg = await downloader.downloadImage(productInfo.image_link, savePath, - { - maxRetries: 3, - initialDelay: 300, - timeout: 15000, - }).then(result => { - if (result) { - // console.log('Download completato con successo!'); - } else { - console.log('Download non riuscito.'); - } - - return result; - - }); - return { prodInfo: productInfo, aggiornatoimg: aggiornatoimg.ris }; - } - } - - let fileesistente = false; - if (productInfo.imagefile) { - // controlla se esiste il file - const img = tools.getdirByIdApp(productInfo.idapp) + dirmain + - server_constants.DIR_UPLOAD + '/products/' + productInfo.imagefile.split('/').pop(); - const filecompleto = path.resolve(__dirname, img); // Sostituisci con il percorso dove salvare l'immagine - - // Se non esiste lo scarico ! - fileesistente = fs.existsSync(filecompleto); - } - - if (!vecchiomodo && (!productInfo.image_link || !fileesistente)) { - - let scarica_da_sito = !productInfo.imagefile; - - if (!scarica_da_sito && productInfo.imagefile) { - scarica_da_sito = !fileesistente; // Se non esiste lo scarico ! - } - - if (scarica_da_sito) { - // date and time - productInfo.imagefile = 'img_' + new Date().toISOString().replace(/T/, ' ').replace(/\..+/, ''); - const img = tools.getdirByIdApp(productInfo.idapp) + dirmain + - server_constants.DIR_UPLOAD + '/products/' + 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 - - const downloader = new ImageDownloader(); - - - const aggiornatoimg = await downloader.downloadImage(link, savePath, - { - maxRetries: 3, - initialDelay: 300, - timeout: 15000, - nomefileoriginale: true, - }).then(result => { - if (result) { - // console.log('Download completato con successo!'); - } else { - console.log('Download non riuscito.'); - } - - return result; - - }); - if (aggiornatoimg.filepath) { - const filenamebase = path.basename(aggiornatoimg.filepath); - // const img = '/upload/products/' + filenamebase; - productInfo.imagefile = filenamebase; - } - - return { prodInfo: productInfo, aggiornatoimg: aggiornatoimg.ris }; - } else { - return { prodInfo: null, aggiornatoimg: false }; - } - } - - } catch (e) { - console.error('downloadImgIfMissing', e.message); - } - - return { prodInfo: null, aggiornatoimg: false }; - -} async function completaSettaggioProduct_AndProductInfo(arrcampi_productInfo, arrcampi_product, rec, product, productInfo) { @@ -1123,601 +991,16 @@ router.post('/import', authenticate, async (req, res) => { return res.status(200).send({ updated, imported, errors }); } else if (cmd === shared_consts.Cmd.MACRO_CATALOGO_JSON) { - let updated = 0; - let imported = 0; - let errors = 0; - - const ripopola = true; //++MODIFICARE! - - if (ripopola) { - dataObjects = null; - - try { - dataObjects = JSON.parse(`[${data.arrdata}]`); - } catch (e) { - dataObjects = null; - } - - if (dataObjects && dataObjects[0]) { - // Cancella la collection ImportaMacros - await Importamacro.deleteMany({ idapp }); - - // Aggiungi i record su ImportaMacros - for (const recinv of dataObjects[0]) { - let isnuovo = false - let setta = false - - let recmacro = recinv; - - recmacro.idapp = idapp; - - recmacro._id = recmacro.id; - - delete recmacro.id; - - // Ottengo isbn e Pagine da ImportaIsbn - - const recrankingisbn = await ImportaIsbn.findOne({ sku: recmacro.sku }).lean(); - if (recrankingisbn) { - if (!recmacro.isbn) { - recmacro.isbn = recrankingisbn.isbn; - } - // Se Pagine non sono state settate - if ((!recmacro.Pagine || recmacro.Pagine === 0) && recrankingisbn.Pagine) - recmacro.Pagine = recrankingisbn.Pagine; - - // Se misure non sono state settate - if (!recmacro.misure && recrankingisbn.misure) { - recmacro.misure = recrankingisbn.misure; - } - } - - let queryprod = { idapp, _id: recmacro._id }; - - try { - let risrec = await Importamacro.findOneAndUpdate(queryprod, { $set: recmacro }, { new: true, upsert: true, strict: false }); - if (risrec) { - imported++; - if (imported % 100 === 0) - console.log('Importati su dir Temporanea ', imported); - } - - } catch (e) { - console.error(e); - errors++; - } - } - } - - const cancella_categorie = false; - - if (cancella_categorie) { - await CatProd.deleteMany({ idapp }); - } + try { + const macro = new Macro(idapp); // Crea un'istanza della classe Macro + const result = await macro.importaCatalogo(data); // Chiama il metodo importaCatalogo + return res.status(200).send(result); + } catch (e) { + console.error(e.message); + return res.status(400).send(e); } - // Rileggi tutti i record di ImportaMacros - dataObjects = await Importamacro.find({ idapp }).lean(); - - console.log('*** INIZIO IMPORT PRODOTTI ... '); - - let indprod = 0; - let newprod = 0; - - let numprod = dataObjects.length; - - let nontrovati = 0; - - for (const product of dataObjects) { - let isnuovo = false - let setta = false - - let importa = true; - - - - if (!product.title || !product.sku) - importa = false; - - if (importa) { - let versGM = product.Versione ? product.Versione : ''; - - // split versioneGM in array with separated "," - let arrversGM = versGM.split(",").map(x => x.trim()); - - // se non esiste l'ISBN, allora me lo cerco in base a sku ! - - let trova = false - if (product._id === '30310') { - trova = true - } - - if (!product.isbn || product.isbn.startsWith('field')) { - const rectrovare = await ImportaIsbn.findOne({ sku: product.sku }).lean(); - if (rectrovare) { - // se l'isbn non inizia con 'field' allora è buono - if (rectrovare.isbn && !rectrovare.isbn.startsWith('field')) { - product.isbn = rectrovare.isbn; - } - } else { - nontrovati++; - // console.log(`${nontrovati} - ISBN non trovato [sku=${product.sku} title=${product.title}]`) - } - - } - - let productInfo = { - idapp: product.idapp, - code: product.isbn, - id_wp: product._id, - sku: product.sku, - - name: product.title, - description: product.description, - short_descr: product.short_descr, - publisher: product.editore, - collezione: product.Collezione, - // author: product.Autore ? product.Autore : '', - link: product.link ? product.link : '', - idCatProds: [], - idSubCatProds: [], - //img: 'upload/products/' + product.code + '.jpg', - // image_link: product.image_link ? product.image_link : '', - img2: product.img2 ? product.img2 : '', - img3: product.img3 ? product.img3 : '', - img4: product.img4 ? product.img4 : '', - checkout_link: product.checkout_link ? product.checkout_link : '', - } - const test = false; - - if (test) { - productInfo.imagefile = '' - productInfo.image_link = ''; - let { prodInfo, aggiornatoimg } = await downloadImgIfMissing(productInfo); - console.log('imagefile=', prodInfo.imagefile) - - } - - let esisteindb = await ProductInfo.findOne({ code: productInfo.code }).lean(); - if (esisteindb) { - productInfo.idCatProds = esisteindb.idCatProds; - productInfo.idSubCatProds = esisteindb.idSubCatProds; - } - - let versione = 0; - - if (indprod % 100 === 0) - console.log(indprod + '/' + numprod); - - - productInfo.productTypes = []; - // console.log('indprod', indprod, 'arrversGM', arrversGM, 'versione', product.Versione); - - for (let i = 0; i < arrversGM.length; i++) { - // Download, DVD, Epub, Mobi, Nuovo, PDF, Streaming, Usato - if (arrversGM[i] === 'Nuovo') - vers = shared_consts.PRODUCTTYPE.NUOVO - else if (arrversGM[i] === 'Usato') - vers = shared_consts.PRODUCTTYPE.USATO; - else if (arrversGM[i] === 'Download') - vers = shared_consts.PRODUCTTYPE.DOWNLOAD; - else if (arrversGM[i] === 'DVD') - vers = shared_consts.PRODUCTTYPE.DVD; - else if (arrversGM[i] === 'Epub') - vers = shared_consts.PRODUCTTYPE.EPUB; - else if (arrversGM[i] === 'Mobi') - vers = shared_consts.PRODUCTTYPE.MOBI; - else if (arrversGM[i] === 'PDF') - vers = shared_consts.PRODUCTTYPE.PDF; - else if (arrversGM[i] === 'Streaming') - vers = shared_consts.PRODUCTTYPE.STREAMING; - - if (i === 0) { - // salvati il primo, // nel 99,9% dei casi c'è solo 1 elemento (perchè queste sono tutte le variazioni) - versione = vers; - } - - 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$/, ""); - - const recrankingisbn = await ImportaIsbn.findOne({ sku: product.sku }).lean(); - - let reccateg = null; - - if (product.categories) { - // Verifica prima se questa categoria è stata aggiornata ! - if (recrankingisbn && recrankingisbn.DescrArgomento) { - - if (tools.isArray(recrankingisbn.ListaArgomenti) && recrankingisbn.ListaArgomenti.length > 1) { - console.log('ListaArgomenti STA RITORNANDO UN ARRAY !!!! ', recrankingisbn.ListaArgomenti); - } - - // !!!! - for (const idArgomento of recrankingisbn.ListaArgomenti) { - mycatstr = recrankingisbn.DescrArgomento; - - if (mycatstr) - productInfo = await updateProductInfo(productInfo, product, idapp, mycatstr); - } - - } else { - - arrcat = product.categories.trim().split(','); - productInfo.idCatProds = []; - for (const mycat of arrcat) { - let mycatstr = mycat.trim(); - - // Controlla se ci sono le sottocategorie: - arrsubcat = mycatstr.trim().split('>'); - - if (arrsubcat.length > 1) { - // Ci sono delle sottocategorie - mycatstr = arrsubcat[0].trim(); - product.subcat_name = arrsubcat[1].trim();; - } - - // Cerca la Categoria - reccateg = await CatProd.findOne({ idapp, name: mycatstr }).lean(); - if (!reccateg) { - // Non esiste questo produttore, quindi lo creo ! - reccateg = new CatProd({ idapp, name: mycatstr }); - ris = await reccateg.save(); - console.log('CREA con ARGOMENTO VECCHIO... ', mycatstr); - reccateg = await CatProd.findOne({ idapp, name: mycatstr }).lean(); - } - - if (reccateg) { - productInfo.idCatProds.push(reccateg._id); - } - } - } - } - - // "Autore" : "Silia,Marucelli, Stefano,Cattinelli", - let arrAuthor = []; - if (product.Autore) { - const arrrecauthor = product.Autore.trim().split(','); - - if (arrrecauthor.length >= 1) { - try { - let author = { - name: arrrecauthor[0].trim(), - } - if (arrrecauthor.length === 1) { - author = extractNameAndSurnameByComplete(arrrecauthor[0].trim()); - } else { - author.surname = arrrecauthor[1].trim(); - } - arrAuthor.push(author); - - if (arrrecauthor.length > 1) { - for (let i = 2; i < arrrecauthor.length; i = i + 2) { - try { - author = { - name: arrrecauthor[i].trim() - } - if (arrrecauthor.length > i + 1) { - author.surname = arrrecauthor[i + 1].trim() - } - arrAuthor.push(author); - } catch (e) { - } - } - } - productInfo.idAuthors = []; - - for (const myauthor of arrAuthor) { - // Cerca l'Autore - recauthor = await Author.findOne({ idapp, name: myauthor.name, surname: myauthor.surname }).lean(); - if (!recauthor) { - // Non esiste questo Autore, quindi lo creo ! - recauthor = new Author({ idapp, name: myauthor.name, surname: myauthor.surname }); - ris = await recauthor.save(); - recauthor = await Author.findOne({ idapp, name: myauthor.name, surname: myauthor.surname }).lean(); - } - - if (recauthor) { - productInfo.idAuthors.push(recauthor._id); - } - - } - - } catch (e) { - console.error(e); - } - } - } - - if (product.subcat_name) { - arrsubcat = product.subcat_name.trim().split(','); - productInfo.idSubCatProds = []; - for (const mysubcat of arrsubcat) { - let mysubcatstr = mysubcat.trim(); - - // Cerca la Sotto Categoria - let recsubcateg = await SubCatProd.findOne({ idapp, name: mysubcatstr }).lean(); - if (!recsubcateg) { - // Non esiste questa Sotto Categoria, quindi la creo ! - const idCatProd = reccateg ? reccateg._id : '' - recsubcateg = new SubCatProd({ idapp, name: mysubcatstr, idCatProd }); - ris = await recsubcateg.save(); - recsubcateg = await SubCatProd.findOne({ idapp, name: mysubcatstr, idCatProd }).lean(); - } - - if (recsubcateg) { - productInfo.idSubCatProds.push(recsubcateg._id); - } - } - } - if (productInfo.publisher) { - try { - publisher = productInfo.publisher.trim(); - // Cerca la Sotto Categoria - let recpublisher = await Publisher.findOne({ idapp, name: publisher }).lean(); - if (!recpublisher) { - // Non esiste questo Editore, quindi la creo ! - recpublisher = new Publisher({ idapp, name: publisher }); - ris = await recpublisher.save(); - recpublisher = await Publisher.findOne({ idapp, name: publisher }).lean(); - } - - if (recpublisher) { - productInfo.idPublisher = recpublisher._id; - } - } catch (e) { - console.error(e); - } - } - - - if (!product.hasOwnProperty('active')) { - product.active = true; - } - - // Update ProductInfo - let risrecInfo = await ProductInfo.findOneAndUpdate({ code: productInfo.code }, { $set: productInfo }, { new: true, upsert: true }); - if (risrecInfo) { - product.idProductInfo = risrecInfo._id; - recnewInfo = await ProductInfo.findOne({ code: productInfo.code }).lean(); - - let { prodInfo, aggiornatoimg } = await downloadImgIfMissing(recnewInfo); - - if (aggiornatoimg) { - await ProductInfo.findOneAndUpdate({ code: productInfo.code }, { $set: prodInfo }); - } - - if (risrecInfo._id) { - // Record existed, so it was updated - let arrfieldchange = tools.differentObjects(productInfo, recnewInfo); - if (arrfieldchange && arrfieldchange.length > 0) { - updated++; - console.log('Changed: ', recnewInfo.name + ': ' + arrfieldchange); - } - } - - // Cerca il GAS - let recGas = null; - if (product.gas_name) { - // Cerca il GAS - recGas = await Gasordine.findOne({ idapp, name: product.gas_name }).lean(); - } - - if (!recGas && !!product.gas_name) { - recGas = new Gasordine({ idapp, name: product.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(); - } - - let myproduct = {}; - - - let recProductExist = null; - // ISBN e versione del prodotto sono le chiavi uniche - let queryprod = { idProductInfo: product.idProductInfo }; - - if (recGas) { - queryprod = { ...queryprod, idGasordine: recGas._id }; - } - - recProductExist = await Product.findOne(queryprod).lean(); - - if (!recProductExist) { - isnuovo = true; - } - - let arrvariazioni = []; - if (isnuovo) { - myproduct.isbn = product.isbn; - myproduct.maxbookableGASQty = product.maxbookableGASQty ? product.maxbookableGASQty : null; - myproduct.active = product.active; - myproduct.idGasordine = recGas ? recGas._id : null; - myproduct.idProductInfo = product.idProductInfo; - myproduct.idapp = idapp; - } else { - arrvariazioni = recProductExist.arrvariazioni; - if (!arrvariazioni) { - arrvariazioni = []; - } - } - - // cerca l'indice della versione in arrvariazioni - let ind = arrvariazioni.findIndex(x => - x.versione === versione) - - let nuovaVariazione = ind < 0; - - // - let variazione = {}; - if (!nuovaVariazione) { - // Mantieni intatte questi campi del RECORD su DB: - variazione.quantita = arrvariazioni[ind].quantita; - } - - // *** CONTROLLA SE AGGIORNARE O MENO DETERMINATI CAMPI CHE SONO STATI GIA' SETTATI - if (recrankingisbn) { - if (product.misure !== recrankingisbn.misure && recrankingisbn.misure) { - product.misure = recrankingisbn.misure; - } - if (product.formato !== recrankingisbn.formato && recrankingisbn.formato) { - product.formato = recrankingisbn.formato; - } - if (product.Pagine !== recrankingisbn.Pagine && recrankingisbn.Pagine) { - product.Pagine = recrankingisbn.Pagine; - } - if (product.Edizione !== recrankingisbn.Edizione && recrankingisbn.Edizione) { - product.Edizione = recrankingisbn.Edizione; - } - } - - - variazione.active = true; // ++ ?? - variazione.versione = versione; - variazione.versione = versione; - variazione.status = product.Stato ? product.Stato : null; - variazione.price = product.price ? parseFloat(tools.convertPriceEurToValue(product.price)) : null; - variazione.sale_price = product.sale_price ? parseFloat(tools.convertPriceEurToValue(product.sale_price)) : null; - variazione.formato = product.formato ? product.formato : ''; - variazione.tipologia = product.Tipologia ? product.Tipologia : ''; - variazione.edizione = product.Edizione ? product.Edizione : ''; - variazione.pagine = tools.isValidNumber(product.Pagine) ? tools.convstrToInt(product.Pagine) : 0; - variazione.misure = product.misure ? product.misure : ''; - variazione.eta = product.eta ? product.eta : ''; - variazione.addtocart_link = product.addtocart_link ? product.addtocart_link : ''; - - - if (!options.aggiornaStockQty && !nuovaVariazione) { - // non aggiornare la Quantita in magazzino - } else if (product.Quantita) { - variazione.quantita = parseInt(product.Quantita); - } - variazione.preOrderDate = product.preOrderDate ? product.preOrderDate : null; - - // ----------------------------- - - if (ind >= 0) - arrvariazioni[ind] = variazione; // aggiorna il record "ind" in arrvariazioni - else - arrvariazioni.push(variazione); // aggiunge un nuovo record in arrvariazioni - - // Effettua l'ordinamento seguendo la "versione" - arrvariazioni.sort((a, b) => a.versione - b.versione); - - // Inserisce o aggiorna il record variazione nell'array delle variazioni, in base a "versione" - if (isnuovo) { - myproduct.arrvariazioni = arrvariazioni; - } - - let recold = await Product.findOne(queryprod).lean(); - - let risrec = null; - if (isnuovo) { - // CREA PRODUCT - risrec = await Product.findOneAndUpdate(queryprod, { $set: myproduct }, { new: true, upsert: true }); - } else { - // Esiste già, pertanto ci aggiorno arrvariazioni - risrec = await Product.findOneAndUpdate(queryprod, { $set: { arrvariazioni } }, { new: true, upsert: true }); - } - - let recnew = await Product.findOne(queryprod).lean(); - - if (risrec) { - if (risrec._id) { - - if (recold) { - // Record existed, so it was updated - let arrfieldchange = tools.differentObjects(recold, recnew); - if (arrfieldchange.length > 0) { - updated++; - let modif = ''; - for (const field of arrfieldchange) { - if (field === 'arrvariazioni') { - modif += field + ': ' - - // Controlla quali campi sono variati tra recold.arrvariazioni e recnew.arrvariazioni - for (const variazione of recnew.arrvariazioni) { - // trova la versione in recold.arrvariazioni - let ind = recold.arrvariazioni.findIndex(x => x.versione === variazione.versione); - - if (ind < 0) { - modif += 'Nuova Variazione [' + variazione.versione + '] ' + variazione.status + ' | Price: ' + variazione.price + ' -> Sale_Price: ' + variazione.sale_price + ' | '; - } else { - let oldvariazione = recold.arrvariazioni[ind]; - if (oldvariazione.status !== variazione.status) { - modif += 'Variazione [' + oldvariazione.versione + '] ' + variazione.status + ' -> ' + variazione.status; - } - if (oldvariazione.price !== variazione.price) { - modif += ' | Price: ' + oldvariazione.price + ' -> ' + variazione.price; - } - if (oldvariazione.sale_price !== variazione.sale_price) { - modif += ' | Sale Price: ' + oldvariazione.sale_price + ' -> ' + variazione.sale_price; - } - if (oldvariazione.formato !== variazione.formato) { - modif += ' | Formato: ' + oldvariazione.formato + ' -> ' + variazione.formato; - } - if (oldvariazione.tipologia !== variazione.tipologia) { - modif += ' | Tipologia: ' + oldvariazione.tipologia + ' -> ' + variazione.tipologia; - } - if (oldvariazione.edizione !== variazione.edizione) { - modif += ' | Edizione: ' + oldvariazione.edizione + ' -> ' + variazione.edizione; - } - if (oldvariazione.eta !== variazione.eta) { - modif += ' | Età: ' + oldvariazione.eta + ' -> ' + variazione.eta; - } - if (oldvariazione.preOrderDate !== variazione.preOrderDate) { - modif += ' | PreOrderDate: ' + oldvariazione.preOrderDate + ' -> ' + variazione.preOrderDate; - } - if (oldvariazione.addtocart_link !== variazione.addtocart_link) { - modif += ' | AddToCart: ' + oldvariazione.addtocart_link + ' -> ' + variazione.addtocart_link; - } - } - } - - } else { - modif += field + ': ' + recold[field] + ' -> ' + recnew[field] + ' | '; - } - - } - - console.log('Changed: [' + indprod + '/' + dataObjects.length + ']', productInfo.name, '[' + myproduct.idProductInfo + '] : ' + modif); - } - } else { - newprod++; - console.log('Nuovo Prodotto : [' + newprod + '/' + dataObjects.length + ']', productInfo.name); - } - } else { - // Record didn't exist, so it was created - imported++; - } - } else { - // risrec is null or undefined, indicating an error - console.error('Error: ', myproduct.productInfo.name); - errors++; - } - - await Product.singlerecconvert_AfterImport_AndSave(idapp, recnew, isnuovo); - } else { - console.error('Error ProductInfo: ', product.code); - errors++; - } - } - - indprod++; - } - - console.log('*** IMPORTATI: ', imported, '*** NUOVI: ', newprod, 'AGGIORNATI = ' + updated + ' (su ' + dataObjects.length + ' RECORD)'); - - return res.status(200).send({ updated, imported, errors }); } else if (cmd === shared_consts.Cmd.PRODUCTS) { dataObjects = JSON.parse(`[${data.arrdata}]`); @@ -2080,6 +1363,612 @@ router.post('/import', authenticate, async (req, res) => { }); +async function importaCatalogo(data) { + let updated = 0; + let imported = 0; + let errors = 0; + + try { + + const ripopola = true; //++MODIFICARE! + + if (ripopola) { + dataObjects = null; + + try { + dataObjects = JSON.parse(`[${data.arrdata}]`); + } catch (e) { + dataObjects = null; + } + + if (dataObjects && dataObjects[0]) { + // Cancella la collection ImportaMacros + await Importamacro.deleteMany({ idapp }); + + // Aggiungi i record su ImportaMacros + for (const recinv of dataObjects[0]) { + let isnuovo = false + let setta = false + + let recmacro = recinv; + + recmacro.idapp = idapp; + + recmacro._id = recmacro.id; + + delete recmacro.id; + + // Ottengo isbn e Pagine da ImportaIsbn + + const recrankingisbn = await ImportaIsbn.findOne({ sku: recmacro.sku }).lean(); + if (recrankingisbn) { + if (!recmacro.isbn) { + recmacro.isbn = recrankingisbn.isbn; + } + // Se Pagine non sono state settate + if ((!recmacro.Pagine || recmacro.Pagine === 0) && recrankingisbn.Pagine) + recmacro.Pagine = recrankingisbn.Pagine; + + // Se misure non sono state settate + if (!recmacro.misure && recrankingisbn.misure) { + recmacro.misure = recrankingisbn.misure; + } + } + + let queryprod = { idapp, _id: recmacro._id }; + + try { + let risrec = await Importamacro.findOneAndUpdate(queryprod, { $set: recmacro }, { new: true, upsert: true, strict: false }); + if (risrec) { + imported++; + if (imported % 100 === 0) + console.log('Importati su dir Temporanea ', imported); + } + + } catch (e) { + console.error(e); + errors++; + } + } + } + + const cancella_categorie = false; + + if (cancella_categorie) { + await CatProd.deleteMany({ idapp }); + } + + } + + // Rileggi tutti i record di ImportaMacros + dataObjects = await Importamacro.find({ idapp }).lean(); + + console.log('*** INIZIO IMPORT PRODOTTI ... '); + + let indprod = 0; + let newprod = 0; + + let numprod = dataObjects.length; + + let nontrovati = 0; + + for (const product of dataObjects) { + let isnuovo = false + let setta = false + + let importa = true; + + + + if (!product.title || !product.sku) + importa = false; + + if (importa) { + let versGM = product.Versione ? product.Versione : ''; + + // split versioneGM in array with separated "," + let arrversGM = versGM.split(",").map(x => x.trim()); + + // se non esiste l'ISBN, allora me lo cerco in base a sku ! + + let trova = false + if (product._id === '30310') { + trova = true + } + + if (!product.isbn || product.isbn.startsWith('field')) { + const rectrovare = await ImportaIsbn.findOne({ sku: product.sku }).lean(); + if (rectrovare) { + // se l'isbn non inizia con 'field' allora è buono + if (rectrovare.isbn && !rectrovare.isbn.startsWith('field')) { + product.isbn = rectrovare.isbn; + } + } else { + nontrovati++; + // console.log(`${nontrovati} - ISBN non trovato [sku=${product.sku} title=${product.title}]`) + } + + } + + let productInfo = { + idapp: product.idapp, + code: product.isbn, + id_wp: product._id, + sku: product.sku, + + name: product.title, + description: product.description, + short_descr: product.short_descr, + publisher: product.editore, + collezione: product.Collezione, + // author: product.Autore ? product.Autore : '', + link: product.link ? product.link : '', + idCatProds: [], + idSubCatProds: [], + //img: 'upload/products/' + product.code + '.jpg', + // image_link: product.image_link ? product.image_link : '', + img2: product.img2 ? product.img2 : '', + img3: product.img3 ? product.img3 : '', + img4: product.img4 ? product.img4 : '', + checkout_link: product.checkout_link ? product.checkout_link : '', + } + const test = false; + + if (test) { + productInfo.imagefile = '' + productInfo.image_link = ''; + let { prodInfo, aggiornatoimg } = await downloadImgIfMissing(productInfo); + console.log('imagefile=', prodInfo.imagefile) + + } + + let esisteindb = await ProductInfo.findOne({ code: productInfo.code }).lean(); + if (esisteindb) { + productInfo.idCatProds = esisteindb.idCatProds; + productInfo.idSubCatProds = esisteindb.idSubCatProds; + } + + let versione = 0; + + if (indprod % 100 === 0) + console.log(indprod + '/' + numprod); + + + productInfo.productTypes = []; + // console.log('indprod', indprod, 'arrversGM', arrversGM, 'versione', product.Versione); + + + // IdTipologia (Libri (1)) + for (let i = 0; i < arrversGM.length; i++) { + // Download, DVD, Epub, Mobi, Nuovo, PDF, Streaming, Usato + if (arrversGM[i] === 'Nuovo') + vers = shared_consts.PRODUCTTYPE.NUOVO + else if (arrversGM[i] === 'Usato') + vers = shared_consts.PRODUCTTYPE.USATO; + else if (arrversGM[i] === 'Download') + vers = shared_consts.PRODUCTTYPE.DOWNLOAD; + else if (arrversGM[i] === 'DVD') + vers = shared_consts.PRODUCTTYPE.DVD; + else if (arrversGM[i] === 'Epub') + vers = shared_consts.PRODUCTTYPE.EPUB; + else if (arrversGM[i] === 'Mobi') + vers = shared_consts.PRODUCTTYPE.MOBI; + else if (arrversGM[i] === 'PDF') + vers = shared_consts.PRODUCTTYPE.PDF; + else if (arrversGM[i] === 'Streaming') + vers = shared_consts.PRODUCTTYPE.STREAMING; + + if (i === 0) { + // salvati il primo, // nel 99,9% dei casi c'è solo 1 elemento (perchè queste sono tutte le variazioni) + versione = vers; + } + + 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$/, ""); + + const recrankingisbn = await ImportaIsbn.findOne({ sku: product.sku }).lean(); + + let reccateg = null; + + if (product.categories) { + // Verifica prima se questa categoria è stata aggiornata ! + if (recrankingisbn && recrankingisbn.DescrArgomento) { + + if (tools.isArray(recrankingisbn.ListaArgomenti) && recrankingisbn.ListaArgomenti.length > 1) { + console.log('ListaArgomenti STA RITORNANDO UN ARRAY !!!! ', recrankingisbn.ListaArgomenti); + } + + // !!!! + for (const idArgomento of recrankingisbn.ListaArgomenti) { + mycatstr = recrankingisbn.DescrArgomento; + + if (mycatstr) + productInfo = await updateProductInfo(productInfo, product, idapp, mycatstr); + } + + } else { + + arrcat = product.categories.trim().split(','); + productInfo.idCatProds = []; + for (const mycat of arrcat) { + let mycatstr = mycat.trim(); + + // Controlla se ci sono le sottocategorie: + arrsubcat = mycatstr.trim().split('>'); + + if (arrsubcat.length > 1) { + // Ci sono delle sottocategorie + mycatstr = arrsubcat[0].trim(); + product.subcat_name = arrsubcat[1].trim();; + } + + // Cerca la Categoria + reccateg = await CatProd.findOne({ idapp, name: mycatstr }).lean(); + if (!reccateg) { + // Non esiste questo produttore, quindi lo creo ! + reccateg = new CatProd({ idapp, name: mycatstr }); + ris = await reccateg.save(); + console.log('CREA con ARGOMENTO VECCHIO... ', mycatstr); + reccateg = await CatProd.findOne({ idapp, name: mycatstr }).lean(); + } + + if (reccateg) { + productInfo.idCatProds.push(reccateg._id); + } + } + } + } + + // "Autore" : "Silia,Marucelli, Stefano,Cattinelli", + let arrAuthor = []; + if (product.Autore) { + const arrrecauthor = product.Autore.trim().split(','); + + if (arrrecauthor.length >= 1) { + try { + let author = { + name: arrrecauthor[0].trim(), + } + if (arrrecauthor.length === 1) { + author = extractNameAndSurnameByComplete(arrrecauthor[0].trim()); + } else { + author.surname = arrrecauthor[1].trim(); + } + arrAuthor.push(author); + + if (arrrecauthor.length > 1) { + for (let i = 2; i < arrrecauthor.length; i = i + 2) { + try { + author = { + name: arrrecauthor[i].trim() + } + if (arrrecauthor.length > i + 1) { + author.surname = arrrecauthor[i + 1].trim() + } + arrAuthor.push(author); + } catch (e) { + } + } + } + productInfo.idAuthors = []; + + for (const myauthor of arrAuthor) { + // Cerca l'Autore + recauthor = await Author.findOne({ idapp, name: myauthor.name, surname: myauthor.surname }).lean(); + if (!recauthor) { + // Non esiste questo Autore, quindi lo creo ! + recauthor = new Author({ idapp, name: myauthor.name, surname: myauthor.surname }); + ris = await recauthor.save(); + recauthor = await Author.findOne({ idapp, name: myauthor.name, surname: myauthor.surname }).lean(); + } + + if (recauthor) { + productInfo.idAuthors.push(recauthor._id); + } + + } + + } catch (e) { + console.error(e); + } + } + } + + if (product.subcat_name) { + arrsubcat = product.subcat_name.trim().split(','); + productInfo.idSubCatProds = []; + for (const mysubcat of arrsubcat) { + let mysubcatstr = mysubcat.trim(); + + // Cerca la Sotto Categoria + let recsubcateg = await SubCatProd.findOne({ idapp, name: mysubcatstr }).lean(); + if (!recsubcateg) { + // Non esiste questa Sotto Categoria, quindi la creo ! + const idCatProd = reccateg ? reccateg._id : '' + recsubcateg = new SubCatProd({ idapp, name: mysubcatstr, idCatProd }); + ris = await recsubcateg.save(); + recsubcateg = await SubCatProd.findOne({ idapp, name: mysubcatstr, idCatProd }).lean(); + } + + if (recsubcateg) { + productInfo.idSubCatProds.push(recsubcateg._id); + } + } + } + if (productInfo.publisher) { + try { + publisher = productInfo.publisher.trim(); + // Cerca la Sotto Categoria + let recpublisher = await Publisher.findOne({ idapp, name: publisher }).lean(); + if (!recpublisher) { + // Non esiste questo Editore, quindi la creo ! + recpublisher = new Publisher({ idapp, name: publisher }); + ris = await recpublisher.save(); + recpublisher = await Publisher.findOne({ idapp, name: publisher }).lean(); + } + + if (recpublisher) { + productInfo.idPublisher = recpublisher._id; + } + } catch (e) { + console.error(e); + } + } + + + if (!product.hasOwnProperty('active')) { + product.active = true; + } + + // Update ProductInfo + let risrecInfo = await ProductInfo.findOneAndUpdate({ code: productInfo.code }, { $set: productInfo }, { new: true, upsert: true }); + if (risrecInfo) { + product.idProductInfo = risrecInfo._id; + recnewInfo = await ProductInfo.findOne({ code: productInfo.code }).lean(); + + let { prodInfo, aggiornatoimg } = await downloadImgIfMissing(recnewInfo); + + if (aggiornatoimg) { + await ProductInfo.findOneAndUpdate({ code: productInfo.code }, { $set: prodInfo }); + } + + if (risrecInfo._id) { + // Record existed, so it was updated + let arrfieldchange = tools.differentObjects(productInfo, recnewInfo); + if (arrfieldchange && arrfieldchange.length > 0) { + updated++; + console.log('Changed: ', recnewInfo.name + ': ' + arrfieldchange); + } + } + + // Cerca il GAS + let recGas = null; + if (product.gas_name) { + // Cerca il GAS + recGas = await Gasordine.findOne({ idapp, name: product.gas_name }).lean(); + } + + if (!recGas && !!product.gas_name) { + recGas = new Gasordine({ idapp, name: product.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(); + } + + let myproduct = {}; + + + let recProductExist = null; + // ISBN e versione del prodotto sono le chiavi uniche + let queryprod = { idProductInfo: product.idProductInfo }; + + if (recGas) { + queryprod = { ...queryprod, idGasordine: recGas._id }; + } + + recProductExist = await Product.findOne(queryprod).lean(); + + if (!recProductExist) { + isnuovo = true; + } + + let arrvariazioni = []; + if (isnuovo) { + myproduct.isbn = product.isbn; + myproduct.maxbookableGASQty = product.maxbookableGASQty ? product.maxbookableGASQty : null; + myproduct.active = product.active; + myproduct.idGasordine = recGas ? recGas._id : null; + myproduct.idProductInfo = product.idProductInfo; + myproduct.idapp = idapp; + } else { + arrvariazioni = recProductExist.arrvariazioni; + if (!arrvariazioni) { + arrvariazioni = []; + } + } + + // cerca l'indice della versione in arrvariazioni + let ind = arrvariazioni.findIndex(x => + x.versione === versione) + + let nuovaVariazione = ind < 0; + + // + let variazione = {}; + if (!nuovaVariazione) { + // Mantieni intatte questi campi del RECORD su DB: + variazione.quantita = arrvariazioni[ind].quantita; + } + + // *** CONTROLLA SE AGGIORNARE O MENO DETERMINATI CAMPI CHE SONO STATI GIA' SETTATI + if (recrankingisbn) { + if (product.misure !== recrankingisbn.misure && recrankingisbn.misure) { + product.misure = recrankingisbn.misure; + } + if (product.formato !== recrankingisbn.formato && recrankingisbn.formato) { + product.formato = recrankingisbn.formato; + } + if (product.Pagine !== recrankingisbn.Pagine && recrankingisbn.Pagine) { + product.Pagine = recrankingisbn.Pagine; + } + if (product.Edizione !== recrankingisbn.Edizione && recrankingisbn.Edizione) { + product.Edizione = recrankingisbn.Edizione; + } + } + + + variazione.active = true; // ++ ?? + variazione.versione = versione; + variazione.status = product.Stato ? product.Stato : null; + variazione.price = product.price ? parseFloat(tools.convertPriceEurToValue(product.price)) : null; + variazione.sale_price = product.sale_price ? parseFloat(tools.convertPriceEurToValue(product.sale_price)) : null; + variazione.formato = product.formato ? product.formato : ''; + variazione.tipologia = product.Tipologia ? product.Tipologia : ''; + variazione.edizione = product.Edizione ? product.Edizione : ''; + variazione.pagine = tools.isValidNumber(product.Pagine) ? tools.convstrToInt(product.Pagine) : 0; + variazione.misure = product.misure ? product.misure : ''; + variazione.eta = product.eta ? product.eta : ''; + variazione.addtocart_link = product.addtocart_link ? product.addtocart_link : ''; + + + if (!options.aggiornaStockQty && !nuovaVariazione) { + // non aggiornare la Quantita in magazzino + } else if (product.Quantita) { + variazione.quantita = parseInt(product.Quantita); + } + variazione.preOrderDate = product.preOrderDate ? product.preOrderDate : null; + + // ----------------------------- + + if (ind >= 0) + arrvariazioni[ind] = variazione; // aggiorna il record "ind" in arrvariazioni + else + arrvariazioni.push(variazione); // aggiunge un nuovo record in arrvariazioni + + // Effettua l'ordinamento seguendo la "versione" + arrvariazioni.sort((a, b) => a.versione - b.versione); + + // Inserisce o aggiorna il record variazione nell'array delle variazioni, in base a "versione" + if (isnuovo) { + myproduct.arrvariazioni = arrvariazioni; + } + + let recold = await Product.findOne(queryprod).lean(); + + let risrec = null; + if (isnuovo) { + // CREA PRODUCT + risrec = await Product.findOneAndUpdate(queryprod, { $set: myproduct }, { new: true, upsert: true }); + } else { + // Esiste già, pertanto ci aggiorno arrvariazioni + risrec = await Product.findOneAndUpdate(queryprod, { $set: { arrvariazioni } }, { new: true, upsert: true }); + } + + let recnew = await Product.findOne(queryprod).lean(); + + if (risrec) { + if (risrec._id) { + + if (recold) { + // Record existed, so it was updated + let arrfieldchange = tools.differentObjects(recold, recnew); + if (arrfieldchange.length > 0) { + updated++; + let modif = ''; + for (const field of arrfieldchange) { + if (field === 'arrvariazioni') { + modif += field + ': ' + + // Controlla quali campi sono variati tra recold.arrvariazioni e recnew.arrvariazioni + for (const variazione of recnew.arrvariazioni) { + // trova la versione in recold.arrvariazioni + let ind = recold.arrvariazioni.findIndex(x => x.versione === variazione.versione); + + if (ind < 0) { + modif += 'Nuova Variazione [' + variazione.versione + '] ' + variazione.status + ' | Price: ' + variazione.price + ' -> Sale_Price: ' + variazione.sale_price + ' | '; + } else { + let oldvariazione = recold.arrvariazioni[ind]; + if (oldvariazione.status !== variazione.status) { + modif += 'Variazione [' + oldvariazione.versione + '] ' + variazione.status + ' -> ' + variazione.status; + } + if (oldvariazione.price !== variazione.price) { + modif += ' | Price: ' + oldvariazione.price + ' -> ' + variazione.price; + } + if (oldvariazione.sale_price !== variazione.sale_price) { + modif += ' | Sale Price: ' + oldvariazione.sale_price + ' -> ' + variazione.sale_price; + } + if (oldvariazione.formato !== variazione.formato) { + modif += ' | Formato: ' + oldvariazione.formato + ' -> ' + variazione.formato; + } + if (oldvariazione.tipologia !== variazione.tipologia) { + modif += ' | Tipologia: ' + oldvariazione.tipologia + ' -> ' + variazione.tipologia; + } + if (oldvariazione.edizione !== variazione.edizione) { + modif += ' | Edizione: ' + oldvariazione.edizione + ' -> ' + variazione.edizione; + } + if (oldvariazione.eta !== variazione.eta) { + modif += ' | Età: ' + oldvariazione.eta + ' -> ' + variazione.eta; + } + if (oldvariazione.preOrderDate !== variazione.preOrderDate) { + modif += ' | PreOrderDate: ' + oldvariazione.preOrderDate + ' -> ' + variazione.preOrderDate; + } + if (oldvariazione.addtocart_link !== variazione.addtocart_link) { + modif += ' | AddToCart: ' + oldvariazione.addtocart_link + ' -> ' + variazione.addtocart_link; + } + } + } + + } else { + modif += field + ': ' + recold[field] + ' -> ' + recnew[field] + ' | '; + } + + } + + console.log('Changed: [' + indprod + '/' + dataObjects.length + ']', productInfo.name, '[' + myproduct.idProductInfo + '] : ' + modif); + } + } else { + newprod++; + console.log('Nuovo Prodotto : [' + newprod + '/' + dataObjects.length + ']', productInfo.name); + } + } else { + // Record didn't exist, so it was created + imported++; + } + } else { + // risrec is null or undefined, indicating an error + console.error('Error: ', myproduct.productInfo.name); + errors++; + } + + await Product.singlerecconvert_AfterImport_AndSave(idapp, recnew, isnuovo); + } else { + console.error('Error ProductInfo: ', product.code); + errors++; + } + } + + indprod++; + } + + console.log('*** IMPORTATI: ', imported, '*** NUOVI: ', newprod, 'AGGIORNATI = ' + updated + ' (su ' + dataObjects.length + ' RECORD)'); + + return res.status(200).send({ updated, imported, errors }); + + } catch (e) { + console.log(e.message); + return res.status(400).send(e); + } +} + router.post('/exec', authenticate, async (req, res) => { try { idapp = req.body.idapp; diff --git a/src/server/router/articleRoutes.js b/src/server/router/articleRoutes.js index fa328f9..c1d2969 100644 --- a/src/server/router/articleRoutes.js +++ b/src/server/router/articleRoutes.js @@ -1,5 +1,5 @@ const express = require("express"); -const { getArticlesSalesHandler, exportArticlesSalesByJSON, viewTable, saveTable, queryTable } = require("../controllers/articleController"); +const { getArticlesSalesHandler, exportArticlesSalesByJSON, viewTable, saveTable, queryTable, updateAllBook } = require("../controllers/articleController"); const { authenticate } = require("../middleware/authenticate"); const router = express.Router(); @@ -11,6 +11,9 @@ router.post("/export-articles-sales-json", authenticate, exportArticlesSalesByJS router.post("/view-table", authenticate, viewTable); router.post("/save-table", authenticate, saveTable); router.post("/query", authenticate, queryTable); +router.post("/updateAllBook", authenticate, updateAllBook); + + module.exports = router; diff --git a/src/server/router/products_router.js b/src/server/router/products_router.js index 673be42..d3266cb 100755 --- a/src/server/router/products_router.js +++ b/src/server/router/products_router.js @@ -89,7 +89,7 @@ router.get('/id/:id', async function (req, res) { var product = await Product.getProductById(id); - console.log('Product ID', id, product); + // console.log('Product ID', id, product); if (product) { return res.send({ code: server_constants.RIS_CODE_OK, product: product }); diff --git a/src/server/tools/general.js b/src/server/tools/general.js index 0cc9afc..864ba8f 100755 --- a/src/server/tools/general.js +++ b/src/server/tools/general.js @@ -6100,7 +6100,149 @@ module.exports = { date: dateObj, timestamp: dateObj.getTime() }; - } + }, + + getDateFromISOString(mydate) { + const mydate2 = new Date(mydate) + return mydate2 + }, + + async downloadImgIfMissing(productInfo) { + + try { + if (this.sulServer()) { + dirmain = ''; + } else { + dirmain = server_constants.DIR_PUBLIC_LOCALE; + } + + const vecchiomodo = false; + + if (productInfo.image_link && vecchiomodo) { + + const relativeimg = productInfo.image_link.split('/').pop(); + const img = this.getdirByIdApp(productInfo.idapp) + dirmain + + server_constants.DIR_UPLOAD + '/products/' + productInfo.image_link.split('/').pop(); + const savePath = path.resolve(__dirname, img); // Sostituisci con il percorso dove salvare l'immagine + + let scaricaimg = !productInfo.imagefile || !fs.existsSync(savePath); + + if (!productInfo.imagefile && fs.existsSync(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 }; + } else { + scaricaimg = true; + } + } + + if (productInfo.imagefile && fs.existsSync(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 + scaricaimg = true; + } + } + + + if (scaricaimg && vecchiomodo) { + // Download image from the URL productInfo.image_link + productInfo.imagefile = relativeimg; + + const downloader = new ImageDownloader(); + + const aggiornatoimg = await downloader.downloadImage(productInfo.image_link, savePath, + { + maxRetries: 3, + initialDelay: 300, + timeout: 15000, + }).then(result => { + if (result) { + // console.log('Download completato con successo!'); + } else { + console.log('Download non riuscito.'); + } + + return result; + + }); + return { prodInfo: productInfo, aggiornatoimg: aggiornatoimg.ris }; + } + } + + let fileesistente = false; + if (productInfo.imagefile) { + // controlla se esiste il file + const img = this.getdirByIdApp(productInfo.idapp) + dirmain + + server_constants.DIR_UPLOAD + '/products/' + productInfo.imagefile.split('/').pop(); + const filecompleto = path.resolve(__dirname, img); // Sostituisci con il percorso dove salvare l'immagine + + // Se non esiste lo scarico ! + fileesistente = fs.existsSync(filecompleto); + } + + if (!vecchiomodo && (!productInfo.image_link || !fileesistente)) { + + let scarica_da_sito = !productInfo.imagefile; + + if (!scarica_da_sito && productInfo.imagefile) { + scarica_da_sito = !fileesistente; // Se non esiste lo scarico ! + } + + if (scarica_da_sito) { + // date and time + productInfo.imagefile = 'img_' + new Date().toISOString().replace(/T/, ' ').replace(/\..+/, ''); + const img = this.getdirByIdApp(productInfo.idapp) + dirmain + + server_constants.DIR_UPLOAD + '/products/' + 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 + + const downloader = new ImageDownloader(); + + + const aggiornatoimg = await downloader.downloadImage(link, savePath, + { + maxRetries: 3, + initialDelay: 300, + timeout: 15000, + nomefileoriginale: true, + }).then(result => { + if (result) { + // console.log('Download completato con successo!'); + } else { + console.log('Download non riuscito.'); + } + + return result; + + }); + if (aggiornatoimg.filepath) { + const filenamebase = path.basename(aggiornatoimg.filepath); + // const img = '/upload/products/' + filenamebase; + productInfo.imagefile = filenamebase; + } + + return { prodInfo: productInfo, aggiornatoimg: aggiornatoimg.ris }; + } else { + return { prodInfo: null, aggiornatoimg: false }; + } + } + + } catch (e) { + console.error('downloadImgIfMissing', e.message); + } + + return { prodInfo: null, aggiornatoimg: false }; + + }, + diff --git a/src/server/tools/shared_nodejs.js b/src/server/tools/shared_nodejs.js index 0e983be..e80f9aa 100755 --- a/src/server/tools/shared_nodejs.js +++ b/src/server/tools/shared_nodejs.js @@ -1187,6 +1187,7 @@ module.exports = { CmdQueryMs: { GET: 0, SET: 1, + UPDATE: 2, }, SENDRIS_CODES: {