- 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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -202,7 +202,7 @@ module.exports.executeQueryTable = function (idapp, params) {
return tools.executeQueryTable(this, idapp, params);
};
module.exports.findAllIdApp = async function (idapp, code, id) {
/*module.exports.findAllIdApp = async function (idapp, code, id) {
let myfind = {};
let myqueryadd = {};
let query = [];
@@ -295,299 +295,9 @@ module.exports.findAllIdApp = async function (idapp, code, id) {
console.error('E', e);
}
};
module.exports.getProductByCode = function (idapp, code) {
return productInfo.findAllIdApp(idapp, code);
}
module.exports.replaceProductImgToImageFile = async function (abilitaserver) {
const ProductInfo = this;
if (abilitaserver) {
// const result = await ProductInfo.updateMany({ "img": { $exists: true } }, { $rename: { 'img': 'imagefile' } });
// Trova tutti i documenti con il campo 'img' che esiste
const documents = await ProductInfo.find({ "img": { $exists: true } });
// Aggiorna ciascun documento
for (let doc of documents) {
if (doc.img && doc.img.startsWith('upload/products/')) {
// Rimuovi il prefisso '/upload/products' dal campo `img`
doc.imagefile = doc.img.replace(/^\upload\/products\//, '');
doc.img = undefined; // Può anche rimuovere il campo img corrente se desiderato
await doc.save(); // Salva il documento aggiornato
}
}
console.log(`Updated ${documents.length} document(s) with new imagefile paths.`);
} else {
const documents = await ProductInfo.find({ "imagefile": { $exists: true } });
// Aggiorna ciascun documento
for (let doc of documents) {
if (doc.imagefile && doc.imagefile.startsWith('upload/products/')) {
// Rimuovi il prefisso '/upload/products' dal campo `img`
doc.imagefile = doc.imagefile.replace(/^\upload\/products\//, '');
await doc.save(); // Salva il documento aggiornato
}
}
console.log(`Updated ${documents.length} document(s) with new imagefile paths.`);
};*/
}
await ProductInfo.updateMany({}, { 'vers_img': 0 });
console.log(`Updated ${result.modifiedCount} document(s).`);
};
/**
* @typedef {Object} Article
* @property {bigint} Id
* @property {number} IdArticolo
* @property {string} Ean13
* @property {string} Titolo
* @property {string} ListaAutori
* @property {string} ListaArgomenti
* @property {number} IdStatoProdotto
* @property {number} PrezzoIvato
* @property {number} IdMarchioEditoriale
* @property {number} IdCollana
* @property {Date} DataPubblicazione
* @property {number} IdTipologia
* @property {number} IdTipoFormato
* @property {string} Misure
* @property {string} Pagine
* @property {string} Sottotitolo
* @property {string} Durata
* @property {string} Numero
* @property {string} Edizione
* @property {string} Ristampa
* @property {Date} DataInizioCampagna
* @property {Date} DataFineCampagna
* @property {number} ScontoCampagna
* @property {number} PrezzoIvatoScontatoCampagna
* @property {Date} DataOra
* @property {boolean} Enabled
* @property {number} IDTagGruppo
* @property {string} Utente
* @property {number} PercIva
* @property {number} IdTitoloOriginale
* @property {boolean} EnabledAlFresco
* @property {number} CodEdizione
* @property {string} FasciaEta
* @property {string} DescrizioneStatoProdotto
* @property {string} DescrizioneTipologia
* @property {string} DescrizioneFormato
* @property {string} DescrizioneCollana
* @property {string} DescrArgomento
* @property {string} AutoriCompleti
* @property {string} CasaEditrice
*/
/**
* Aggiorna il prodotto basandosi su un articolo
* @param {Article} article - Dati dell'articolo da aggiornare
* @param {boolean} creanew
* @returns {Promise<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()
.then(() => { })

View File

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

View File

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

View File

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