import products dinamically

This commit is contained in:
Surya Paolo
2024-02-06 20:12:54 +01:00
parent 9fe81713e5
commit 64bd3cebb3
13 changed files with 577 additions and 32 deletions

View File

@@ -38,6 +38,151 @@ router.post('/updateval', authenticate, async (req, res) => {
});
function fixURL(url) {
return url.replace(/https:\//g, 'https://');
}
function completaSettaggioProduct_AndProductInfo(arrcampi_productInfo, arrcampi_product, rec, product, productInfo) {
try {
if (shared_consts.CAMPI_PRODUCTINFO_CONVERT.includes('weight_and_unit')) {
const ris1 = tools.getWeightAndUnitByText(rec['weight_and_unit']);
if (ris1) {
productInfo.weight = ris1.weight;
productInfo.unit = ris1.unit;
}
}
if (shared_consts.CAMPI_PRODUCTINFO_CONVERT.includes('weight_and_unit_lordo')) {
const ris2 = tools.getWeightAndUnitByText(rec['weight_and_unit_lordo']);
if (ris2) {
productInfo.weight_lordo = ris2.weight;
productInfo.unit_lordo = ris2.unit;
}
}
if (rec.hasOwnProperty('link_scheda')) {
productInfo['link_scheda'] = fixURL(rec['link_scheda'])
}
for (const campo of shared_consts.PRODUCTINFO.CAMPI_FIRST_UPPERCASE) {
if (rec.hasOwnProperty(campo)) {
productInfo[campo] = tools.capitalize(rec[campo]);
}
}
// Conversione in Euro
for (campoprezzo of shared_consts.CAMPI_EURO) {
if (rec.hasOwnProperty(campoprezzo)) {
product[campoprezzo] = tools.convertPriceEurToValue(rec[campoprezzo])
}
}
if (!productInfo.img && product.code) {
productInfo.img = 'upload/products/' + product.code + '.jpg';
}
return { product, productInfo };
} catch (e) {
console.error('Err', e);
}
return { product, productInfo };
}
function getValoriAndIndice(dati, arrinclude) {
const campi = dati;
for (const key in campi) {
if (Object.hasOwnProperty.call(obj, key)) {
const value = obj[key];
console.log(`${key}: ${value}`);
}
}
const risultato = campi.map((campo, indice) => {
let mycampo = campo.trim();
if (arrinclude) {
if (arrinclude.includes(mycampo))
return { name: mycampo, ind: indice };
} else {
return { name: mycampo, ind: indice };
}
});
return risultato;
}
function getValoriAndIndice_ProductInfo(dati) {
//return getValoriAndIndice(dati, shared_consts.CAMPI_PRODUCTINFO)
return shared_consts.CAMPI_PRODUCTINFO;
}
function getValoriAndIndice_Product(dati) {
//return getValoriAndIndice(dati, shared_consts.CAMPI_PRODUCT);
return shared_consts.CAMPI_PRODUCT;
}
function extractArrayDataFromCSV(idapp, rec) {
try {
// la prima riga contiene il nome della proprietà:
let productInfo = {
idapp: idapp,
idCatProds: [],
idSubCatProds: [],
};
let product = {
idapp,
};
arrcampi_productInfo = getValoriAndIndice_ProductInfo(null);
arrcampi_product = getValoriAndIndice_Product(null);
for (const campoobj of arrcampi_productInfo) {
if (rec.hasOwnProperty(campoobj))
productInfo[campoobj] = rec[campoobj];
}
for (const campoobj of arrcampi_product) {
if (rec.hasOwnProperty(campoobj))
product[campoobj] = rec[campoobj];
}
const ris = completaSettaggioProduct_AndProductInfo(arrcampi_productInfo, arrcampi_product, rec, product, productInfo);
/*
// code: product.code,
name: product.name,
link: product.link,
idCatProds: [],
idSubCatProds: [],
img: 'upload/products/' + product.code + '.jpg',
weight: product.weight,
unit: tools.getIdUnitsByText(product.unit),
}
*/
return ris;
} catch (e) {
console.error('Err', e);
}
return dataObjects;
};
router.post('/import', authenticate, async (req, res) => {
const cmd = req.body.cmd;
const idapp = req.body.idapp;
@@ -64,7 +209,7 @@ router.post('/import', authenticate, async (req, res) => {
let inventario = recinv;
inventario.idapp = idapp;
let risrec = await Inventariogm.findOneAndUpdate(queryprod, { $set: inventario }, { new: true, upsert: true });
}
@@ -97,7 +242,7 @@ router.post('/import', authenticate, async (req, res) => {
arrcat = product.cat_name.trim().split(',');
for (const mycat of arrcat) {
let mycatstr = mycat.trim();
// Cerca la Categoria
reccateg = await CatProd.findOne({ idapp, name: mycatstr }).lean();
if (!reccateg) {
@@ -117,7 +262,7 @@ router.post('/import', authenticate, async (req, res) => {
arrsubcat = product.subcat_name.trim().split(',');
for (const mysubcat of arrsubcat) {
let mysubcatstr = mysubcat.trim();
// Cerca la Sotto Categoria
let recsubcateg = await SubCatProd.findOne({ idapp, name: mysubcatstr }).lean();
if (!recsubcateg) {
@@ -176,16 +321,16 @@ router.post('/import', authenticate, async (req, res) => {
ris = await recGas.save();
recGas = await Gasordine.findOne({ idapp, name: product.gas_name }).lean();
}
let recProductExist = null;
let queryprod = { idProductInfo: product.idProductInfo };
if (recGas) {
queryprod = {...queryprod, idGasordine: recGas._id};
queryprod = { ...queryprod, idGasordine: recGas._id };
}
recProductExist = await Product.findOne({ queryprod }).lean();
if (!recProductExist) {
isnuovo = true;
}
@@ -225,6 +370,154 @@ router.post('/import', authenticate, async (req, res) => {
}
}
} else if (cmd === shared_consts.Cmd.PRODUCTS_V2) {
let arrrec = JSON.parse(`[${data.arrdata}]`);
let updated = 0;
let imported = 0;
let errors = 0;
let ind = 0
const [, ...myarrshift] = arrrec;
for (const rec of myarrshift) {
let risprod = extractArrayDataFromCSV(idapp, rec);
let product = risprod.product;
let productInfo = risprod.productInfo;
let isnuovo = false
let setta = false
let reccateg = null;
if (rec.cat_name) {
arrcat = rec.cat_name.trim().split(',');
for (const mycat of arrcat) {
let mycatstr = mycat.trim();
// Cerca la Categoria
reccateg = await CatProd.findOne({ idapp, name: mycatstr }).lean();
if (!reccateg) {
// Non esiste questo produttore, quindi lo creo !
reccateg = new CatProd({ idapp, name: mycatstr });
ris = await reccateg.save();
reccateg = await CatProd.findOne({ idapp, name: mycatstr }).lean();
}
if (reccateg) {
productInfo.idCatProds.push(reccateg._id);
}
}
}
if (rec.subcat_name) {
arrsubcat = rec.subcat_name.trim().split(',');
for (const mysubcat of arrsubcat) {
let mysubcatstr = mysubcat.trim();
// Cerca la Sotto Categoria
let recsubcateg = await SubCatProd.findOne({ idapp, name: mysubcatstr }).lean();
if (!recsubcateg) {
// Non esiste questa Sotto Categoria, quindi la creo !
const idCatProd = reccateg ? reccateg._id : ''
recsubcateg = new SubCatProd({ idapp, name: mysubcatstr, idCatProd });
ris = await recsubcateg.save();
recsubcateg = await SubCatProd.findOne({ idapp, name: mysubcatstr, idCatProd }).lean();
}
if (recsubcateg) {
productInfo.idSubCatProds.push(recsubcateg._id);
}
}
}
if (!rec.hasOwnProperty('active')) {
product.active = true;
}
let esisteindb = await ProductInfo.findOne({ code: productInfo.code }).lean();
// Update ProductInfo
let risrecInfo = await ProductInfo.findOneAndUpdate({ code: productInfo.code }, { $set: productInfo }, { new: true, upsert: true });
if (risrecInfo) {
product.idProductInfo = risrecInfo._id;
recnewInfo = await ProductInfo.findOne({ code: productInfo.code }).lean();
if (risrecInfo._id) {
// Record existed, so it was updated
let arrfieldchange = tools.differentObjects(productInfo, recnewInfo);
if (arrfieldchange && arrfieldchange.length > 0) {
// updated++;
console.log('Changed: ', recnewInfo.name + ': ' + arrfieldchange);
}
}
// Cerca il GAS
let recGas = null;
if (rec.gas_name) {
// Cerca il GAS
recGas = await Gasordine.findOne({ idapp, name: rec.gas_name }).lean();
}
if (!recGas && !!rec.gas_name) {
recGas = new Gasordine({ idapp, name: rec.gas_name, active: true });
// Non esiste questo GAS, quindi lo creo !
ris = await recGas.save();
recGas = await Gasordine.findOne({ idapp, name: rec.gas_name }).lean();
}
let recProductExist = null;
let queryprod = { idProductInfo: product.idProductInfo };
if (recGas) {
queryprod = { ...queryprod, idGasordine: recGas._id };
}
recProductExist = await Product.findOne({ queryprod }).lean();
if (!recProductExist) {
isnuovo = true;
}
if (!options.aggiornaStockQty && esisteindb && !isnuovo) {
delete product.stockQty;
delete product.maxbookableGASQty;
}
// AGGIORNA PRODUCT
let risrec = await Product.findOneAndUpdate(queryprod, { $set: product }, { new: true, upsert: true });
let recnew = await Product.findOne(queryprod).lean();
if (risrec) {
if (risrec._id) {
// Record existed, so it was updated
let arrfieldchange = tools.differentObjects(product, recnew);
if (arrfieldchange.length > 0) {
updated++;
console.log('Changed: ', product.idProductInfo + ': ' + arrfieldchange);
}
} else {
// Record didn't exist, so it was created
imported++;
}
} else {
// risrec is null or undefined, indicating an error
console.error('Error: ', product.productInfo.name);
errors++;
}
await Product.singlerecconvert_AfterImport_AndSave(idapp, recnew, isnuovo);
} else {
console.error('Error ProductInfo: ', product.code);
errors++;
}
ind++;
}
// L'opzione ordered: false gestisce gli errori senza interrompere l'inserimento
/*return await Product.insertMany(dataObjects, { ordered: false })