From 1d52ab1d082ee22b93d7582eeae65329e72a40a8 Mon Sep 17 00:00:00 2001 From: Surya Paolo Date: Sat, 27 Sep 2025 17:24:46 +0200 Subject: [PATCH] - corretto gruppomacro catalogo, info prodotti, estrazione dati da amazon corretto. --- src/server/models/orderscart.js | 2 +- src/server/models/product.js | 33 +++- src/server/models/t_web_articolifatturati.js | 1 + src/server/models/t_web_ordini.js | 2 + src/server/modules/Macro.js | 178 +++++++++++-------- src/server/modules/Scraping.js | 39 ++-- src/server/router/admin_router.js | 34 +--- src/server/router/api_router.js | 17 +- src/server/server.js | 2 +- src/server/tools/general.js | 71 ++++---- 10 files changed, 214 insertions(+), 165 deletions(-) diff --git a/src/server/models/orderscart.js b/src/server/models/orderscart.js index 0d39923..530ee80 100755 --- a/src/server/models/orderscart.js +++ b/src/server/models/orderscart.js @@ -277,7 +277,7 @@ module.exports.getOrdersCartByQuery = async function (query) { if (item.order.idProduct) { item.order.idProduct.productInfo = item.order.idProduct.productInfo ? item.order.idProduct.productInfo : { ...item.order.idProduct.idProductInfo }; item.order.idProduct.productInfo.unitstr = tools.getUnitsMeasure(item.order.idProduct.productInfo.unit, true); - item.order.idProduct.idProductInfo = item.order.idProduct.productInfo ? item.order.idProduct.productInfo._id : ''; + // item.order.idProduct.idProductInfo = item.order.idProduct.productInfo ? item.order.idProduct.productInfo._id : ''; } const myid = item.order._id; // console.log('ID ORD', order.numorder, myid, order.user.name); diff --git a/src/server/models/product.js b/src/server/models/product.js index 440a031..e32cb68 100755 --- a/src/server/models/product.js +++ b/src/server/models/product.js @@ -293,7 +293,6 @@ const productSchema = new Schema({ ], price_acquistato: { type: Number, - required: true, }, after_price: { type: String, @@ -1379,15 +1378,13 @@ module.exports.resetImageNotFound = async function () { 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 !!` + mylog = `Rimuovo ${arrproduct.length} product senza date_updated_fromGM !!` console.log(mylog); for (const product of arrproduct) { @@ -1406,3 +1403,31 @@ module.exports.removeProductInfoWithoutDateUpdatedFromGM = async function (idapp return mylog; }; +module.exports.HideProductInfoWithoutDateUpdatedFromGM = async function (idapp) { + const Product = this; + + let mylog; + + try { + const arrproduct = await Product.find({ idapp, 'productInfo.date_updated_fromGM': { $exists: false } }); + + if (arrproduct.length > 0 && arrproduct.length < 1000) { + mylog = `Nascondo ${arrproduct.length} product senza date_updated_fromGM !!` + console.log(mylog); + + for (const product of arrproduct) { + await Product.updateOne( + { _id: product._id }, + { $unset: { date_updated_fromGM: true } } + ); + } + } + + return mylog; + } catch (error) { + mylog += 'Error Hide productInfo without date_updated_fromGM:' + error; + console.error(mylog); + } + + return mylog; +}; diff --git a/src/server/models/t_web_articolifatturati.js b/src/server/models/t_web_articolifatturati.js index 2d3f5aa..4f202fc 100755 --- a/src/server/models/t_web_articolifatturati.js +++ b/src/server/models/t_web_articolifatturati.js @@ -1,5 +1,6 @@ const mongoose = require('mongoose'); +const Product = require('./product'); // Definizione dello schema const articoliFatturatiSchema = new mongoose.Schema({ diff --git a/src/server/models/t_web_ordini.js b/src/server/models/t_web_ordini.js index ea15d11..876bd76 100755 --- a/src/server/models/t_web_ordini.js +++ b/src/server/models/t_web_ordini.js @@ -18,6 +18,8 @@ PrimaCopiaDaSpedire - int () const mongoose = require('mongoose'); +const Product = require('./product'); + // Definizione dello schema const ordiniSchema = new mongoose.Schema({ Codice: { diff --git a/src/server/modules/Macro.js b/src/server/modules/Macro.js index c4a8645..d111960 100644 --- a/src/server/modules/Macro.js +++ b/src/server/modules/Macro.js @@ -443,11 +443,8 @@ class Macro { let count = 0; if (Array.isArray(recproducts)) { if (recproducts.length > 10 && lavoromassivo && options.rimuovieventualiCancellati) { - // disattiva dalla tabella productInfo tutti i campi date_updated_fromGM - const result = await Product.updateMany( - { idapp: options.idapp }, - { $unset: { 'productInfo.date_updated_fromGM': null } } - ); + // disattiva dalla tabella product tutti i campi date_updated_fromGM + const result = await Product.updateMany({ idapp: options.idapp }, { $unset: { date_updated_fromGM: null } }); let quanti_rimossi = result.modifiedCount; console.log(`Sbianca date_updated_fromGM da Product: (${quanti_rimossi} su ${result.matchedCount})`); rimuoviTabellePerIniziare = true; @@ -476,7 +473,7 @@ class Macro { } for (const recproduct of recproducts) { - await this.elaboraProdotto(recproduct, opt); + await this.elaboraProdotto(recproduct, opt, recproducts.length === 1); const sku = recproduct.IdArticolo; @@ -496,7 +493,7 @@ class Macro { } if (rimuoviTabellePerIniziare && options.rimuovieventualiCancellati) { - await ProductInfo.removeProductInfoWithoutDateUpdatedFromGM(options.idapp); + await Product.HideProductInfoWithoutDateUpdatedFromGM(options.idapp); } if (myjob) await myjob.terminateJob(); } @@ -621,55 +618,87 @@ class Macro { /** * Elabora un singolo prodotto. */ - async elaboraProdotto(productInput, options) { + async elaboraProdotto(productInput, options, forzacaricamento = false) { let isnuovo = false, setta = false, importa = true; let product = { ...productInput, deleted: false }; - if (options.inputdaGM) product = await this.convertiDaCampiGMACampoFDV_ProductInfo(options.idapp, product); + try { + if (options.inputdaGM) product = await this.convertiDaCampiGMACampoFDV_ProductInfo(options.idapp, product); - if (!product.title || !product.sku) importa = false; + if (!product.title || !product.sku) importa = false; - if (importa) { - product.productInfo = this.preparaProductInfo(product); + if (importa) { + if (this.localoptions?.importadaFDV) { + const recrankingisbn = await ImportaIsbn.findOne({ sku: product.sku }).lean(); + if (recrankingisbn) { + this.aggiornaCampiDaIsbn(product, recrankingisbn); + } + } - if (this.localoptions?.importadaFDV) { - const recrankingisbn = await ImportaIsbn.findOne({ sku: product.sku }).lean(); - if (recrankingisbn) { - this.aggiornaCampiDaIsbn(product, recrankingisbn); + if (!product.hasOwnProperty('active')) { + product.active = true; + } + + //Aggiorna il campo product + let risprod = await Product.findOneAndUpdate( + { isbn: product.isbn }, + { $set: product }, + { new: true, upsert: false, returnOriginal: false } + ).lean(); + + product.productInfo = this.preparaProductInfo(product); + await this.gestisciCategorie(product); + await this.gestisciAutori(product); + await this.gestisciEditore(product); + await this.gestisciCollana(product); + + // Se non lo trovo allora lo salvo come nuovo. + const dataFutura = new Date(product.productInfo.date_pub) > new Date(); // è da pubblicare ? + if (!risprod && (forzacaricamento || product.stockQty > 0 || dataFutura)) { + await Product.create(product); + risprod = await Product.findOne({ isbn: product.isbn }).lean(); + } else { + risprod = await Product.findOne({ isbn: product.isbn }).lean(); + } + + if (risprod) { + this.queryprod = { _id: risprod._id }; + + await this.gestisciGasOrdine(product); + await this.gestisciVariazioni(product, options); + + + const imagefile = await this.aggiornaImmagineSeNecessario(risprod, forzacaricamento || dataFutura); + if (imagefile) { + product.productInfo.imagefile = imagefile; + } + + // aggiorna productInfo + let risprodInfo = await Product.findOneAndUpdate( + { isbn: product.isbn }, + { $set: { productInfo: product.productInfo } }, + { new: true, upsert: false, returnOriginal: false } + ).lean(); + + // prodotto risprodInfo trovato ? + if (risprodInfo) { + // console.log('Prodotto trovato:', product.productInfo.name, product.productInfo.code); + } + } else { + console.error( + 'Prodotto non trovato:', + product.productInfo.name, + product.productInfo.code + 'qta=' + product.stockQty + ); + options.errors++; } } - - if (!product.hasOwnProperty('active')) { - product.active = true; - } - - await this.gestisciCategorie(product); - await this.gestisciAutori(product); - await this.gestisciEditore(product); - await this.gestisciCollana(product); - - const risrecInfo = await Product.findOneAndUpdate( - { code: productInfo.code }, - { $set: productInfo }, - { new: true, upsert: true, returnOriginal: false } - ).lean(); - - if (risrecInfo) { - product.idProductInfo = risrecInfo._id; - this.queryprod = { idProductInfo: product.idProductInfo }; - - const aggiornatoimg = await this.aggiornaImmagineSeNecessario(risrecInfo); - if (!aggiornatoimg?.delete) { - await this.gestisciGasOrdine(product, risrecInfo); - await this.gestisciVariazioni(product, risrecInfo, options); - } - } else { - console.error('Errore ProductInfo:', product.code); - options.errors++; - } + } catch (e) { + console.error('Errore nel gestire il prodotto:', e); + options.errors++; } } @@ -721,10 +750,14 @@ class Macro { img3: product.img3 || undefined, img4: product.img4 || undefined, checkout_link: product.checkout_link || undefined, - idStatoProdotto: product.productInfo.idStatoProdotto || undefined, + idStatoProdotto: product.idStatoProdotto || undefined, date_pub: product.date_pub || undefined, sottotitolo: product.sottotitolo || undefined, ...(product.date_updated_fromGM ? { date_updated_fromGM: product.date_updated_fromGM } : {}), + ...(product.link_macro ? { link_macro: product.link_macro } : {}), + ...(product.descrizione_completa_macro + ? { descrizione_completa_macro: product.descrizione_completa_macro } + : {}), }; } catch (e) { console.error('Errore preparaProductInfo :', e); @@ -807,10 +840,10 @@ class Macro { // Controlla se il Titolo esiste nella tabella temporanea let titolo = productGM.Titolo; - + const tabdescr = await ImportaDescr.findOne({ code: productGM.Ean13 }).lean(); if (tabdescr?.title) { - titolo = tabdescr.title + titolo = tabdescr.title; } const recproduct = { @@ -842,10 +875,18 @@ class Macro { // addtocart_link: '', stockQty: productGM.QtaDisponibile || undefined, date_pub: productGM.DataPubblicazione ? tools.getDateFromISOString(productGM.DataPubblicazione) : null, - sottotitolo: productGM.Sottotitolo, productTypes: [shared_consts.PRODUCTTYPE.PRODUCT], date_updated_fromGM: new Date(), idStorehouses: [recstorehouse._id], + ...(tabdescr?.descrizione ? { descrizione_breve_macro: tools.getvalueByJsonText(tabdescr?.descrizione) } : {}), + ...(tabdescr?.descrizione_completa + ? { descrizione_completa_macro: tools.getvalueByJsonText(tabdescr?.descrizione_completa) } + : {}), + ...(tabdescr?.sottotitolo + ? { sottotitolo: tools.getvalueByJsonText(tabdescr?.sottotitolo) } + : { sottotitolo: productGM.Sottotitolo }), + // ...(tabdescr?.titolo ? { name: tools.getvalueByJsonText(tabdescr?.titolo) } : {}), + ...(tabdescr?.url ? { link_macro: tools.getvalueByJsonText(tabdescr?.url) } : {}), }; let vers = 0; @@ -878,7 +919,6 @@ class Macro { await nuovaCategoria.save(); } - if (!reccateg?.idArgomento && product.DescrArgomento) { // Se non c'è l'argomento, allora lo cerco nel DB const recarg = await T_Web_Argomenti.findOne({ Descrizione: product.DescrArgomento }).lean(); @@ -888,9 +928,10 @@ class Macro { } } - const myriscat = reccateg?._id || (nuovaCategoria ? nuovaCategoria._id : null); - if (myriscat) product.productInfo.idCatProds.push(myriscat); + if (myriscat) { + product.productInfo.idCatProds.push(myriscat); + } } else { if (product.categories) { // const arrcat = product.categories.trim().split(','); @@ -908,7 +949,9 @@ class Macro { } const myriscat = reccateg?._id || (nuovaCategoria ? nuovaCategoria._id : null); - if (myriscat) product.productInfo.idCatProds.push(myriscat); + if (myriscat) { + product.productInfo.idCatProds.push(myriscat); + } } } } @@ -1007,7 +1050,8 @@ class Macro { return; } } - if (recpublisher?._id || nuovoEditore?._id) product.productInfo.idPublisher = recpublisher?._id || nuovoEditore._id; + if (recpublisher?._id || nuovoEditore?._id) + product.productInfo.idPublisher = recpublisher?._id || nuovoEditore._id; } } @@ -1035,13 +1079,13 @@ class Macro { /** * Aggiorna l'immagine se necessario. */ - async aggiornaImmagineSeNecessario(product) { - const { prodInfo, aggiornatoimg } = await tools.downloadImgIfMissing(product); + async aggiornaImmagineSeNecessario(product, forzacaricamento) { + const { imagefile, aggiornatoimg } = await tools.downloadImgIfMissing(product, forzacaricamento); if (aggiornatoimg) { - await Product.findOneAndUpdate({ _id: product._id }, { $set: { productInfo: prodInfo } }); + return imagefile; } - return aggiornatoimg; + return null; } /** @@ -1079,21 +1123,19 @@ class Macro { } else { arrvariazioni.push(nuovaVariazione); } + // rimuovi le variazioni senza versione + arrvariazioni = arrvariazioni.filter((v) => v.versione); return arrvariazioni.sort((a, b) => a.versione - b.versione); } /** * Gestisce le variazioni del prodotto. */ - async gestisciVariazioni(product, risrecInfo, options) { + async gestisciVariazioni(product, options) { const recold = await Product.findOne(this.queryprod).lean(); const variazione = this.preparaVariazione(product); const myproduct = { ...product, - ...(!product.isbn ? [{ isbn: risrecInfo.code }] : []), - ...(!product.maxbookableGASQty && risrecInfo.maxbookableGASQty - ? [{ maxbookableGASQty: risrecInfo.maxbookableGASQty }] - : []), idapp: this.idapp, arrvariazioni: [variazione], }; @@ -1101,7 +1143,7 @@ class Macro { let risultupdate = null; if (recold) { - const arrvariazioni = this.aggiornaVariazioni(recold.arrvariazioni, variazione); + let arrvariazioni = this.aggiornaVariazioni(recold.arrvariazioni, variazione); const updatedDoc = await Product.findOneAndUpdate( this.queryprod, { $set: { arrvariazioni } }, @@ -1121,10 +1163,6 @@ class Macro { options.idRecUpdated = wasUpserted ? updatedDoc.lastErrorObject.upserted : updatedDoc.value._id; } } - - if (recold.isbn !== risrecInfo.code) { - product.isbn = risrecInfo.code; - } } if (!recold || this.isModified(recold, myproduct) || !this.recProductExist) { const updatedDoc = await Product.findOneAndUpdate( @@ -1172,10 +1210,10 @@ class Macro { async getStat() { let mystr = ''; - const ris = await ProductInfo.countDocuments({ + const ris = await Product.countDocuments({ $or: [{ date_updated_fromGM: { $exists: false } }, { date_updated_fromGM: null }], }); - mystr += `${ris} ProductInfo non aggiornati da GM, quindi da cancellare ! \n`; + mystr += `${ris} Product non aggiornati da GM, quindi da nascondere ! \n`; return mystr; } diff --git a/src/server/modules/Scraping.js b/src/server/modules/Scraping.js index b983c4f..e555e08 100644 --- a/src/server/modules/Scraping.js +++ b/src/server/modules/Scraping.js @@ -53,7 +53,7 @@ class AmazonBookScraper { }); return { html: data, url }; } catch (err) { - console.error(`Errore fetching isbn10 ${isbn10} (ISBN:${isbn}) (tentativo ${attempt}):`, err.message); + console.error(`Errore fetching ${url} per isbn10 ${isbn10} (ISBN:${isbn}) (tentativo ${attempt}):`, err.message); if (attempt < retryLimit) { console.log(`Riprovo tra ${delay / 1000} secondi...`); @@ -699,7 +699,7 @@ class AmazonBookScraper { try { // Prendi solo quelli che non sono ancora stati scraped ! - const products = await Product.aggregate([ + const query = [ // Filtro di base sui campi idapp, isbn, scraped, e scraped_error { $match: { @@ -711,25 +711,9 @@ class AmazonBookScraper { */ }, }, - // Popoliamo il campo idProductInfo - { - $lookup: { - from: 'productinfos', // Nome della collezione per 'idProductInfo' - localField: 'idProductInfo', // Campo del documento corrente (Product) - foreignField: '_id', // Campo di riferimento in ProductInfo - as: 'idProductInfo', // Campo in cui verranno inseriti i dati popolati - }, - }, - // De-strutturiamo l'array idProductInfo, se è un array - { - $unwind: { - path: '$idProductInfo', - preserveNullAndEmptyArrays: true, // Mantieni i documenti anche se idProductInfo è null o vuoto - }, - }, { $match: { - 'idProductInfo.idStatoProdotto': { $in: [1, 4, 34, 45, 46] }, // Condizione su idStatoProdotto + 'productInfo.idStatoProdotto': { $in: [1, 4, 34, 45, 46] }, // Condizione su idStatoProdotto }, }, // Proiettiamo solo i campi necessari @@ -741,17 +725,18 @@ class AmazonBookScraper { title: 1, sottotitolo: 1, arrvariazioni: 1, - 'idProductInfo._id': 1, - 'idProductInfo.date_pub': 1, - 'idProductInfo.name': 1, - 'idProductInfo.sottotitolo': 1, - 'idProductInfo.idStatoProdotto': 1, - 'idProductInfo.link_macro': 1, - 'idProductInfo.imagefile': 1, + 'productInfo.date_pub': 1, + 'productInfo.name': 1, + 'productInfo.sottotitolo': 1, + 'productInfo.idStatoProdotto': 1, + 'productInfo.link_macro': 1, + 'productInfo.imagefile': 1, }, }, // A questo punto, puoi aggiungere altre operazioni di aggregazione se necessario (e.g., ordinamento) - ]); + ]; + + const products = await Product.aggregate(query); // console.log(products); diff --git a/src/server/router/admin_router.js b/src/server/router/admin_router.js index 428ca3d..f98b767 100755 --- a/src/server/router/admin_router.js +++ b/src/server/router/admin_router.js @@ -974,20 +974,6 @@ async function completaSettaggioProduct_AndProductInfo( } } - if (rec.hasOwnProperty('old_code')) { - const old_code = rec['old_code']; - let oldrec = await ProductInfo.findOne({ code: old_code }).lean(); - if (oldrec) { - const precid = productInfo._id; - const preccode = productInfo.code; - - productInfo = oldrec; - if (precid) productInfo._id = precid; - else delete productInfo._id; - - productInfo.code = preccode; - } - } if (rec.hasOwnProperty('productTypes')) { productInfo.productTypes = productInfo.productTypes; } else { @@ -1291,7 +1277,7 @@ router.post('/import', authenticate, async (req, res) => { ); // Update ProductInfo, non crea nuovi record ! - let risrecInfo = await ProductInfo.findOneAndUpdate( + let risrecInfo = await Product.findOneAndUpdate( { code: productInfo.code }, { $set: productInfo }, { new: true, upsert: false } @@ -1413,7 +1399,7 @@ router.post('/import', authenticate, async (req, res) => { if (risrecInfo) { productImported.productInfo = risrecInfo._id; - recnewInfo = await ProductInfo.findOne({ code: productInfo.code }).lean(); + recnewInfo = await Product.findOne({ code: product.code }).lean(); if (risrecInfo._id) { // Record existed, so it was updated @@ -1564,22 +1550,20 @@ router.post('/import', authenticate, async (req, res) => { productInfo.productTypes = [shared_consts.PRODUCTTYPE.PRODUCT]; } - let esisteindb = await ProductInfo.findOne({ code: productInfo.code }).lean(); + let esisteindb = await Product.findOne({ code: productInfo.code }).lean(); - // Update ProductInfo - let risrecInfo = await ProductInfo.findOneAndUpdate( - { code: productInfo.code }, - { $set: productInfo }, + // Update Product + let risrecInfo = await Product.findOneAndUpdate( + { code: product.code }, + { $set: product }, { new: true, upsert: true } ); if (risrecInfo) { - product.idProductInfo = risrecInfo._id; - - recnewInfo = await ProductInfo.findOne({ code: productInfo.code }).lean(); + recnewInfo = await Product.findOne({ code: product.code }).lean(); if (risrecInfo._id) { // Record existed, so it was updated - let arrfieldchange = tools.differentObjects(productInfo, recnewInfo); + let arrfieldchange = tools.differentObjects(productInfo, recnewInfo.productInfo); if (arrfieldchange && arrfieldchange.length > 0) { // updated++; console.log('Changed: ', recnewInfo.name + ': ' + arrfieldchange); diff --git a/src/server/router/api_router.js b/src/server/router/api_router.js index e25023b..b2881f1 100644 --- a/src/server/router/api_router.js +++ b/src/server/router/api_router.js @@ -386,7 +386,10 @@ router.post('/search-books', authenticate, async (req, res) => { for (const book of books) { let trovatoISBN = false; let trovato = false; + let productfind = null; + for (let field of book) { + field = field.trim(); let valido = typeof field === 'string' && field.length > 4 && field.length < 50; if (valido) { @@ -400,7 +403,7 @@ router.post('/search-books', authenticate, async (req, res) => { // Priorità se lo trovo per ISBN: if (productInfoarrISBN.length === 1) { - productInfo = productInfoarrISBN[0]; + productfind = productInfoarrISBN[0]; trovatoISBN = true; trovato = true; } @@ -412,12 +415,12 @@ router.post('/search-books', authenticate, async (req, res) => { 'productInfo.name': field, }).exec(); if (productarrTitle.length === 1) { - productInfo = productarrTitle[0]; + productfind = productarrTitle[0]; trovato = true; } else { if (productarrTitle.length > 1) { // Prendi l'Ultimo ! - productInfo = productarrTitle[productarrTitle.length - 1]; + productfind = productarrTitle[productarrTitle.length - 1]; trovato = true; } } @@ -428,12 +431,12 @@ router.post('/search-books', authenticate, async (req, res) => { 'productInfo.name': new RegExp(`.*${escapeRegExp(tools.removeAccents(field.toUpperCase()))}.*`, 'i'), }).exec(); if (productarrTitle.length === 1) { - productInfo = productarrTitle[0]; + productfind = productarrTitle[0]; trovato = true; } else { if (productarrTitle.length > 1) { // Prendi l'Ultimo ! - productInfo = productarrTitle[productarrTitle.length - 1]; + productfind = productarrTitle[productarrTitle.length - 1]; trovato = true; } } @@ -444,8 +447,8 @@ router.post('/search-books', authenticate, async (req, res) => { } if (trovato) { - if (productInfo) { - product = await Product.findOne({ idProductInfo: productInfo._id }).exec(); + if (productfind) { + product = await Product.findOne({ _id: productfind._id }).exec(); if (product) { const existingResult = results.find((r) => r._id.toString() === product._id.toString()); if (!existingResult) { diff --git a/src/server/server.js b/src/server/server.js index 9dafa4a..d6faaba 100755 --- a/src/server/server.js +++ b/src/server/server.js @@ -751,7 +751,7 @@ connectToDatabase(connectionUrl, options) // ⏱️ Timeout globale per la connessione TCP server.setTimeout(timeoutMs, () => { - console.log(`TCP timeout su server: ${hostname}:${port}`); + console.log(`TCP timeout su server: ${hostname}:${port} ${website}`); }); // ⏱️ Timeout per singola richiesta HTTP diff --git a/src/server/tools/general.js b/src/server/tools/general.js index 1806e60..7d1d1b6 100755 --- a/src/server/tools/general.js +++ b/src/server/tools/general.js @@ -1767,7 +1767,8 @@ module.exports = { if (idapp === 0) idapp = '13'; - if (idapp === '13') { // this.RISO + if (idapp === '13') { + // this.RISO queryadmins = { username: 'surya1977', idapp }; } @@ -5782,7 +5783,12 @@ module.exports = { try { // let dir = this.getdirByIdApp(idapp) + dirmain + '/' + this.getDirUpload(); - let dir = this.getdirByIdApp(idapp) + '/' + this.getDirUpload() + shared_consts.getDirectoryImgByTable(table, username) + dirmain; + let dir = + this.getdirByIdApp(idapp) + + '/' + + this.getDirUpload() + + shared_consts.getDirectoryImgByTable(table, username) + + dirmain; img = dir + img; @@ -5844,7 +5850,6 @@ module.exports = { //} if (myurl.startsWith('http://127.0.0.1')) { //myurl = myurl.replace('http://127.0.0.1:8084/', 'https://riso.app/') - // Se è in locale allora metti una foto finta... // myurl = // 'https://images.unsplash.com/photo-1464047736614-af63643285bf?q=80&w=2874&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D'; @@ -5940,7 +5945,7 @@ module.exports = { return mydate2; }, - async downloadImgIfMissing(product) { + async downloadImgIfMissing(product, forzacaricamento = false) { const Product = require('../models/product'); try { @@ -5950,40 +5955,37 @@ module.exports = { dirmain = server_constants.DIR_PUBLIC_LOCALE; } - /*if (true) { - const prova = await this.isFileExistsAsync('prova'); - console.log('PROVA:', prova); - }*/ - const vecchiomodo = false; + let imagefile = product.productInfo.imagefile; + if (product.productInfo.image_link && vecchiomodo) { const relativeimg = product.productInfo.image_link.split('/').pop(); const img = - this.getdirByIdApp(product.productInfo.idapp) + + this.getdirByIdApp(product.idapp) + dirmain + server_constants.DIR_UPLOAD + '/products/' + product.productInfo.image_link.split('/').pop(); const savePath = path.resolve(__dirname, img); // Sostituisci con il percorso dove salvare l'immagine - let scaricaimg = !product.productInfo.imagefile || !(await this.isFileExistsAsync(savePath)); + let scaricaimg = !imagefile || !(await this.isFileExistsAsync(savePath)); - if (!product.productInfo.imagefile && (await this.isFileExistsAsync(savePath))) { + if (!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 - product.productInfo.imagefile = relativeimg; - return { prodInfo: product.productInfo, aggiornatoimg: true }; + imagefile = relativeimg; + return { imagefile, aggiornatoimg: true }; } else { scaricaimg = true; } } - if (product.productInfo.imagefile && (await this.isFileExistsAsync(savePath))) { + if (imagefile && (await this.isFileExistsAsync(savePath))) { // esiste il file, ma sul DB non è corretto const stats = fs.statSync(savePath); // Ottieni informazioni sul file @@ -5995,7 +5997,7 @@ module.exports = { if (scaricaimg && vecchiomodo) { // Download image from the URL productInfo.image_link - product.productInfo.imagefile = relativeimg; + imagefile = relativeimg; const downloader = new ImageDownloader(); @@ -6014,19 +6016,19 @@ module.exports = { return result; }); - return { prodInfo: product.productInfo, aggiornatoimg: aggiornatoimg.ris }; + return { imagefile, aggiornatoimg: aggiornatoimg.ris }; } } let fileesistente = false; - if (product.productInfo.imagefile && product.productInfo.imagefile !== 'noimg.jpg') { + if (imagefile && imagefile !== 'noimg.jpg') { // controlla se esiste il file const img = - this.getdirByIdApp(product.productInfo.idapp) + + this.getdirByIdApp(product.idapp) + dirmain + server_constants.DIR_UPLOAD + '/products/' + - product.productInfo.imagefile.split('/').pop(); + imagefile.split('/').pop(); const filecompleto = path.resolve(__dirname, img); // Sostituisci con il percorso dove salvare l'immagine // Se non esiste lo scarico ! @@ -6034,21 +6036,22 @@ module.exports = { } if (!vecchiomodo && (!product.productInfo.image_link || !fileesistente)) { - let scarica_da_sito = !product.productInfo.imagefile || product.productInfo.imagefile === 'noimg.jpg'; + let scarica_da_sito = !imagefile || imagefile === 'noimg.jpg'; - if (!scarica_da_sito && product.productInfo.imagefile) { + if (!scarica_da_sito && imagefile) { scarica_da_sito = !fileesistente; // Se non esiste lo scarico ! } - if (scarica_da_sito && !product.productInfo.image_not_found) { + if ((scarica_da_sito && !product.productInfo.image_not_found) || forzacaricamento) { // date and time - product.productInfo.imagefile = 'img_' + new Date().toISOString().replace(/T/, ' ').replace(/\..+/, ''); + imagefile = + 'img_' + new Date().toISOString().replace(/T/, '').replace(/\..+/, '').replace(/:/, '').replace(/./, ''); const img = - this.getdirByIdApp(product.productInfo.idapp) + + this.getdirByIdApp(product.idapp) + dirmain + server_constants.DIR_UPLOAD + '/products/' + - product.productInfo.imagefile.split('/').pop(); + 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=' + product.productInfo.sku; @@ -6084,19 +6087,19 @@ module.exports = { if (aggiornatoimg?.filepath) { const filenamebase = path.basename(aggiornatoimg.filepath); // const img = '/upload/products/' + filenamebase; - product.productInfo.imagefile = filenamebase; + imagefile = filenamebase; } - return { prodInfo: product.productInfo, aggiornatoimg: aggiornatoimg.ris }; + return { imagefile, aggiornatoimg: aggiornatoimg.ris }; } else { - return { prodInfo: null, aggiornatoimg: false }; + return { imagefile: null, aggiornatoimg: false }; } } } catch (e) { console.error('downloadImgIfMissing', e.message); } - return { prodInfo: null, aggiornatoimg: false }; + return { imagefile: null, aggiornatoimg: false }; }, removeAccents(mystr) { @@ -6220,4 +6223,12 @@ module.exports = { return mydate; }, + getvalueByJsonText(valore) { + if (valore && valore['#text']) { + if (valore['#text']) return valore['#text']; + else return value; + } + + return null; + }, };