Files
freeplanet_serverside/src/server/models/productInfo.js

446 lines
9.7 KiB
JavaScript
Executable File

mongoose = require('mongoose').set('debug', false)
const Schema = mongoose.Schema;
const tools = require('../tools/general');
mongoose.Promise = global.Promise;
mongoose.level = "F";
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
const productInfoSchema = new Schema({
idapp: {
type: String,
},
department: {
type: String, ref: 'Department'
},
sku: {
type: String,
},
code: {
type: String,
unique: true,
required: true,
},
codice: { // codice interno prodotto
type: String,
},
id_wp: { // id in wordpress
type: String,
},
codice_EAN: {
type: String,
},
barcode: {
type: String,
},
name: {
type: String,
},
description: {
type: String,
},
short_descr: {
type: String,
},
idCatProds: [{ type: Schema.Types.ObjectId, ref: 'CatProd' }],
idSubCatProds: [{ type: Schema.Types.ObjectId, ref: 'SubCatProd' }],
color: {
type: String
},
size: {
type: String // 11x4x3
},
weight: {
type: Number
},
weight_lordo: {
type: Number
},
unit: {
type: Number,
default: 0,
},
unit_lordo: {
type: Number,
default: 0,
},
sfuso: { // serve se moltiplicare le qta (es: 12 kg) oppure fare (2 x 20 ml)
type: Boolean
},
vegan: {
type: Boolean
},
icon: {
type: String,
},
img: {
type: String,
},
imagefile: {
type: String,
},
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' }],
idCollana: { type: Number },
idPublisher: { type: Schema.Types.ObjectId, ref: 'Publisher' },
collezione: {
type: String,
},
ListaArgomenti: {
type: String,
},
date_pub: {
type: Date,
},
date_pub_ts: {
type: Number,
},
productTypes: [{
type: Number,
}],
date_updated: {
type: Date,
},
totVen: Number,
totFat: Number,
vLast3M: Number,
fatLast3M: Number,
vLast6M: Number,
vLastY: Number,
vLast2Y: Number,
dataUltimoOrdine: Date,
rank3M: Number,
rank6M: Number,
rank1Y: Number,
descrizione_breve_macro: String,
descrizione_completa_macro: String,
sottotitolo: String,
link_macro: String,
});
var productInfo = module.exports = mongoose.model('ProductInfo', productInfoSchema);
module.exports.getFieldsForSearch = function () {
return [
{ field: 'name', type: tools.FieldType.string },
{ field: 'code', type: tools.FieldType.string },
{ field: 'sku', type: tools.FieldType.string },
{ field: 'codice_EAN', type: tools.FieldType.string },
]
};
module.exports.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params);
};
module.exports.findAllIdApp = async function (idapp, code, id) {
let myfind = {};
let myqueryadd = {};
let query = [];
try {
if (idapp)
myfind = { idapp };
if (code) {
myfind = { ...myfind, code }
}
if (id) {
myqueryadd = {
$addFields: {
myId1: {
$toObjectId: id,
},
},
}
myfind = {
$expr: {
$eq: ["$_id", "$myId1"],
},
}
query.push(myqueryadd);
}
query.push(
{ $match: myfind },
{
$lookup: {
from: 'catprods',
localField: 'idCatProds',
foreignField: '_id',
as: 'catprods'
}
},
{
$lookup: {
from: 'authors',
localField: 'idAuthors',
foreignField: '_id',
as: 'authors'
}
},
{
$lookup: {
from: 'collanas',
localField: 'idCollana',
foreignField: '_id',
as: 'collana'
}
},
{
$lookup: {
from: 'publishers',
localField: 'idPublisher',
foreignField: '_id',
as: 'publisher'
}
},
{
$lookup: {
from: 'subcatprods',
localField: 'idSubCatProds',
foreignField: '_id',
as: 'subcatprods'
}
},
{
$sort: {
name: 1 // 1 for ascending order, -1 for descending order
}
},
);
let ris = await productInfo.aggregate(query)
return ris;
} catch (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.createIndexes((err) => {
if (err) throw err;
});