- Modifiche a ProductInfo... Continua

This commit is contained in:
Surya Paolo
2025-08-29 23:34:08 +02:00
parent 2ee710b748
commit fcbc64cea8
24 changed files with 1006 additions and 1010 deletions

34
.vscode/launch.json vendored
View File

@@ -1,7 +1,7 @@
{ {
"version": "0.2.0", "version": "0.2.0",
"configurations": [ "configurations": [
{ {
"type": "node", "type": "node",
"request": "launch", "request": "launch",
@@ -61,5 +61,37 @@
"TESTING_ON": "1" "TESTING_ON": "1"
} }
}, },
{
"type": "node",
"request": "launch",
"name": "Debug CheckSmartBot",
"program": "${workspaceFolder}/../checksmartbot/bot.js",
"console": "integratedTerminal",
"outFiles": [
"${workspaceFolder}/../**/*.js"
],
"envFile": "${workspaceFolder}/.env",
"skipFiles": [
"<node_internals>/**"
],
"autoAttachChildProcesses": true,
"smartStep": true
},
{
"type": "node",
"request": "launch",
"name": "Avvia bot con pm2 (attach)",
"runtimeExecutable": "pm2",
"runtimeArgs": [
"start",
"bot.js",
"--name",
"checksmartbot"
],
"console": "integratedTerminal",
"restart": true,
"port": 9229,
"attach": true
}
] ]
} }

View File

@@ -237,7 +237,7 @@ exports.getTableContentBase = async (options) => {
GROUP BY IdArticolo GROUP BY IdArticolo
) b ON T.IdArticolo = b.IdArticolo AND T.DataOra = b.data ` + ) b ON T.IdArticolo = b.IdArticolo AND T.DataOra = b.data ` +
(options.campispeciali (options.campispeciali
? ` ? `
RIGHT JOIN RIGHT JOIN
( SELECT ( SELECT
e.IdStatoProdotto, e.IdStatoProdotto,
@@ -302,10 +302,9 @@ ON
GROUP BY IdArgomento GROUP BY IdArgomento
) h ON g2.IdArgomento = h.IdArgomento AND g2.DataOra = h.data12 ) h ON g2.IdArgomento = h.IdArgomento AND g2.DataOra = h.data12
) i2 ON T.ListaArgomenti = i2.IdArgomento ) i2 ON T.ListaArgomenti = i2.IdArgomento
`+ ` +
(options.showQtaDisponibile (options.showQtaDisponibile
? ` RIGHT JOIN(
? ` RIGHT JOIN(
SELECT o.Codice, o.QtaDisponibile SELECT o.Codice, o.QtaDisponibile
FROM T_WEB_Disponibile o FROM T_WEB_Disponibile o
JOIN( JOIN(
@@ -314,8 +313,8 @@ ON
GROUP BY Codice GROUP BY Codice
) p ON o.Codice = p.Codice AND o.DataOra = p.data1 ) p ON o.Codice = p.Codice AND o.DataOra = p.data1
) q ON T.IdArticolo = q.Codice` ) q ON T.IdArticolo = q.Codice`
: ``) + : ``) +
` RIGHT JOIN( ` RIGHT JOIN(
SELECT a3.IdMarchioEditoriale, a3.Descrizione as CasaEditrice SELECT a3.IdMarchioEditoriale, a3.Descrizione as CasaEditrice
FROM T_WEB_MarchiEditoriali a3 FROM T_WEB_MarchiEditoriali a3
JOIN( JOIN(
@@ -816,17 +815,17 @@ exports.viewTable = async (req, res) => {
exports.updateLocalDb = async (tableContent, options) => { exports.updateLocalDb = async (tableContent, options) => {
try { try {
const ProductInfo = require('../models/productInfo'); const Product = require('../models/product');
const CatProd = require('../models/catprod'); const CatProd = require('../models/catprod');
let recproductInfo = { const code = tableContent.Ean13.trim();
code: tableContent.Ean13.trim(),
};
let risrecUpdated = null; let risrecUpdated = null;
const recfound = await ProductInfo.findOne({ code: recproductInfo.code }).lean(); const recfound = await Product.findOne({ 'productInfo.code': code }).lean();
if (recfound) { if (recfound) {
const recproductInfo = recfound.productInfo;
ListaArgomenti = tableContent.ListaArgomenti; ListaArgomenti = tableContent.ListaArgomenti;
let arrayPulito = ListaArgomenti.trim() // Rimuove gli spazi all'inizio e alla fine let arrayPulito = ListaArgomenti.trim() // Rimuove gli spazi all'inizio e alla fine
@@ -835,7 +834,7 @@ exports.updateLocalDb = async (tableContent, options) => {
if (arrayPulito && arrayPulito.length > 0) { if (arrayPulito && arrayPulito.length > 0) {
let aggiornacat = false; let aggiornacat = false;
const precCatProds = recfound.idCatProds; const precCatProds = recfound.productInfo.idCatProds;
let reccatprods = []; let reccatprods = [];
for (let i = 0; i < arrayPulito.length; i++) { for (let i = 0; i < arrayPulito.length; i++) {
const idArgomento = parseInt(arrayPulito[i]); const idArgomento = parseInt(arrayPulito[i]);
@@ -882,9 +881,9 @@ exports.updateLocalDb = async (tableContent, options) => {
} }
if (aggiorna) { if (aggiorna) {
risrecUpdated = await ProductInfo.findOneAndUpdate( risrecUpdated = await Product.findOneAndUpdate(
{ code: recproductInfo.code }, { _id: recfound._id },
{ $set: recproductInfo }, { $set: { productInfo: recproductInfo } },
{ new: true, upsert: true } { new: true, upsert: true }
); );
} }

View File

@@ -194,25 +194,29 @@ CatalogSchema.statics.getCatalogById = async function (id) {
try { try {
let arrrec = await Catalog.find({ _id: id }) let arrrec = await Catalog.find({ _id: id })
.populate({ .populate({
path: 'lista_prodotti', // Popola il campo lista_prodotti path: 'lista_prodotti',
populate: { populate: [
path: 'idProductInfo', {
model: 'ProductInfo', path: 'productInfo.idCatProds',
populate: [ model: 'CatProd',
{ },
path: 'idCatProds', {
model: 'CatProd', path: 'productInfo.idSubCatProds',
}, model: 'SubCatProd',
{ },
path: 'idSubCatProds', {
model: 'SubCatProd', path: 'productInfo.idAuthors',
}, model: 'Author',
{ },
path: 'idAuthors', {
model: 'Author', path: 'productInfo.idCollana',
}, model: 'Collana',
], },
}, {
path: 'productInfo.idPublisher',
model: 'Publisher',
},
],
}) })
.populate({ .populate({
path: 'lista_prodotti', path: 'lista_prodotti',
@@ -254,11 +258,11 @@ CatalogSchema.statics.getCatalogById = async function (id) {
const originalLength = catalog.lista_prodotti.length; const originalLength = catalog.lista_prodotti.length;
catalog.lista_prodotti = catalog.lista_prodotti.filter( catalog.lista_prodotti = catalog.lista_prodotti.filter(
(product) => (product) =>
product.idProductInfo && product.productInfo &&
product.idProductInfo.code && product.productInfo.code &&
product.idProductInfo.code !== '' && product.productInfo.code !== '' &&
product.idProductInfo.imagefile && product.productInfo.imagefile &&
product.idProductInfo.imagefile !== 'noimg.jpg' && product.productInfo.imagefile !== 'noimg.jpg' &&
!product.delete !product.delete
); );
if (catalog.lista_prodotti.length !== originalLength) { if (catalog.lista_prodotti.length !== originalLength) {
@@ -272,17 +276,16 @@ CatalogSchema.statics.getCatalogById = async function (id) {
lista_prodotti: catalog.lista_prodotti.map((product) => ({ lista_prodotti: catalog.lista_prodotti.map((product) => ({
...product.toObject(), ...product.toObject(),
productInfo: { productInfo: {
...product.idProductInfo.toObject(), // Copia tutti i campi di idProductInfo ...product.productInfo,
catprods: product.idProductInfo.idCatProds, // Rinomina idCatProds in catprods catprods: product.productInfo.idCatProds,
subcatprods: product.idProductInfo.idSubCatProds, subcatprods: product.productInfo.idSubCatProds,
collana: product.idProductInfo.idCollana, collana: product.productInfo.idCollana,
authors: product.idProductInfo.idAuthors, authors: product.productInfo.idAuthors,
}, },
producer: product.idProducer, producer: product.idProducer,
storehouse: product.idStorehouses, storehouse: product.idStorehouses,
scontisticas: product.idScontisticas, scontisticas: product.idScontisticas,
gasordine: product.idGasordine, gasordine: product.idGasordine,
idProductInfo: product.idProductInfo._id, // CHECK
})), })),
})); }));

View File

@@ -62,13 +62,13 @@ CatProdSchema.statics.findAllIdApp = async function (idapp) {
return await CatProd.find(myfind).sort({ name: 1 }).lean(); return await CatProd.find(myfind).sort({ name: 1 }).lean();
}; };
CatProdSchema.statics.updateCatDeleteEmpty = async function (idapp) { /*CatProdSchema.statics.updateCatDeleteEmpty = async function (idapp) {
try { try {
const toDelete = await CatProd.aggregate([ const toDelete = await CatProd.aggregate([
{ $match: { idapp } }, { $match: { idapp } },
{ {
$lookup: { $lookup: {
from: 'productinfos', from: 'products',
localField: '_id', localField: '_id',
foreignField: 'idCatProds', foreignField: 'idCatProds',
as: 'products' as: 'products'
@@ -99,7 +99,7 @@ CatProdSchema.statics.updateCatDeleteEmpty = async function (idapp) {
return error; return error;
} }
}; };*/
CatProdSchema.statics.getCatProdWithTitleCount = async function (idapp, updatedata) { CatProdSchema.statics.getCatProdWithTitleCount = async function (idapp, updatedata) {
try { try {
@@ -108,9 +108,9 @@ CatProdSchema.statics.getCatProdWithTitleCount = async function (idapp, updateda
{ $match: { idapp } }, { $match: { idapp } },
{ {
$lookup: { $lookup: {
from: 'productinfos', // Nome della tua collezione productInfo from: 'products', // Nome della tua collezione productInfo
localField: '_id', localField: '_id',
foreignField: 'idCatProds', foreignField: 'productInfo.idCatProds',
as: 'products' as: 'products'
} }
}, },

View File

@@ -63,9 +63,9 @@ module.exports.getCollaneWithTitleCount = async function (idapp, updatedata) {
{ $match: { idapp } }, { $match: { idapp } },
{ {
$lookup: { $lookup: {
from: 'productinfos', // Nome della tua collezione productInfo from: 'products', // Nome della tua collezione productInfo
localField: '_id', localField: '_id',
foreignField: 'idCollana', foreignField: 'productInfo.idCollana',
as: 'products' as: 'products'
} }
}, },

View File

@@ -168,20 +168,6 @@ module.exports.findAllIdApp = async function (idapp) {
as: 'product', as: 'product',
}, },
}, },
{
$lookup: {
from: 'productinfos',
localField: 'product.idProduct',
foreignField: '_id',
as: 'product.productInfo',
},
},
{
$unwind: {
path: '$product.productInfo',
preserveNullAndEmptyArrays: true,
},
},
{ {
$lookup: { $lookup: {
from: 'producers', from: 'producers',
@@ -358,20 +344,6 @@ module.exports.getTotalOrderById = async function (id) {
preserveNullAndEmptyArrays: true, preserveNullAndEmptyArrays: true,
}, },
}, },
{
$lookup: {
from: 'productinfos',
localField: 'product.idProductInfo',
foreignField: '_id',
as: 'product.productInfo',
},
},
{
$unwind: {
path: '$product.productInfo',
preserveNullAndEmptyArrays: true,
},
},
{ {
$lookup: { $lookup: {
from: 'producers', from: 'producers',
@@ -637,19 +609,6 @@ module.exports.GeneraCSVOrdineProdotti = async function () {
preserveNullAndEmptyArrays: true, preserveNullAndEmptyArrays: true,
}, },
}, },
{
$lookup: {
from: 'productinfos',
localField: 'product.idProductInfo',
foreignField: '_id',
as: 'productInfo',
},
},
{
$unwind: {
path: '$productInfo',
},
},
{ {
$lookup: { $lookup: {
from: 'gasordines', from: 'gasordines',
@@ -682,8 +641,8 @@ module.exports.GeneraCSVOrdineProdotti = async function () {
{ {
$group: { $group: {
_id: '$product._id', _id: '$product._id',
name: { $first: '$productInfo.name' }, name: { $first: '$product.productInfo.name' },
weight: { $first: '$productInfo.weight' }, weight: { $first: '$product.productInfo.weight' },
price_acquistato: { $first: '$product.price_acquistato' }, price_acquistato: { $first: '$product.price_acquistato' },
totalQuantity: { $sum: { $add: ['$quantity', '$quantitypreordered'] } }, totalQuantity: { $sum: { $add: ['$quantity', '$quantitypreordered'] } },
totalPrice_acquistato: { totalPrice_acquistato: {

View File

@@ -10,7 +10,6 @@ const Storehouse = require('../models/storehouse');
const Provider = require('../models/provider'); const Provider = require('../models/provider');
const Gasordine = require('../models/gasordine'); const Gasordine = require('../models/gasordine');
const Product = require('../models/product'); const Product = require('../models/product');
const ProductInfo = require('../models/productInfo');
const { Circuit } = require('../models/circuit'); const { Circuit } = require('../models/circuit');
@@ -225,10 +224,6 @@ module.exports.getOrdersCartByQuery = async function (query) {
populate: { populate: {
path: 'idProduct', path: 'idProduct',
model: 'Product', model: 'Product',
populate: {
path: 'idProductInfo',
model: 'ProductInfo'
}
} }
}) })
.populate({ .populate({

View File

@@ -39,7 +39,181 @@ const productSchema = new Schema({
isbn: { isbn: {
type: String, type: String,
}, },
idProductInfo: { type: Schema.Types.ObjectId, ref: 'ProductInfo', index: true }, idProductInfo: { type: Schema.Types.ObjectId, ref: 'ProductInfo', index: true }, //@@@ DA CANCELLARE DOPO DELLA CONVERSIONE
productInfo: {
department: {
type: String, ref: 'Department'
},
sku: {
type: String,
},
code: {
type: String,
required: true,
},
codice: {
type: String,
}, // codice interno prodotto
id_wp: {
type: String,
}, // id in wordpress
codice_EAN: {
type: String,
},
barcode: {
type: String,
},
name: {
type: String,
index: true,
},
description: {
type: String,
},
short_descr: {
type: String,
},
idCatProds: [{
type: Schema.Types.ObjectId, ref: 'CatProd', index: true
}],
idSubCatProds: [{
type: Schema.Types.ObjectId, ref: 'SubCatProd'
}],
idStatoProdotto: {
type: Number, index: true
},
color: {
type: String
},
size: {
type: String // 11x4x3
},
weight: {
type: Number
},
weight_lordo: {
type: Number
},
unit: {
type: Number,
},
unit_lordo: {
type: Number,
},
sfuso: {
type: Boolean
}, // serve se moltiplicare le qta (es: 12 kg) oppure fare (2 x 20 ml)
vegan: {
type: Boolean
},
icon: {
type: String,
},
img: {
type: String,
},
imagefile: {
type: String,
},
image_not_found: {
type: Boolean,
},
vers_img: {
type: Number,
},
image_link: {
type: String,
},
link_scheda: {
type: String,
},
link: {
type: String,
},
checkout_link: {
type: String,
},
versioneGM: {
type: String,
},
img2: {
type: String,
},
img3: {
type: String,
},
img4: {
type: String,
},
ingredienti: {
type: String,
},
valori_nutrizionali: {
type: String,
},
note: {
type: String,
},
idAuthors: [{
type: Schema.Types.ObjectId, ref: 'Author', index: true
}],
idCollana: {
type: Schema.Types.ObjectId, ref: 'Collana', index: true
},
idPublisher: {
type: Schema.Types.ObjectId, ref: 'Publisher', index: true
},
collezione: {
type: String,
},
ListaArgomenti: {
type: String,
},
date_pub: {
type: Date,
index: 1,
},
date_pub_ts: {
type: Number,
},
productTypes: [{
type: Number,
}],
date_updated: {
type: Date,
},
date_updated_fromGM: {
type: Date,
},
totVen: Number,
totFat: Number,
vLast3M: Number,
fatLast3M: Number,
fatLast6M: Number,
fatLast1Y: Number,
fatLast2Y: Number,
vLast6M: {
type: Number,
index: true,
},
vLast1Y: {
type: Number, index: true
},
vLast2Y: Number,
dataUltimoOrdine: Date,
rank3M: Number,
rank6M: Number,
rank1Y: Number,
descrizione_breve_macro: String,
descrizione_completa_macro: String,
descr_trafiletto_catalogo: String,
sottotitolo: String,
link_macro: String,
},
idProducer: { type: Schema.Types.ObjectId, ref: 'Producer', index: true }, idProducer: { type: Schema.Types.ObjectId, ref: 'Producer', index: true },
idStorehouses: [{ type: Schema.Types.ObjectId, ref: 'Storehouse', index: true }], idStorehouses: [{ type: Schema.Types.ObjectId, ref: 'Storehouse', index: true }],
idGasordine: { type: Schema.Types.ObjectId, ref: 'Gasordine', index: true }, idGasordine: { type: Schema.Types.ObjectId, ref: 'Gasordine', index: true },
@@ -367,20 +541,6 @@ module.exports.executeQueryPickup = async function (idapp, params) {
} }
let aggr2 = [ let aggr2 = [
{
$lookup: {
from: 'productinfos',
localField: 'idProductInfo',
foreignField: '_id',
as: 'productInfo',
},
},
{
$unwind: {
path: '$productInfo',
preserveNullAndEmptyArrays: true,
},
},
{ {
$lookup: { $lookup: {
from: 'authors', from: 'authors',
@@ -606,15 +766,6 @@ module.exports.findAllIdApp = async function (idapp, code, id, all, isbn) {
}, },
{ $unwind: { path: '$producer', preserveNullAndEmptyArrays: true } }, { $unwind: { path: '$producer', preserveNullAndEmptyArrays: true } },
{
$lookup: {
from: 'productinfos',
localField: 'idProductInfo',
foreignField: '_id',
as: 'productInfo',
},
},
{ $unwind: { path: '$productInfo', preserveNullAndEmptyArrays: true } },
{ {
$match: { $match: {
'productInfo.code': { $exists: true, $ne: '' }, 'productInfo.code': { $exists: true, $ne: '' },
@@ -1054,3 +1205,208 @@ module.exports.singlerecconvert_AfterImport_AndSave = async function (idapp, pro
console.error('Err', e); console.error('Err', e);
} }
}; };
// ---------------------------------------------
module.exports.replaceProductImgToImageFile = async function (abilitaserver) {
const Product = this;
if (abilitaserver) {
// const result = await ProductInfo.updateMany({ "img": { $exists: true } }, { $rename: { 'img': 'imagefile' } });
// Trova tutti i documenti con il campo 'img' che esiste
const documents = await Product.find({ "productInfo.img": { $exists: true } });
// Aggiorna ciascun documento
for (let doc of documents) {
if (doc.img && doc.img.startsWith('upload/products/')) {
// Rimuovi il prefisso '/upload/products' dal campo `img`
doc.imagefile = doc.img.replace(/^\upload\/products\//, '');
doc.img = undefined; // Può anche rimuovere il campo img corrente se desiderato
await doc.save(); // Salva il documento aggiornato
}
}
console.log(`Updated ${documents.length} document(s) with new imagefile paths.`);
} else {
const documents = await Product.find({ "productInfo.imagefile": { $exists: true } });
// Aggiorna ciascun documento
for (let doc of documents) {
if (doc.imagefile && doc.imagefile.startsWith('upload/products/')) {
// Rimuovi il prefisso '/upload/products' dal campo `img`
doc.imagefile = doc.imagefile.replace(/^\upload\/products\//, '');
await doc.save(); // Salva il documento aggiornato
}
}
console.log(`Updated ${documents.length} document(s) with new imagefile paths.`);
}
// await Product.updateMany({}, { 'vers_img': 0 });
console.log(`Updated ${result.modifiedCount} document(s).`);
};
module.exports.correggiProductTypes = async function () {
const Product = this;
const bulkOps = [];
try {
// Fase di aggregazione
const cursor = Product.aggregate([
{
$project: {
_id: 1,
'productInfo.productType': 1,
'productInfo.productTypes': [{ $ifNull: ['$productType', 10] }]
}
}
]).cursor({ batchSize: 1000 }).exec();
// Itera attraverso ogni documento utilizzando il cursore
for await (const doc of cursor) {
bulkOps.push({
updateOne: {
filter: { _id: doc._id },
update: {
$set: { 'productInfo.productTypes': doc.productTypes },
$unset: { 'productInfo.productType': "" }
}
}
});
// Scrivi i batch di operazioni ogni 1000 documenti
if (bulkOps.length === 1000) {
await Product.bulkWrite(bulkOps);
bulkOps.length = 0;
}
}
// Scrivi eventuali operazioni rimanenti
if (bulkOps.length > 0) {
await Produc.bulkWrite(bulkOps);
}
console.log('ProductInfo.productType converted to productTypes array and saved');
} catch (err) {
console.error('Error converting ProductInfo.productType:', err);
}
}
module.exports.updateProductInfoByStats = async function (idapp) {
let mylog = '';
let mylog2 = '';
let mylogtot = '';
try {
const Product = this;
const T_WEB_ArticoliFatturati = require('./t_web_articolifatturati');
const T_WEB_Ordini = require('./t_web_ordini');
mylog = "Inizio Aggiornamento Statistiche... \n";
mylogtot += mylog;
console.log(mylog);
let countUpdate = 0;
countUpdate = await T_WEB_ArticoliFatturati.updateStatisticsFatt('', idapp, true);
// Itera sui risultati e aggiorna productInfo
mylog = `Aggiornati ${countUpdate} record di productInfo`;
mylogtot += mylog;
console.log(mylog);
mylog2 = "Inizio Aggiornamento Statistiche Ordini ... \n";
mylogtot += mylog2;
console.log(mylog2);
countUpdate = await T_WEB_Ordini.updateStatisticsOrders('', idapp, true);
mylog2 = `Aggiornati ${countUpdate} record di productInfo`;
mylogtot += mylog2;
console.log(mylog2);
} catch (error) {
mylog = "Errore durante l'aggiornamento di productInfo:" + error;
console.error(mylog);
}
return mylogtot;
}
// crea setImgNotFound
module.exports.setImgNotFound = async function (id) {
// set sul record id il flag image_not_found
try {
const Product = this;
await Product.updateOne(
{ _id: id },
{ $set: { 'productInfo.image_not_found': true } }
);
console.log(`Flag image_not_found set for record with id: ${id}`);
} catch (error) {
console.error(`Error setting image_not_found flag for id ${id}:`, error);
}
}
// imposta tutti i record con image_not_found: false
module.exports.resetImageNotFound = async function () {
try {
const Product = this;
await Product.updateMany(
{ 'productInfo.image_not_found': true },
{ $set: { image_not_found: false } }
);
console.log('Flag image_not_found reset to false for all records');
return true;
} catch (error) {
console.error('Error resetting image_not_found flag:', error);
}
}
// crea una funzione che mi rimuove il record "product" che utilizza productInfo, nel caso in cui date_updated_fromGM non esista
module.exports.removeProductInfoWithoutDateUpdatedFromGM = async function (idapp) {
const Product = this;
const globalTables = require('../tools/globalTables');
let mylog;
try {
const arrproduct = await Product.find({ idapp, 'productInfo.date_updated_fromGM': { $exists: false } });
if (arrproduct.length > 0 && arrproduct.length < 1000) {
mylog = `Rimuovo ${arrproduct.length} productInfo senza date_updated_fromGM !!`
console.log(mylog);
for (const product of arrproduct) {
await Product.updateOne(
{ _id: product._id },
{ $set: { deleted: true } }
);
}
}
return mylog;
} catch (error) {
mylog += 'Error removing productInfo without date_updated_fromGM:' + error;
console.error(mylog);
}
return mylog;
};

View File

@@ -202,7 +202,7 @@ module.exports.executeQueryTable = function (idapp, params) {
return tools.executeQueryTable(this, idapp, params); return tools.executeQueryTable(this, idapp, params);
}; };
module.exports.findAllIdApp = async function (idapp, code, id) { /*module.exports.findAllIdApp = async function (idapp, code, id) {
let myfind = {}; let myfind = {};
let myqueryadd = {}; let myqueryadd = {};
let query = []; let query = [];
@@ -295,299 +295,9 @@ module.exports.findAllIdApp = async function (idapp, code, id) {
console.error('E', e); console.error('E', e);
} }
}; };*/
module.exports.getProductByCode = function (idapp, code) {
return productInfo.findAllIdApp(idapp, code);
}
module.exports.replaceProductImgToImageFile = async function (abilitaserver) {
const ProductInfo = this;
if (abilitaserver) {
// const result = await ProductInfo.updateMany({ "img": { $exists: true } }, { $rename: { 'img': 'imagefile' } });
// Trova tutti i documenti con il campo 'img' che esiste
const documents = await ProductInfo.find({ "img": { $exists: true } });
// Aggiorna ciascun documento
for (let doc of documents) {
if (doc.img && doc.img.startsWith('upload/products/')) {
// Rimuovi il prefisso '/upload/products' dal campo `img`
doc.imagefile = doc.img.replace(/^\upload\/products\//, '');
doc.img = undefined; // Può anche rimuovere il campo img corrente se desiderato
await doc.save(); // Salva il documento aggiornato
}
}
console.log(`Updated ${documents.length} document(s) with new imagefile paths.`);
} else {
const documents = await ProductInfo.find({ "imagefile": { $exists: true } });
// Aggiorna ciascun documento
for (let doc of documents) {
if (doc.imagefile && doc.imagefile.startsWith('upload/products/')) {
// Rimuovi il prefisso '/upload/products' dal campo `img`
doc.imagefile = doc.imagefile.replace(/^\upload\/products\//, '');
await doc.save(); // Salva il documento aggiornato
}
}
console.log(`Updated ${documents.length} document(s) with new imagefile paths.`);
}
await ProductInfo.updateMany({}, { 'vers_img': 0 });
console.log(`Updated ${result.modifiedCount} document(s).`);
};
/**
* @typedef {Object} Article
* @property {bigint} Id
* @property {number} IdArticolo
* @property {string} Ean13
* @property {string} Titolo
* @property {string} ListaAutori
* @property {string} ListaArgomenti
* @property {number} IdStatoProdotto
* @property {number} PrezzoIvato
* @property {number} IdMarchioEditoriale
* @property {number} IdCollana
* @property {Date} DataPubblicazione
* @property {number} IdTipologia
* @property {number} IdTipoFormato
* @property {string} Misure
* @property {string} Pagine
* @property {string} Sottotitolo
* @property {string} Durata
* @property {string} Numero
* @property {string} Edizione
* @property {string} Ristampa
* @property {Date} DataInizioCampagna
* @property {Date} DataFineCampagna
* @property {number} ScontoCampagna
* @property {number} PrezzoIvatoScontatoCampagna
* @property {Date} DataOra
* @property {boolean} Enabled
* @property {number} IDTagGruppo
* @property {string} Utente
* @property {number} PercIva
* @property {number} IdTitoloOriginale
* @property {boolean} EnabledAlFresco
* @property {number} CodEdizione
* @property {string} FasciaEta
* @property {string} DescrizioneStatoProdotto
* @property {string} DescrizioneTipologia
* @property {string} DescrizioneFormato
* @property {string} DescrizioneCollana
* @property {string} DescrArgomento
* @property {string} AutoriCompleti
* @property {string} CasaEditrice
*/
/**
* Aggiorna il prodotto basandosi su un articolo
* @param {Article} article - Dati dell'articolo da aggiornare
* @param {boolean} creanew
* @returns {Promise<void>}
*/
module.exports.aggiornaProductFromGMArticle = async function (article, creanew) {
const ProductInfo = this;
try {
if (article) {
// cerca se esiste sul db locale
let findrec = this.find({ sku: article.IdArticolo }).lean();
if (findrec) {
// Articolo Trovato !
} else {
// articolo inesistente, lo vuoi creare ?
if (creanew) {
findrec = null;
}
}
if (findrec) {
}
}
} catch (e) {
console.error('Error aggiornaProductFromGMArticle:', err);
}
};
module.exports.correggiProductTypes = async function () {
const ProductInfo = this;
const bulkOps = [];
try {
// Fase di aggregazione
const cursor = ProductInfo.aggregate([
{
$project: {
_id: 1,
productType: 1,
productTypes: [{ $ifNull: ['$productType', 10] }]
}
}
]).cursor({ batchSize: 1000 }).exec();
// Itera attraverso ogni documento utilizzando il cursore
for await (const doc of cursor) {
bulkOps.push({
updateOne: {
filter: { _id: doc._id },
update: {
$set: { productTypes: doc.productTypes },
$unset: { productType: "" }
}
}
});
// Scrivi i batch di operazioni ogni 1000 documenti
if (bulkOps.length === 1000) {
await ProductInfo.bulkWrite(bulkOps);
bulkOps.length = 0;
}
}
// Scrivi eventuali operazioni rimanenti
if (bulkOps.length > 0) {
await ProductInfo.bulkWrite(bulkOps);
}
console.log('ProductInfo.productType converted to productTypes array and saved');
} catch (err) {
console.error('Error converting ProductInfo.productType:', err);
}
}
module.exports.updateProductInfoByStats = async function (idapp) {
let mylog = '';
let mylog2 = '';
let mylogtot = '';
try {
const ProductInfo = this;
const T_WEB_ArticoliFatturati = require('./t_web_articolifatturati');
const T_WEB_Ordini = require('./t_web_ordini');
mylog = "Inizio Aggiornamento Statistiche... \n";
mylogtot += mylog;
console.log(mylog);
let countUpdate = 0;
countUpdate = await T_WEB_ArticoliFatturati.updateStatisticsFatt('', idapp, true);
// Itera sui risultati e aggiorna productInfo
mylog = `Aggiornati ${countUpdate} record di productInfo`;
mylogtot += mylog;
console.log(mylog);
mylog2 = "Inizio Aggiornamento Statistiche Ordini ... \n";
mylogtot += mylog2;
console.log(mylog2);
countUpdate = await T_WEB_Ordini.updateStatisticsOrders('', idapp, true);
mylog2 = `Aggiornati ${countUpdate} record di productInfo`;
mylogtot += mylog2;
console.log(mylog2);
} catch (error) {
mylog = "Errore durante l'aggiornamento di productInfo:" + error;
console.error(mylog);
}
return mylogtot;
}
// crea setImgNotFound
module.exports.setImgNotFound = async function (id) {
// set sul record id il flag image_not_found
try {
const ProductInfo = this;
await ProductInfo.updateOne(
{ _id: id },
{ $set: { image_not_found: true } }
);
console.log(`Flag image_not_found set for record with id: ${id}`);
} catch (error) {
console.error(`Error setting image_not_found flag for id ${id}:`, error);
}
}
// imposta tutti i record con image_not_found: false
module.exports.resetImageNotFound = async function () {
try {
const ProductInfo = this;
await ProductInfo.updateMany(
{ image_not_found: true },
{ $set: { image_not_found: false } }
);
console.log('Flag image_not_found reset to false for all records');
return true;
} catch (error) {
console.error('Error resetting image_not_found flag:', error);
}
}
// crea una funzione che mi rimuove il record "product" che utilizza productInfo, nel caso in cui date_updated_fromGM non esista
module.exports.removeProductInfoWithoutDateUpdatedFromGM = async function (idapp) {
const ProductInfo = this;
const globalTables = require('../tools/globalTables');
const Product = globalTables.getTableByTableName('Product');
let mylog;
try {
const arrproductInfo = await ProductInfo.find({ idapp, date_updated_fromGM: { $exists: false } });
if (arrproductInfo.length > 0 && arrproductInfo.length < 1000) {
mylog = `Rimuovo ${arrproductInfo.length} productInfo senza date_updated_fromGM !!`
console.log(mylog);
for (const productinfo of arrproductInfo) {
// cerca nella tabella Product se esiste idProductInfo = _id e cancella tutti i record che hanno questa corrispondenza
if (Product) {
await Product.updateMany(
{ idProductInfo: productinfo._id },
{ $set: { deleted: true } }
);
}
// Ora rimuovi anche questo productInfo
await ProductInfo.updateOne(
{ _id: productinfo._id },
{ $set: { deleted: true } }
);
}
}
return mylog;
} catch (error) {
mylog += 'Error removing productInfo without date_updated_fromGM:' + error;
console.error(mylog);
}
return mylog;
};
module.exports.createIndexes() module.exports.createIndexes()
.then(() => { }) .then(() => { })

View File

@@ -55,9 +55,9 @@ module.exports.getEditoriWithTitleCount = async function (idapp, updatedata) {
{ $match: { idapp } }, { $match: { idapp } },
{ {
$lookup: { $lookup: {
from: 'productinfos', // Nome della tua collezione productInfo from: 'products', // Nome della tua collezione productInfo
localField: '_id', localField: '_id',
foreignField: 'idPublisher', foreignField: 'productInfo.idPublisher',
as: 'products' as: 'products'
} }
}, },

View File

@@ -1,6 +1,5 @@
const mongoose = require('mongoose'); const mongoose = require('mongoose');
const ProductInfo = require('../models/productInfo');
// Definizione dello schema // Definizione dello schema
const articoliFatturatiSchema = new mongoose.Schema({ const articoliFatturatiSchema = new mongoose.Schema({
@@ -166,18 +165,18 @@ module.exports.updateStatisticsFatt = async function (CodArticolo, idapp, update
if (update) { if (update) {
for (const stat of statistics) { for (const stat of statistics) {
const result = await ProductInfo.updateOne( const result = await Product.updateOne(
{ {
sku: stat.sku, idapp,
idapp 'productInfo.sku': stat.sku,
}, // Cerca il documento con lo stesso sku }, // Cerca il documento con lo stesso sku
{ {
$set: { $set: {
fatLast3M: stat.fatLast3M, 'productInfo.fatLast3M': stat.fatLast3M,
fatLast6M: stat.fatLast6M, 'productInfo.fatLast6M': stat.fatLast6M,
fatLast1Y: stat.fatLast1Y, 'productInfo.fatLast1Y': stat.fatLast1Y,
fatLast2Y: stat.fatLast2Y, 'productInfo.fatLast2Y': stat.fatLast2Y,
totFat: stat.totFat, 'productInfo.totFat': stat.totFat,
} }
}, },
{ upsert: false } // Non crea il documento se non esiste { upsert: false } // Non crea il documento se non esiste

View File

@@ -18,8 +18,6 @@ PrimaCopiaDaSpedire - int ()
const mongoose = require('mongoose'); const mongoose = require('mongoose');
const ProductInfo = require('../models/productInfo');
// Definizione dello schema // Definizione dello schema
const ordiniSchema = new mongoose.Schema({ const ordiniSchema = new mongoose.Schema({
Codice: { Codice: {
@@ -168,18 +166,18 @@ module.exports.updateStatisticsOrders = async function (CodArticoloGM, idapp, up
if (update) { if (update) {
for (const stat of statistics) { for (const stat of statistics) {
const result = await ProductInfo.updateOne( const result = await Product.updateOne(
{ {
sku: stat.sku, 'productInfo.sku': stat.sku,
idapp, idapp,
}, // Cerca il documento con lo stesso sku }, // Cerca il documento con lo stesso sku
{ {
$set: { $set: {
totVen: stat.totVen, 'productInfo.totVen': stat.totVen,
vLast3M: stat.vLast3M, 'productInfo.vLast3M': stat.vLast3M,
vLast6M: stat.vLast6M, 'productInfo.vLast6M': stat.vLast6M,
vLast1Y: stat.vLast1Y, 'productInfo.vLast1Y': stat.vLast1Y,
vLast2Y: stat.vLast2Y, 'productInfo.vLast2Y': stat.vLast2Y,
} }
}, },
{ upsert: false } // Non crea il documento se non esiste { upsert: false } // Non crea il documento se non esiste

View File

@@ -108,10 +108,10 @@ class CronMod {
await CatProd.deleteMany({ idapp }); await CatProd.deleteMany({ idapp });
await SubCatProd.deleteMany({ idapp }); await SubCatProd.deleteMany({ idapp });
} else if (mydata.dbop === 'removeProductInfoWithoutDateUpdatedFromGM') { } else if (mydata.dbop === 'removeProductInfoWithoutDateUpdatedFromGM') {
mystr = await ProductInfo.removeProductInfoWithoutDateUpdatedFromGM(idapp); mystr = await Product.removeProductInfoWithoutDateUpdatedFromGM(idapp);
ris = { mystr }; ris = { mystr };
} else if (mydata.dbop === 'resetImageNotFound') { } else if (mydata.dbop === 'resetImageNotFound') {
mystr = await ProductInfo.resetImageNotFound(); mystr = await Product.resetImageNotFound();
ris = { mystr }; ris = { mystr };
} else if (mydata.dbop === 'StatMacro') { } else if (mydata.dbop === 'StatMacro') {
const macro = new Macro(idapp, {}); const macro = new Macro(idapp, {});
@@ -220,7 +220,7 @@ class CronMod {
mystr = await CatProd.updateCatDeleteEmpty(req.body.idapp); mystr = await CatProd.updateCatDeleteEmpty(req.body.idapp);
ris = { mystr }; ris = { mystr };
} else if (mydata.dbop === 'UpdateStatFatturato') { } else if (mydata.dbop === 'UpdateStatFatturato') {
mystr = await ProductInfo.updateProductInfoByStats(req.body.idapp); mystr = await Product.updateProductInfoByStats(req.body.idapp);
ris = { mystr }; ris = { mystr };
} else if (mydata.dbop === 'MigrateMSSQLToMongoDb') { } else if (mydata.dbop === 'MigrateMSSQLToMongoDb') {
const { mssqlmigrateTables } = require('../controllers/articleController'); const { mssqlmigrateTables } = require('../controllers/articleController');
@@ -464,11 +464,11 @@ class CronMod {
await Circuit.createCircuitIfNotExist(req, idapp, recprov.prov); await Circuit.createCircuitIfNotExist(req, idapp, recprov.prov);
} }
} else if (mydata.dbop === 'correggiProductTypes') { } else if (mydata.dbop === 'correggiProductTypes') {
await ProductInfo.correggiProductTypes(); await Product.correggiProductTypes();
} else if (mydata.dbop === 'replaceProductImgToImageFile') { } else if (mydata.dbop === 'replaceProductImgToImageFile') {
await ProductInfo.replaceProductImgToImageFile(true); await Product.replaceProductImgToImageFile(true);
} else if (mydata.dbop === 'removeUploadProducts_Path') { } else if (mydata.dbop === 'removeUploadProducts_Path') {
await ProductInfo.replaceProductImgToImageFile(false); await Product.replaceProductImgToImageFile(false);
} else if (mydata.dbop === 'correggiCircuitiANull') { } else if (mydata.dbop === 'correggiCircuitiANull') {
await User.updateMany({}, { $pull: { 'profile.mycircuits': { circuitname: null } } }); await User.updateMany({}, { $pull: { 'profile.mycircuits': { circuitname: null } } });
} else if (mydata.dbop === 'ImpostaMinMaxPersonali') { } else if (mydata.dbop === 'ImpostaMinMaxPersonali') {

View File

@@ -1,6 +1,5 @@
const Importamacro = require('../models/importamacro'); // Assicurati di avere i modelli corretti const Importamacro = require('../models/importamacro'); // Assicurati di avere i modelli corretti
const ImportaIsbn = require('../models/importaisbn'); const ImportaIsbn = require('../models/importaisbn');
const ProductInfo = require('../models/productInfo');
const Product = require('../models/product'); const Product = require('../models/product');
const CatProd = require('../models/catprod'); const CatProd = require('../models/catprod');
const SubCatProd = require('../models/subcatprod'); const SubCatProd = require('../models/subcatprod');
@@ -444,13 +443,13 @@ class Macro {
let count = 0; let count = 0;
if (Array.isArray(recproducts)) { if (Array.isArray(recproducts)) {
if (recproducts.length > 10 && lavoromassivo && options.rimuovieventualiCancellati) { if (recproducts.length > 10 && lavoromassivo && options.rimuovieventualiCancellati) {
// rimuovi dalla tabella productInfo tutti i campi date_updated_fromGM // disattiva dalla tabella productInfo tutti i campi date_updated_fromGM
const result = await ProductInfo.updateMany( const result = await Product.updateMany(
{ idapp: options.idapp }, { idapp: options.idapp },
{ $unset: { date_updated_fromGM: null } } { $unset: { 'productInfo.date_updated_fromGM': null } }
); );
let quanti_rimossi = result.modifiedCount; let quanti_rimossi = result.modifiedCount;
console.log(`Sbianca date_updated_fromGM da ProductInfo: (${quanti_rimossi} su ${result.matchedCount})`); console.log(`Sbianca date_updated_fromGM da Product: (${quanti_rimossi} su ${result.matchedCount})`);
rimuoviTabellePerIniziare = true; rimuoviTabellePerIniziare = true;
} }
@@ -634,7 +633,7 @@ class Macro {
if (!product.title || !product.sku) importa = false; if (!product.title || !product.sku) importa = false;
if (importa) { if (importa) {
const productInfo = this.preparaProductInfo(product); product.productInfo = this.preparaProductInfo(product);
if (this.localoptions?.importadaFDV) { if (this.localoptions?.importadaFDV) {
const recrankingisbn = await ImportaIsbn.findOne({ sku: product.sku }).lean(); const recrankingisbn = await ImportaIsbn.findOne({ sku: product.sku }).lean();
@@ -647,12 +646,12 @@ class Macro {
product.active = true; product.active = true;
} }
await this.gestisciCategorie(productInfo, product); await this.gestisciCategorie(product);
await this.gestisciAutori(productInfo, product); await this.gestisciAutori(product);
await this.gestisciEditore(productInfo, product); await this.gestisciEditore(product);
await this.gestisciCollana(productInfo, product); await this.gestisciCollana(product);
const risrecInfo = await ProductInfo.findOneAndUpdate( const risrecInfo = await Product.findOneAndUpdate(
{ code: productInfo.code }, { code: productInfo.code },
{ $set: productInfo }, { $set: productInfo },
{ new: true, upsert: true, returnOriginal: false } { new: true, upsert: true, returnOriginal: false }
@@ -705,7 +704,6 @@ class Macro {
preparaProductInfo(product) { preparaProductInfo(product) {
try { try {
return { return {
idapp: product.idapp,
code: product.isbn, code: product.isbn,
id_wp: product._id || undefined, id_wp: product._id || undefined,
sku: product.sku, sku: product.sku,
@@ -869,10 +867,10 @@ class Macro {
/** /**
* Gestisce le categorie e sottocategorie del prodotto. * Gestisce le categorie e sottocategorie del prodotto.
*/ */
async gestisciCategorie(productInfo, product) { async gestisciCategorie(product) {
try { try {
if (product.DescrArgomento) { if (product.DescrArgomento) {
productInfo.idCatProds = []; product.productInfo.idCatProds = [];
const reccateg = await CatProd.findOne({ idapp: this.idapp, name: product.DescrArgomento }); const reccateg = await CatProd.findOne({ idapp: this.idapp, name: product.DescrArgomento });
let nuovaCategoria = null; let nuovaCategoria = null;
if (!reccateg) { if (!reccateg) {
@@ -892,12 +890,12 @@ class Macro {
const myriscat = reccateg?._id || (nuovaCategoria ? nuovaCategoria._id : null); const myriscat = reccateg?._id || (nuovaCategoria ? nuovaCategoria._id : null);
if (myriscat) productInfo.idCatProds.push(myriscat); if (myriscat) product.productInfo.idCatProds.push(myriscat);
} else { } else {
if (product.categories) { if (product.categories) {
// const arrcat = product.categories.trim().split(','); // const arrcat = product.categories.trim().split(',');
const arrcat = product.categories.trim().split(','); const arrcat = product.categories.trim().split(',');
productInfo.idCatProds = []; product.productInfo.idCatProds = [];
for (const mycat of arrcat) { for (const mycat of arrcat) {
const mycatstr = mycat.trim(); const mycatstr = mycat.trim();
@@ -910,7 +908,7 @@ class Macro {
} }
const myriscat = reccateg?._id || (nuovaCategoria ? nuovaCategoria._id : null); const myriscat = reccateg?._id || (nuovaCategoria ? nuovaCategoria._id : null);
if (myriscat) productInfo.idCatProds.push(myriscat); if (myriscat) product.productInfo.idCatProds.push(myriscat);
} }
} }
} }
@@ -922,13 +920,13 @@ class Macro {
/** /**
* Gestisce gli autori del prodotto. * Gestisce gli autori del prodotto.
*/ */
async gestisciAutori(productInfo, product) { async gestisciAutori(product) {
if (product.Autore) { if (product.Autore) {
let arrAuthor = []; let arrAuthor = [];
if (product.id_wp) arrAuthor = this.estraiAutori_FDV(product.Autore); if (product.id_wp) arrAuthor = this.estraiAutori_FDV(product.Autore);
else arrAuthor = this.estraiAutori(product.Autore); else arrAuthor = this.estraiAutori(product.Autore);
productInfo.idAuthors = []; product.productInfo.idAuthors = [];
for (const author of arrAuthor) { for (const author of arrAuthor) {
const recauthor = await Author.findOne({ const recauthor = await Author.findOne({
@@ -944,7 +942,7 @@ class Macro {
} }
const myrisautore = recauthor?._id || (nuovoAutore ? nuovoAutore._id : ''); const myrisautore = recauthor?._id || (nuovoAutore ? nuovoAutore._id : '');
if (myrisautore) productInfo.idAuthors.push(myrisautore); if (myrisautore) product.productInfo.idAuthors.push(myrisautore);
} }
} }
} }
@@ -995,9 +993,9 @@ class Macro {
/** /**
* Gestisce l'editore del prodotto. * Gestisce l'editore del prodotto.
*/ */
async gestisciEditore(productInfo, product) { async gestisciEditore(product) {
if (productInfo.publisher) { if (product.productInfo.publisher) {
const publisher = productInfo.publisher.trim(); const publisher = product.productInfo.publisher.trim();
const recpublisher = await Publisher.findOne({ idapp: this.idapp, name: publisher }).lean(); const recpublisher = await Publisher.findOne({ idapp: this.idapp, name: publisher }).lean();
let nuovoEditore = null; let nuovoEditore = null;
@@ -1009,14 +1007,14 @@ class Macro {
return; return;
} }
} }
if (recpublisher?._id || nuovoEditore?._id) productInfo.idPublisher = recpublisher?._id || nuovoEditore._id; if (recpublisher?._id || nuovoEditore?._id) product.productInfo.idPublisher = recpublisher?._id || nuovoEditore._id;
} }
} }
/** /**
* Gestisce la collana del prodotto. * Gestisce la collana del prodotto.
*/ */
async gestisciCollana(productInfo, product) { async gestisciCollana(product) {
if (product.collezione && product.numCollana) { if (product.collezione && product.numCollana) {
const collana = product.collezione.trim(); const collana = product.collezione.trim();
const reccollana = await Collana.findOne({ idapp: this.idapp, title: collana }).lean(); const reccollana = await Collana.findOne({ idapp: this.idapp, title: collana }).lean();
@@ -1030,17 +1028,17 @@ class Macro {
return; return;
} }
} }
if (reccollana?._id || nuovaCollana?._id) productInfo.idCollana = reccollana?._id || nuovaCollana._id; if (reccollana?._id || nuovaCollana?._id) product.productInfo.idCollana = reccollana?._id || nuovaCollana._id;
} }
} }
/** /**
* Aggiorna l'immagine se necessario. * Aggiorna l'immagine se necessario.
*/ */
async aggiornaImmagineSeNecessario(productInfo) { async aggiornaImmagineSeNecessario(product) {
const { prodInfo, aggiornatoimg } = await tools.downloadImgIfMissing(productInfo); const { prodInfo, aggiornatoimg } = await tools.downloadImgIfMissing(product);
if (aggiornatoimg) { if (aggiornatoimg) {
await ProductInfo.findOneAndUpdate({ code: productInfo.code }, { $set: prodInfo }); await Product.findOneAndUpdate({ _id: product._id }, { $set: { productInfo: prodInfo } });
} }
return aggiornatoimg; return aggiornatoimg;

View File

@@ -2,7 +2,6 @@ const axios = require('axios');
const cheerio = require('cheerio'); const cheerio = require('cheerio');
const Product = require('../models/product'); const Product = require('../models/product');
const ProductInfo = require('../models/productInfo');
const tools = require('../tools/general'); const tools = require('../tools/general');
const shared_consts = require('../tools/shared_nodejs'); const shared_consts = require('../tools/shared_nodejs');
@@ -96,9 +95,9 @@ class AmazonBookScraper {
} }
} }
getTitleByProductInfo(productInfo) { getTitleByProduct(product) {
try { try {
return productInfo?.name.trim(); return product?.productInfo.name.trim();
} catch (e) { } catch (e) {
return ''; return '';
} }
@@ -107,9 +106,9 @@ class AmazonBookScraper {
async extractData(myproduct, html, url, isbn10) { async extractData(myproduct, html, url, isbn10) {
const $ = cheerio.load(html); const $ = cheerio.load(html);
const productInfo = await ProductInfo.findOne({ _id: myproduct.idProductInfo }).lean(); const product = await Product.findOne({ _id: myproduct._id }).lean();
const title_ondb = this.getTitleByProductInfo(productInfo); const title_ondb = this.getTitleByProduct(product);
// Titolo // Titolo
let title = $('#productTitle').text().trim() || null; let title = $('#productTitle').text().trim() || null;
@@ -247,6 +246,7 @@ class AmazonBookScraper {
async scrapeISBN(myproduct, isbn, options) { async scrapeISBN(myproduct, isbn, options) {
try { try {
const product = await Product.findOne({ _id: myproduct._id }).lean();
const datastored = await this.findRecordMyScrapingBookByIsbn(isbn); const datastored = await this.findRecordMyScrapingBookByIsbn(isbn);
let data = null; let data = null;
@@ -289,7 +289,6 @@ class AmazonBookScraper {
if (index < 0) index = 0; if (index < 0) index = 0;
} }
const productInfo = {};
let aggiornaDataPubb = false; let aggiornaDataPubb = false;
let aggiornaPages = false; let aggiornaPages = false;
@@ -325,17 +324,17 @@ class AmazonBookScraper {
} }
// Determina se aggiornare data pubblicazione // Determina se aggiornare data pubblicazione
const currentDatePub = myproduct.idProductInfo.date_pub; const currentDatePub = myproduct.productInfo.date_pub;
aggiornaDataPubb = aggiornaDataPubb =
(!options.aggiornasoloSeVuoti || !tools.isDateValid(currentDatePub)) && (!options.aggiornasoloSeVuoti || !tools.isDateValid(currentDatePub)) &&
tools.isDateValid(data.data_pubblicazione); tools.isDateValid(data.data_pubblicazione);
if (aggiornaDataPubb && data.data_pubblicazione) { if (aggiornaDataPubb && data.data_pubblicazione) {
productInfo.date_pub = new Date(data.data_pubblicazione); product.productInfo.date_pub = new Date(data.data_pubblicazione);
} }
aggiornaSottotitolo = (!options.aggiornasoloSeVuoti || !myproduct.idProductInfo.sottotitolo) && data.sottotitolo; aggiornaSottotitolo = (!options.aggiornasoloSeVuoti || !myproduct.productInfo.sottotitolo) && data.sottotitolo;
if (aggiornaSottotitolo && data.sottotitolo) { if (aggiornaSottotitolo && data.sottotitolo) {
productInfo.sottotitolo = data.sottotitolo; product.productInfo.sottotitolo = data.sottotitolo;
} }
aggiornaSottotitolo = false; // !! PER ORA LO DISATTIVO PERCHE' non esiste sempre il sottotitolo in un libro. aggiornaSottotitolo = false; // !! PER ORA LO DISATTIVO PERCHE' non esiste sempre il sottotitolo in un libro.
@@ -373,9 +372,9 @@ class AmazonBookScraper {
if (aggiornaProductInfo) { if (aggiornaProductInfo) {
// Aggiorna productInfo se contiene dati // Aggiorna productInfo se contiene dati
if (!tools.isObjectEmpty(productInfo)) { if (!tools.isObjectEmpty(productInfo)) {
risupdate = await ProductInfo.findOneAndUpdate( risupdate = await Product.findOneAndUpdate(
{ _id: myproduct.idProductInfo }, { _id: myproduct._id },
{ $set: productInfo }, { $set: { productInfo: product.productInfo } },
{ new: true, upsert: true, includeResultMetadata: true } { new: true, upsert: true, includeResultMetadata: true }
).lean(); ).lean();
} }
@@ -384,7 +383,7 @@ class AmazonBookScraper {
const concatenatedProduct = { const concatenatedProduct = {
...recModificato, ...recModificato,
...productInfo, ...product.productInfo,
}; };
if (updated) { if (updated) {

View File

@@ -17,7 +17,6 @@ const Inventariogm = require('../models/inventariogm');
const Importamacro = require('../models/importamacro'); const Importamacro = require('../models/importamacro');
const ImportaDescr = require('../models/importadescr'); const ImportaDescr = require('../models/importadescr');
const ImportaIsbn = require('../models/importaisbn'); const ImportaIsbn = require('../models/importaisbn');
const ProductInfo = require('../models/productInfo');
const CatProd = require('../models/catprod'); const CatProd = require('../models/catprod');
const Collana = require('../models/collana'); const Collana = require('../models/collana');
const Author = require('../models/author'); const Author = require('../models/author');
@@ -72,7 +71,7 @@ function launchGenPdfIfNeeded() {
} }
} }
async function updateProductInfo(recproductInfoAttuale, product, idapp, mycatstr) { /*async function updateProductInfo(recproductInfoAttuale, product, idapp, mycatstr) {
if (!recproductInfoAttuale || !mycatstr) return recproductInfoAttuale; if (!recproductInfoAttuale || !mycatstr) return recproductInfoAttuale;
let idArgomentoNum = null; let idArgomentoNum = null;
@@ -93,7 +92,7 @@ async function updateProductInfo(recproductInfoAttuale, product, idapp, mycatstr
} }
return productInfo; return productInfo;
} }*/
async function findOrCreateCatProd(idapp, idArgomento, DescrArgomento) { async function findOrCreateCatProd(idapp, idArgomento, DescrArgomento) {
let reccatprod = null; let reccatprod = null;
@@ -1240,28 +1239,28 @@ router.post('/import', authenticate, async (req, res) => {
code: product.code, code: product.code,
}; };
const myproductInfo = await ProductInfo.findOne({ code: productInfo.code }); const myproduct = await Product.findOne({ 'productInfo.code': productInfo.code });
// IMPOSTA I VALORI SOLO SE NON ESISTONO ! ALTRIMENTI LASCIA QUELLI GIA' IMPORTATI (O MODIFICATI) // IMPOSTA I VALORI SOLO SE NON ESISTONO ! ALTRIMENTI LASCIA QUELLI GIA' IMPORTATI (O MODIFICATI)
if (getvalueByJsonText(product.url)) { if (getvalueByJsonText(product.url)) {
if ((myproductInfo && !myproductInfo.link_macro) || !myproductInfo) if ((myproduct && !myproduct.productInfo.link_macro) || !myproduct.productInfo)
productInfo.link_macro = getvalueByJsonText(product.url); productInfo.link_macro = getvalueByJsonText(product.url);
} }
if (getvalueByJsonText(product.descrizione)) { if (getvalueByJsonText(product.descrizione)) {
if ((myproductInfo && !myproductInfo.descrizione_breve_macro) || !myproductInfo) if ((myproduct && !myproduct.productInfo.descrizione_breve_macro) || !myproduct.productInfo)
productInfo.descrizione_breve_macro = getvalueByJsonText(product.descrizione); productInfo.descrizione_breve_macro = getvalueByJsonText(product.descrizione);
} }
if (getvalueByJsonText(product.descrizione_completa)) { if (getvalueByJsonText(product.descrizione_completa)) {
if ((myproductInfo && !myproductInfo.descrizione_completa_macro) || !myproductInfo) if ((myproduct && !myproduct.productInfo.descrizione_completa_macro) || !myproduct.productInfo)
productInfo.descrizione_completa_macro = getvalueByJsonText(product.descrizione_completa); productInfo.descrizione_completa_macro = getvalueByJsonText(product.descrizione_completa);
} }
if (getvalueByJsonText(product.sottotitolo)) { if (getvalueByJsonText(product.sottotitolo)) {
if ((myproductInfo && !myproductInfo.sottotitolo) || !myproductInfo) if ((myproduct && !myproduct.productInfo.sottotitolo) || !myproduct.productInfo)
productInfo.sottotitolo = getvalueByJsonText(product.sottotitolo); productInfo.sottotitolo = getvalueByJsonText(product.sottotitolo);
} }
if (getvalueByJsonText(product.titolo)) { if (getvalueByJsonText(product.titolo)) {
if ((myproductInfo && !myproductInfo.name) || !myproductInfo) if ((myproduct && !myproduct.productInfo.name) || !myproduct.productInfo)
productInfo.name = getvalueByJsonText(product.titolo); productInfo.name = getvalueByJsonText(product.titolo);
} }
@@ -1520,27 +1519,27 @@ router.post('/import', authenticate, async (req, res) => {
let imported = 0; let imported = 0;
let errors = 0; let errors = 0;
for (const product of dataObjects) { for (const productImported of dataObjects) {
let isnuovo = false; let isnuovo = false;
let setta = false; let setta = false;
let productInfo = { let productInfo = {
idapp: product.idapp, idapp: productImported.idapp,
code: product.code, code: productImported.code,
name: product.name, name: productImported.name,
link: product.link, link: productImported.link,
idCatProds: [], idCatProds: [],
idSubCatProds: [], idSubCatProds: [],
// img: 'upload/products/' + product.code + '.jpg', // img: 'upload/products/' + product.code + '.jpg',
imagefile: product.code + '.jpg', imagefile: productImported.code + '.jpg',
weight: product.weight, weight: productImported.weight,
unit: tools.getIdUnitsByText(product.unit), unit: tools.getIdUnitsByText(productImported.unit),
productTypes: shared_consts.PRODUCTTYPE.PRODUCT, productTypes: shared_consts.PRODUCTTYPE.PRODUCT,
}; };
let reccateg = null; let reccateg = null;
if (product.cat_name) { if (productImported.cat_name) {
arrcat = product.cat_name.trim().split(','); arrcat = productImported.cat_name.trim().split(',');
for (const mycat of arrcat) { for (const mycat of arrcat) {
let mycatstr = mycat.trim(); let mycatstr = mycat.trim();
@@ -1559,8 +1558,8 @@ router.post('/import', authenticate, async (req, res) => {
} }
} }
if (product.subcat_name) { if (productImported.subcat_name) {
arrsubcat = product.subcat_name.trim().split(','); arrsubcat = productImported.subcat_name.trim().split(',');
productInfo.idSubCatProds = []; productInfo.idSubCatProds = [];
for (const mysubcat of arrsubcat) { for (const mysubcat of arrsubcat) {
let mysubcatstr = mysubcat.trim(); let mysubcatstr = mysubcat.trim();
@@ -1581,24 +1580,26 @@ router.post('/import', authenticate, async (req, res) => {
} }
} }
if (!product.hasOwnProperty('active')) { if (!productImported.hasOwnProperty('active')) {
product.active = true; productImported.active = true;
} }
if (product.code) delete product.code; /*if (product.code) delete product.code;
if (product.name) delete product.name; if (product.name) delete product.name;
if (product.link) delete product.link; if (product.link) delete product.link;*/
let esisteindb = await ProductInfo.findOne({ code: productInfo.code }).lean(); let esisteindb = await Product.findOne({ 'productInfo.code': productInfo.code }).lean();
// Update ProductInfo // Update ProductInfo
let risrecInfo = await ProductInfo.findOneAndUpdate( let risrecInfo = await Product.findOneAndUpdate(
{ code: productInfo.code }, { 'productInfo.code': productInfo.code },
{ $set: productInfo }, { $set: { productInfo: productInfo } },
{ new: true, upsert: true } { new: true, upsert: true }
); );
// .... ANDARE AVANTI DA QUI... .productInfo.... SISTEMARE!
if (risrecInfo) { if (risrecInfo) {
product.idProductInfo = risrecInfo._id; productImported.productInfo = risrecInfo._id;
recnewInfo = await ProductInfo.findOne({ code: productInfo.code }).lean(); recnewInfo = await ProductInfo.findOne({ code: productInfo.code }).lean();
@@ -1613,20 +1614,20 @@ router.post('/import', authenticate, async (req, res) => {
// Cerca il GAS // Cerca il GAS
let recGas = null; let recGas = null;
if (product.gas_name) { if (productImported.gas_name) {
// Cerca il GAS // Cerca il GAS
recGas = await Gasordine.findOne({ idapp, name: product.gas_name }).lean(); recGas = await Gasordine.findOne({ idapp, name: productImported.gas_name }).lean();
} }
if (!recGas && !!product.gas_name) { if (!recGas && !!productImported.gas_name) {
recGas = new Gasordine({ idapp, name: product.gas_name, active: true }); recGas = new Gasordine({ idapp, name: productImported.gas_name, active: true });
// Non esiste questo GAS, quindi lo creo ! // Non esiste questo GAS, quindi lo creo !
ris = await recGas.save(); ris = await recGas.save();
recGas = await Gasordine.findOne({ idapp, name: product.gas_name }).lean(); recGas = await Gasordine.findOne({ idapp, name: productImported.gas_name }).lean();
} }
let recProductExist = null; let recProductExist = null;
let queryprod = { idProductInfo: product.idProductInfo }; let queryprod = { idProductInfo: productImported.idProductInfo };
if (recGas) { if (recGas) {
queryprod = { ...queryprod, idGasordine: recGas._id }; queryprod = { ...queryprod, idGasordine: recGas._id };
@@ -1639,22 +1640,22 @@ router.post('/import', authenticate, async (req, res) => {
} }
if (!options.aggiornaStockQty && esisteindb && !isnuovo) { if (!options.aggiornaStockQty && esisteindb && !isnuovo) {
delete product.stockQty; delete productImported.stockQty;
delete product.maxbookableGASQty; delete productImported.maxbookableGASQty;
} }
// AGGIORNA PRODUCT // AGGIORNA PRODUCT
let risrec = await Product.findOneAndUpdate(queryprod, { $set: product }, { new: true, upsert: true }); let risrec = await Product.findOneAndUpdate(queryprod, { $set: productImported }, { new: true, upsert: true });
let recnew = await Product.findOne(queryprod).lean(); let recnew = await Product.findOne(queryprod).lean();
if (risrec) { if (risrec) {
if (risrec._id) { if (risrec._id) {
// Record existed, so it was updated // Record existed, so it was updated
let arrfieldchange = tools.differentObjects(product, recnew); let arrfieldchange = tools.differentObjects(productImported, recnew);
if (arrfieldchange.length > 0) { if (arrfieldchange.length > 0) {
updated++; updated++;
console.log('Changed:', product.idProductInfo + ': ' + arrfieldchange); console.log('Changed:', productImported.idProductInfo + ': ' + arrfieldchange);
} }
} else { } else {
// Record didn't exist, so it was created // Record didn't exist, so it was created
@@ -1662,13 +1663,13 @@ router.post('/import', authenticate, async (req, res) => {
} }
} else { } else {
// risrec is null or undefined, indicating an error // risrec is null or undefined, indicating an error
console.error('Error: ', product.productInfo.name); console.error('Error: ', productImported.productInfo.name);
errors++; errors++;
} }
await Product.singlerecconvert_AfterImport_AndSave(idapp, recnew, isnuovo); await Product.singlerecconvert_AfterImport_AndSave(idapp, recnew, isnuovo);
} else { } else {
console.error('Error ProductInfo: ', product.code); console.error('Error ProductInfo: ', productImported.code);
errors++; errors++;
} }
} }
@@ -1871,6 +1872,7 @@ router.post('/import', authenticate, async (req, res) => {
return res.status(400).send(); return res.status(400).send();
}); });
/*
async function importaCatalogo(data) { async function importaCatalogo(data) {
let updated = 0; let updated = 0;
let imported = 0; let imported = 0;
@@ -2059,11 +2061,6 @@ async function importaCatalogo(data) {
productInfo.productTypes.push(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( productInfo.name = productInfo.name.replace(
/ - Usato$| - Nuovo$| - Epub$| - Ebook$| - Mobi$| - DVD$| - Streaming$| - Download$/, / - Usato$| - Nuovo$| - Epub$| - Ebook$| - Mobi$| - DVD$| - Streaming$| - Download$/,
@@ -2113,7 +2110,7 @@ async function importaCatalogo(data) {
} }
if (reccateg) { if (reccateg) {
productInfo.idCatProds.push(reccateg._id); product.productInfo.idCatProds.push(reccateg._id);
} }
} }
} }
@@ -2149,7 +2146,7 @@ async function importaCatalogo(data) {
} catch (e) {} } catch (e) {}
} }
} }
productInfo.idAuthors = []; product.productInfo.idAuthors = [];
for (const myauthor of arrAuthor) { for (const myauthor of arrAuthor) {
// Cerca l'Autore // Cerca l'Autore
@@ -2162,7 +2159,7 @@ async function importaCatalogo(data) {
} }
if (recauthor) { if (recauthor) {
productInfo.idAuthors.push(recauthor._id); product.productInfo.idAuthors.push(recauthor._id);
} }
} }
} catch (e) { } catch (e) {
@@ -2173,7 +2170,7 @@ async function importaCatalogo(data) {
if (product.subcat_name) { if (product.subcat_name) {
arrsubcat = product.subcat_name.trim().split(','); arrsubcat = product.subcat_name.trim().split(',');
productInfo.idSubCatProds = []; product.productInfo.idSubCatProds = [];
for (const mysubcat of arrsubcat) { for (const mysubcat of arrsubcat) {
let mysubcatstr = mysubcat.trim(); let mysubcatstr = mysubcat.trim();
@@ -2188,13 +2185,13 @@ async function importaCatalogo(data) {
} }
if (recsubcateg) { if (recsubcateg) {
productInfo.idSubCatProds.push(recsubcateg._id); product.productInfo.idSubCatProds.push(recsubcateg._id);
} }
} }
} }
if (productInfo.publisher) { if (product.productInfo.publisher) {
try { try {
publisher = productInfo.publisher.trim(); publisher = product.productInfo.publisher.trim();
// Cerca la Sotto Categoria // Cerca la Sotto Categoria
let recpublisher = await Publisher.findOne({ idapp, name: publisher }).lean(); let recpublisher = await Publisher.findOne({ idapp, name: publisher }).lean();
if (!recpublisher) { if (!recpublisher) {
@@ -2205,7 +2202,7 @@ async function importaCatalogo(data) {
} }
if (recpublisher) { if (recpublisher) {
productInfo.idPublisher = recpublisher._id; product.productInfo.idPublisher = recpublisher._id;
} }
} catch (e) { } catch (e) {
console.error(e); console.error(e);
@@ -2213,19 +2210,19 @@ async function importaCatalogo(data) {
} }
// Aggiorna la collana solo se non è stata già impostata nel record attuale // Aggiorna la collana solo se non è stata già impostata nel record attuale
//if (recproductInfoAttuale && !recproductInfoAttuale.idCollana && product.DescrizioneCollana) { //if (recproductInfoAttuale && !recproductInfoAttuale.idCollana && product.DescrizioneCollana) {
if (productInfo.collezione && productInfo.numCollana) { if (product.productInfo.collezione && product.productInfo.numCollana) {
reccollana = await Collana.findOne({ idapp, title: collezione }).lean(); reccollana = await Collana.findOne({ idapp, title: collezione }).lean();
if (!reccollana) { if (!reccollana) {
try { try {
// Non esiste questa collana, quindi la creo ! // Non esiste questa collana, quindi la creo !
reccollana = new Collana({ idapp, idCollana: productInfo.numCollana, title: product.DescrizioneCollana }); reccollana = new Collana({ idapp, idCollana: product.productInfo.numCollana, title: product.DescrizioneCollana });
ris = await reccoll.save(); ris = await reccoll.save();
} catch (e) { } catch (e) {
console.error('Err', e); console.error('Err', e);
} }
} }
if (reccollana) productInfo.idCollana = reccollana._id; if (reccollana) product.productInfo.idCollana = reccollana._id;
} }
if (!product.hasOwnProperty('active')) { if (!product.hasOwnProperty('active')) {
@@ -2497,7 +2494,7 @@ async function importaCatalogo(data) {
console.log(e.message); console.log(e.message);
return res.status(400).send(e); return res.status(400).send(e);
} }
} }*/
router.post('/exec', authenticate, async (req, res) => { router.post('/exec', authenticate, async (req, res) => {
try { try {

View File

@@ -10,7 +10,6 @@ const XLSX = require('xlsx');
const upload = multer({ dest: 'uploads/' }); const upload = multer({ dest: 'uploads/' });
const Product = require('../models/product'); const Product = require('../models/product');
const ProductInfo = require('../models/productInfo');
const Author = require('../models/author'); const Author = require('../models/author');
const tools = require('../tools/general'); const tools = require('../tools/general');
@@ -370,8 +369,8 @@ router.post('/search-books', authenticate, async (req, res) => {
// Cerca il primo record che corrisponde per ISBN o titolo // Cerca il primo record che corrisponde per ISBN o titolo
if (true) { if (true) {
if (!trovatoISBN) { if (!trovatoISBN) {
let productInfoarrISBN = await ProductInfo.find({ let productInfoarrISBN = await Product.find({
code: field.toUpperCase(), 'productInfo.code': field.toUpperCase(),
$or: [{ deleted: false }, { deleted: { $exists: false } }], $or: [{ deleted: false }, { deleted: { $exists: false } }],
}).exec(); }).exec();
@@ -384,33 +383,33 @@ router.post('/search-books', authenticate, async (req, res) => {
} }
if (!trovatoISBN && !trovato) { if (!trovatoISBN && !trovato) {
// Prima cerca se è esattamente cosi // Prima cerca se è esattamente cosi
let productInfoarrTitle = await ProductInfo.find({ let productarrTitle = await Product.find({
$or: [{ deleted: false }, { deleted: { $exists: false } }], $or: [{ deleted: false }, { deleted: { $exists: false } }],
name: field, 'productInfo.name': field,
}).exec(); }).exec();
if (productInfoarrTitle.length === 1) { if (productarrTitle.length === 1) {
productInfo = productInfoarrTitle[0]; productInfo = productarrTitle[0];
trovato = true; trovato = true;
} else { } else {
if (productInfoarrTitle.length > 1) { if (productarrTitle.length > 1) {
// Prendi l'Ultimo ! // Prendi l'Ultimo !
productInfo = productInfoarrTitle[productInfoarrTitle.length - 1]; productInfo = productarrTitle[productarrTitle.length - 1];
trovato = true; trovato = true;
} }
} }
if (!trovato) { if (!trovato) {
// Altrimenti per Titolo // Altrimenti per Titolo
productInfoarrTitle = await ProductInfo.find({ productarrTitle = await Product.find({
$or: [{ deleted: false }, { deleted: { $exists: false } }], $or: [{ deleted: false }, { deleted: { $exists: false } }],
name: new RegExp(`.*${escapeRegExp(tools.removeAccents(field.toUpperCase()))}.*`, 'i'), 'productInfo.name': new RegExp(`.*${escapeRegExp(tools.removeAccents(field.toUpperCase()))}.*`, 'i'),
}).exec(); }).exec();
if (productInfoarrTitle.length === 1) { if (productarrTitle.length === 1) {
productInfo = productInfoarrTitle[0]; productInfo = productarrTitle[0];
trovato = true; trovato = true;
} else { } else {
if (productInfoarrTitle.length > 1) { if (productarrTitle.length > 1) {
// Prendi l'Ultimo ! // Prendi l'Ultimo !
productInfo = productInfoarrTitle[productInfoarrTitle.length - 1]; productInfo = productarrTitle[productarrTitle.length - 1];
trovato = true; trovato = true;
} }
} }
@@ -426,15 +425,14 @@ router.post('/search-books', authenticate, async (req, res) => {
if (product) { if (product) {
const existingResult = results.find((r) => r._id.toString() === product._id.toString()); const existingResult = results.find((r) => r._id.toString() === product._id.toString());
if (!existingResult) { if (!existingResult) {
let titolo = productInfo.name; let titolo = product.productInfo.name;
results.push({ results.push({
...product, ...product,
productInfo,
_id: product._id, _id: product._id,
title: titolo, title: titolo,
isbn: product.isbn, isbn: product.isbn,
authors: await Promise.all( authors: await Promise.all(
productInfo.idAuthors.map(async (authorId) => { product.productInfo.idAuthors.map(async (authorId) => {
const author = await Author.findById(authorId).exec(); const author = await Author.findById(authorId).exec();
return author ? `${author.name} ${author.surname}`.trim() : ''; return author ? `${author.name} ${author.surname}`.trim() : '';
}) })

View File

@@ -526,19 +526,6 @@ router.post('/:userId/gestord', authenticate, async function (req, res, next) {
preserveNullAndEmptyArrays: true, preserveNullAndEmptyArrays: true,
}, },
}, },
{
$lookup: {
from: 'productinfos',
localField: 'product.idProductInfo',
foreignField: '_id',
as: 'productInfo',
},
},
{
$unwind: {
path: '$productInfo',
},
},
{ {
$lookup: { $lookup: {
from: 'gasordines', from: 'gasordines',
@@ -588,13 +575,13 @@ router.post('/:userId/gestord', authenticate, async function (req, res, next) {
$group: { $group: {
_id: '$product._id', _id: '$product._id',
name: { name: {
$first: '$productInfo.name', $first: '$product.productInfo.name',
}, },
weight: { weight: {
$first: '$productInfo.weight', $first: '$product.productInfo.weight',
}, },
unit: { unit: {
$first: '$productInfo.unit', $first: '$product.productInfo.unit',
}, },
price_acquistato: { price_acquistato: {
$first: '$product.price_acquistato', $first: '$product.price_acquistato',

View File

@@ -84,7 +84,6 @@ const Collana = require('../models/collana');
const { Catalog } = require('../models/catalog'); const { Catalog } = require('../models/catalog');
const { RaccoltaCataloghi } = require('../models/raccoltacataloghi'); const { RaccoltaCataloghi } = require('../models/raccoltacataloghi');
const Publisher = require('../models/publisher'); const Publisher = require('../models/publisher');
const ProductInfo = require('../models/productInfo');
const Scontistica = require('../models/scontistica'); const Scontistica = require('../models/scontistica');
const Department = require('../models/department'); const Department = require('../models/department');
const { Category } = require('../models/category'); const { Category } = require('../models/category');
@@ -1953,7 +1952,6 @@ async function load(req, res, version = '0') {
? Product.findAllIdApp(idapp, undefined, undefined, req.user ? User.isManager(req.user.perm) : false) ? Product.findAllIdApp(idapp, undefined, undefined, req.user ? User.isManager(req.user.perm) : false)
: Promise.resolve([]),*/ : Promise.resolve([]),*/
products: Promise.resolve([]), products: Promise.resolve([]),
// productInfos: version >= 91 ? ProductInfo.findAllIdApp(idapp) : Promise.resolve([]),
productInfos: Promise.resolve([]), productInfos: Promise.resolve([]),
catprods: version >= 91 ? Product.getArrCatProds(idapp, shared_consts.PROD.BOTTEGA) : Promise.resolve([]), catprods: version >= 91 ? Product.getArrCatProds(idapp, shared_consts.PROD.BOTTEGA) : Promise.resolve([]),
subcatprods: version >= 91 ? SubCatProd.findAllIdApp(idapp) : Promise.resolve([]), subcatprods: version >= 91 ? SubCatProd.findAllIdApp(idapp) : Promise.resolve([]),

File diff suppressed because it is too large Load Diff

View File

@@ -5935,8 +5935,7 @@ module.exports = {
return mydate2; return mydate2;
}, },
async downloadImgIfMissing(productInfo) { async downloadImgIfMissing(product) {
const ProductInfo = require('../models/productInfo');
const Product = require('../models/product'); const Product = require('../models/product');
try { try {
@@ -5953,33 +5952,33 @@ module.exports = {
const vecchiomodo = false; const vecchiomodo = false;
if (productInfo.image_link && vecchiomodo) { if (product.productInfo.image_link && vecchiomodo) {
const relativeimg = productInfo.image_link.split('/').pop(); const relativeimg = product.productInfo.image_link.split('/').pop();
const img = const img =
this.getdirByIdApp(productInfo.idapp) + this.getdirByIdApp(product.productInfo.idapp) +
dirmain + dirmain +
server_constants.DIR_UPLOAD + server_constants.DIR_UPLOAD +
'/products/' + '/products/' +
productInfo.image_link.split('/').pop(); product.productInfo.image_link.split('/').pop();
const savePath = path.resolve(__dirname, img); // Sostituisci con il percorso dove salvare l'immagine const savePath = path.resolve(__dirname, img); // Sostituisci con il percorso dove salvare l'immagine
let scaricaimg = !productInfo.imagefile || !(await this.isFileExistsAsync(savePath)); let scaricaimg = !product.productInfo.imagefile || !(await this.isFileExistsAsync(savePath));
if (!productInfo.imagefile && (await this.isFileExistsAsync(savePath))) { if (!product.productInfo.imagefile && (await this.isFileExistsAsync(savePath))) {
// esiste il file, ma sul DB non è corretto // esiste il file, ma sul DB non è corretto
const stats = fs.statSync(savePath); // Ottieni informazioni sul file const stats = fs.statSync(savePath); // Ottieni informazioni sul file
if (stats.size > 0) { if (stats.size > 0) {
// Controlla se la dimensione del file è maggiore di zero // Controlla se la dimensione del file è maggiore di zero
// Esiste il file ed è non vuoto, ma sul DB non è corretto // Esiste il file ed è non vuoto, ma sul DB non è corretto
productInfo.imagefile = relativeimg; product.productInfo.imagefile = relativeimg;
return { prodInfo: productInfo, aggiornatoimg: true }; return { prodInfo: product.productInfo, aggiornatoimg: true };
} else { } else {
scaricaimg = true; scaricaimg = true;
} }
} }
if (productInfo.imagefile && (await this.isFileExistsAsync(savePath))) { if (product.productInfo.imagefile && (await this.isFileExistsAsync(savePath))) {
// esiste il file, ma sul DB non è corretto // esiste il file, ma sul DB non è corretto
const stats = fs.statSync(savePath); // Ottieni informazioni sul file const stats = fs.statSync(savePath); // Ottieni informazioni sul file
@@ -5991,12 +5990,12 @@ module.exports = {
if (scaricaimg && vecchiomodo) { if (scaricaimg && vecchiomodo) {
// Download image from the URL productInfo.image_link // Download image from the URL productInfo.image_link
productInfo.imagefile = relativeimg; product.productInfo.imagefile = relativeimg;
const downloader = new ImageDownloader(); const downloader = new ImageDownloader();
const aggiornatoimg = await downloader const aggiornatoimg = await downloader
.downloadImage(productInfo.image_link, savePath, { .downloadImage(product.productInfo.image_link, savePath, {
maxRetries: 1, maxRetries: 1,
initialDelay: 300, initialDelay: 300,
timeout: 15000, timeout: 15000,
@@ -6010,44 +6009,44 @@ module.exports = {
return result; return result;
}); });
return { prodInfo: productInfo, aggiornatoimg: aggiornatoimg.ris }; return { prodInfo: product.productInfo, aggiornatoimg: aggiornatoimg.ris };
} }
} }
let fileesistente = false; let fileesistente = false;
if (productInfo.imagefile && productInfo.imagefile !== 'noimg.jpg') { if (product.productInfo.imagefile && product.productInfo.imagefile !== 'noimg.jpg') {
// controlla se esiste il file // controlla se esiste il file
const img = const img =
this.getdirByIdApp(productInfo.idapp) + this.getdirByIdApp(product.productInfo.idapp) +
dirmain + dirmain +
server_constants.DIR_UPLOAD + server_constants.DIR_UPLOAD +
'/products/' + '/products/' +
productInfo.imagefile.split('/').pop(); product.productInfo.imagefile.split('/').pop();
const filecompleto = path.resolve(__dirname, img); // Sostituisci con il percorso dove salvare l'immagine const filecompleto = path.resolve(__dirname, img); // Sostituisci con il percorso dove salvare l'immagine
// Se non esiste lo scarico ! // Se non esiste lo scarico !
fileesistente = await this.isFileExistsAsync(filecompleto); fileesistente = await this.isFileExistsAsync(filecompleto);
} }
if (!vecchiomodo && (!productInfo.image_link || !fileesistente)) { if (!vecchiomodo && (!product.productInfo.image_link || !fileesistente)) {
let scarica_da_sito = !productInfo.imagefile || productInfo.imagefile === 'noimg.jpg'; let scarica_da_sito = !product.productInfo.imagefile || product.productInfo.imagefile === 'noimg.jpg';
if (!scarica_da_sito && productInfo.imagefile) { if (!scarica_da_sito && product.productInfo.imagefile) {
scarica_da_sito = !fileesistente; // Se non esiste lo scarico ! scarica_da_sito = !fileesistente; // Se non esiste lo scarico !
} }
if (scarica_da_sito && !productInfo.image_not_found) { if (scarica_da_sito && !product.productInfo.image_not_found) {
// date and time // date and time
productInfo.imagefile = 'img_' + new Date().toISOString().replace(/T/, ' ').replace(/\..+/, ''); product.productInfo.imagefile = 'img_' + new Date().toISOString().replace(/T/, ' ').replace(/\..+/, '');
const img = const img =
this.getdirByIdApp(productInfo.idapp) + this.getdirByIdApp(product.productInfo.idapp) +
dirmain + dirmain +
server_constants.DIR_UPLOAD + server_constants.DIR_UPLOAD +
'/products/' + '/products/' +
productInfo.imagefile.split('/').pop(); product.productInfo.imagefile.split('/').pop();
let savePath = path.resolve(__dirname, img); // Sostituisci con il percorso dove salvare l'immagine let savePath = path.resolve(__dirname, img); // Sostituisci con il percorso dove salvare l'immagine
let link = 'https://www.gruppomacro.com/copertine.php?id_gm=' + productInfo.sku; let link = 'https://www.gruppomacro.com/copertine.php?id_gm=' + product.productInfo.sku;
const downloader = new ImageDownloader(); const downloader = new ImageDownloader();
@@ -6067,12 +6066,12 @@ module.exports = {
(aggiornatoimg?.filepath && aggiornatoimg?.filepath?.includes('noimg.jpg')) (aggiornatoimg?.filepath && aggiornatoimg?.filepath?.includes('noimg.jpg'))
) { ) {
// non trovato quindi la prossima volta non richiederlo // non trovato quindi la prossima volta non richiederlo
await ProductInfo.setImgNotFound(productInfo._id); await Product.setImgNotFound(product._id);
} }
if (aggiornatoimg?.filepath?.includes('noimg.jpg')) { if (aggiornatoimg?.filepath?.includes('noimg.jpg')) {
// nascondi il prodotto se non trovo l'immagine ! // nascondi il prodotto se non trovo l'immagine !
await Product.updateOne({ idProductInfo: productInfo._id }, { $set: { deleted: true } }); await Product.updateOne({ _id: product._id }, { $set: { deleted: true } });
aggiornatoimg = { ris: false, deleted: true }; aggiornatoimg = { ris: false, deleted: true };
} }
@@ -6080,10 +6079,10 @@ module.exports = {
if (aggiornatoimg?.filepath) { if (aggiornatoimg?.filepath) {
const filenamebase = path.basename(aggiornatoimg.filepath); const filenamebase = path.basename(aggiornatoimg.filepath);
// const img = '/upload/products/' + filenamebase; // const img = '/upload/products/' + filenamebase;
productInfo.imagefile = filenamebase; product.productInfo.imagefile = filenamebase;
} }
return { prodInfo: productInfo, aggiornatoimg: aggiornatoimg.ris }; return { prodInfo: product.productInfo, aggiornatoimg: aggiornatoimg.ris };
} else { } else {
return { prodInfo: null, aggiornatoimg: false }; return { prodInfo: null, aggiornatoimg: false };
} }

View File

@@ -66,7 +66,6 @@ const { MsgTemplate } = require('../models/msg_template');
const { Graduatoria } = require('../models/graduatoria'); const { Graduatoria } = require('../models/graduatoria');
const Product = require('../models/product'); const Product = require('../models/product');
const ProductInfo = require('../models/productInfo');
const Producer = require('../models/producer'); const Producer = require('../models/producer');
const Cart = require('../models/cart'); const Cart = require('../models/cart');
const OrdersCart = require('../models/orderscart'); const OrdersCart = require('../models/orderscart');
@@ -116,7 +115,6 @@ module.exports = {
else if (tablename === 'operators') mytable = Operator; else if (tablename === 'operators') mytable = Operator;
else if (tablename === 'products') mytable = Product; else if (tablename === 'products') mytable = Product;
else if (tablename === 'arrvariazioni') mytable = Product; else if (tablename === 'arrvariazioni') mytable = Product;
else if (tablename === 'productinfos') mytable = ProductInfo;
else if (tablename === 'storehouses') mytable = Storehouse; else if (tablename === 'storehouses') mytable = Storehouse;
else if (tablename === 'providers') mytable = Provider; else if (tablename === 'providers') mytable = Provider;
else if (tablename === 'gasordines') mytable = Gasordine; else if (tablename === 'gasordines') mytable = Gasordine;

View File

@@ -258,7 +258,7 @@ module.exports = {
], ],
TABLES_USER_ID: ['mygroups', 'myskills', 'mybachecas', 'myhosps', 'mygoods'], TABLES_USER_ID: ['mygroups', 'myskills', 'mybachecas', 'myhosps', 'mygoods'],
TABLES_CREATEDBY: ['mygroups', 'circuits', 'attivitas'], TABLES_CREATEDBY: ['mygroups', 'circuits', 'attivitas'],
TABLES_UPDATE_LASTMODIFIED: ['myskills', 'mybachecas', 'myhosps', 'mygoods', 'bots', 'mygroups', 'circuits', 'attivitas', 'myelems', 'mypages', 'productinfos', 'products', 'catalogs', 'crons'], TABLES_UPDATE_LASTMODIFIED: ['myskills', 'mybachecas', 'myhosps', 'mygoods', 'bots', 'mygroups', 'circuits', 'attivitas', 'myelems', 'mypages', 'products', 'catalogs', 'crons'],
TABLES_FIELDS_DESCR_AND_CITY_AND_USER: ['myskills', 'mybachecas', 'myhosps', 'mygoods'], TABLES_FIELDS_DESCR_AND_CITY_AND_USER: ['myskills', 'mybachecas', 'myhosps', 'mygoods'],

1
warnedUsers.json Normal file
View File

@@ -0,0 +1 @@
[5356627050]