Files
freeplanet_serverside/src/server/router/admin_router.js

2044 lines
67 KiB
JavaScript
Raw Normal View History

const express = require('express');
const router = express.Router();
2022-09-14 11:32:04 +02:00
const mongoose = require('mongoose').set('debug', false);
2023-12-14 15:20:21 +01:00
const { CfgServer } = require('../models/cfgserver');
const shared_consts = require('../tools/shared_nodejs');
const tools = require('../tools/general');
const fs = require('fs');
2023-12-14 15:20:21 +01:00
const { City } = require('../models/city');
const Product = require('../models/product');
2024-01-30 14:00:37 +01:00
const Inventariogm = require('../models/inventariogm');
2024-04-29 14:58:45 +02:00
const Importamacro = require('../models/importamacro');
2024-12-02 19:37:53 +01:00
const ImportaDescr = require('../models/importadescr');
const ImportaIsbn = require('../models/importaisbn');
2023-12-28 23:48:03 +01:00
const ProductInfo = require('../models/productInfo');
2023-12-27 02:58:15 +01:00
const CatProd = require('../models/catprod');
const Collana = require('../models/collana');
2024-05-04 14:49:02 +02:00
const Author = require('../models/author');
const Publisher = require('../models/publisher');
2024-01-12 13:02:59 +01:00
const SubCatProd = require('../models/subcatprod');
2024-01-16 17:09:55 +01:00
const Gasordine = require('../models/gasordine');
const { User } = require('../models/user');
const server_constants = require('../tools/server_constants');
const { ImageDownloader } = require('../tools/general.js');
const path = require('path');
const gs = require('ghostscript4js');
const { PDFDocument, rgb } = require('pdf-lib');
const pdf = require('pdf-parse');
2023-12-14 15:20:21 +01:00
var { authenticate } = require('../middleware/authenticate');
const multer = require('multer');
const DIR_PDF_IN = __dirname + '/upload/files_input/';
const DIR_PDF_OUT = __dirname + '/upload/files_output/';
const upload = multer({ dest: DIR_PDF_IN });
const util = require('util');
const cwd = process.cwd();
const { exec } = require('child_process');
const execPromise = util.promisify(exec);
async function updateProductInfo(recproductInfoAttuale, product, idapp, mycatstr) {
if (!recproductInfoAttuale || !mycatstr) return recproductInfoAttuale;
let idArgomentoNum = null;
let productInfo = null;
if (product.ListaArgomenti) {
idArgomentoNum = parseInt(product.ListaArgomenti);
productInfo = { ...recproductInfoAttuale, IdArgomento: idArgomentoNum };
} else {
productInfo = { ...recproductInfoAttuale };
}
let reccatprod = await findOrCreateCatProd(idapp, idArgomentoNum, mycatstr);
if (reccatprod) {
updateProductInfoCatProds(productInfo, reccatprod);
}
return productInfo;
}
async function findOrCreateCatProd(idapp, IdArgomento, DescrArgomento) {
let reccatprod = null;
if (IdArgomento) {
reccatprod = await CatProd.findOne({ idapp, IdArgomento }).lean();
}
if (!reccatprod) {
reccatprod = await CatProd.findOne({ idapp, name: DescrArgomento }).lean();
if (reccatprod) {
if (IdArgomento) {
await CatProd.findOneAndUpdate(
{ _id: reccatprod._id },
{ $set: { IdArgomento } },
{ new: true, upsert: false }
);
}
} else {
if (IdArgomento) {
try {
reccatprod = new CatProd({ idapp, IdArgomento, name: DescrArgomento });
await reccatprod.save();
} catch (e) {
console.error('Errore nella creazione di CatProd:', e);
return null;
}
}
}
}
return reccatprod;
}
function updateProductInfoCatProds(productInfo, reccatprod) {
if (productInfo) {
const isChanged = !productInfo.idCatProds || productInfo.idCatProds.length !== 1 ||
productInfo.idCatProds[0] !== reccatprod._id;
if (isChanged) {
productInfo.idCatProds = [reccatprod._id];
console.log('ARGOMENTO VARIATO!', reccatprod.name);
}
}
}
async function compressPdf(inputFile, outputFile, compressione) {
try {
const tempFolder = path.join(cwd, "temp");
const hasTempFolder = tools.isFileExists(tempFolder);
if (!hasTempFolder) {
await fs.mkdir(tempFolder); // Usa la versione promessa di mkdir
}
/*
Quando utilizzi Ghostscript per comprimere un PDF e desideri controllare la qualità di stampa, puoi modificare i parametri dell'opzione -dPDFSETTINGS per ottenere risultati migliori per scopi di stampa.
Le seguenti opzioni sono disponibili per -dPDFSETTINGS:
Opzioni di -dPDFSETTINGS
/screen: Buona per la visualizzazione su schermo; bassa qualità e dimensione del file ridotta.
/ebook: Ottimizza il PDF per la lettura su ebook; qualità media e dimensione media.
/printer: Ottimizza il PDF per la stampa di qualità; migliora la risoluzione rispetto a /ebook.
/prepress: Ottimizza per la stampa di alta qualità; ideale per progetti di stampa professionali.
/default: Usa impostazioni predefinite; generalmente fornisce un buon equilibrio tra qualità e dimensione.
*/
// Comprime il PDF utilizzando Ghostscript
const gsCommand = `gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/${compressione} -dNOPAUSE -dQUIET -dBATCH -sOutputFile="${outputFile}" "${inputFile}"`;
console.log('gsCommand', gsCommand);
// Esegui il comando per la compressione
await execPromise(gsCommand);
console.log(`PDF compresso e salvato come '${outputFile}'`);
} catch (error) {
console.error('Errore durante la compressione:', error);
throw error; // Propaga l'errore
}
}
async function convertPDF_GS(inputFile, outputFile, width, height) {
// Verifica che il file di input esista
if (!tools.isFileExists(inputFile)) {
throw new Error(`Il file di input non esiste: ${inputFile}`);
}
// Converti cm in punti (1 cm = 28.34646 punti)
const widthPt = width * 28.34646;
const heightPt = height * 28.34646;
// Arrotonda i valori
const widthPx = Math.round(widthPt);
const heightPx = Math.round(heightPt);
// Comando Ghostscript
const gsCommand = [
'-sDEVICE=pdfwrite',
'-dCompatibilityLevel=1.4',
'-dPDFSETTINGS=/prepress',
'-dNOPAUSE',
'-dQUIET',
'-dBATCH',
`-dDEVICEWIDTHPOINTS=${widthPx}`,
`-dDEVICEHEIGHTPOINTS=${heightPx}`,
'-dDPIx=300',
'-dDPIy=300',
`-sOutputFile=${outputFile}`,
inputFile
].join(' ');
try {
console.log(gsCommand);
await gs.executeSync(gsCommand); // Assicurati che executeSync restituisca una promessa o usa la funzione corretta se è sincrona.
console.log('Conversione completata con successo!');
// Verifica che il file di output sia stato generato
if (tools.isFileExists(outputFile)) {
console.log('File di output generato:', outputFile);
} else {
console.error('Il File di output NON è stato generato! :', outputFile);
}
} catch (error) {
if (error.code === 'ENOENT') {
throw new Error(`Il file di input non esiste: ${inputFile}`);
} else if (error instanceof gs.GhostscriptError) {
throw new Error(`Errore Ghostscript: ${error.message}`);
} else {
throw new Error(`Errore durante la conversione: ${error.message}`);
}
}
}
async function extractPdfInfo(inputFile) {
// Estrai le dimensioni delle pagine utilizzando pdf-lib
const existingPdfBytes = fs.readFileSync(inputFile);
const pdfDoc = await PDFDocument.load(existingPdfBytes);
// Ottieni informazioni sulle dimensioni delle pagine
const pages = pdfDoc.getPages();
const pageInfo = pages.map(page => {
const { width, height } = page.getSize();
return {
width: width, // in punti
height: height // in punti
};
});
// Estrai informazioni testuali e numero di pagine utilizzando pdf-parse
const dataBuffer = fs.readFileSync(inputFile);
const data = await pdf(dataBuffer);
const dpiInfo = {
numPages: data.numpages,
pageInfo: pageInfo
};
console.log("DPI info might require image extraction (not available directly):");
console.log("Number of Pages:", dpiInfo.numPages);
console.log("Page Dimensions (in points):", dpiInfo.pageInfo);
}
async function convertPDF_PdfLib(inputFile, outputFile, width, height, compressione) {
if (!tools.isFileExists(inputFile)) {
throw new Error(`Il file di input non esiste: ${inputFile}`);
}
try {
// Carica il PDF esistente
const existingPdfBytes = fs.readFileSync(inputFile);
const pdfDoc = await PDFDocument.load(existingPdfBytes);
// Crea un nuovo PDF
const newPdfDoc = await PDFDocument.create();
// Itera attraverso le pagine esistenti
const pages = pdfDoc.getPages();
for (const page of pages) {
const { width: originalWidth, height: originalHeight } = page.getSize();
// Calcola la larghezza e l'altezza in punti
const newWidth = width * 72; // Convertito in punti
const newHeight = height * 72; // Convertito in punti
// Crea una nuova pagina con le dimensioni specificate
const newPage = newPdfDoc.addPage([newWidth, newHeight]);
// Calcola lo scaling per mantenere le proporzioni
const scaleWidth = newWidth / originalWidth;
const scaleHeight = newHeight / originalHeight;
const scale = Math.min(scaleWidth, scaleHeight); // Usa il min per mantenere il rapporto
// Incorpora la pagina esistente nel nuovo PDF
const embeddedPage = await newPdfDoc.embedPage(page);
// Disegna la pagina incorporata nel nuovo PDF
newPage.drawPage(embeddedPage, {
x: (newWidth - originalWidth * scale) / 2, // Centrato orizzontalmente
y: (newHeight - originalHeight * scale) / 2, // Centrato verticalmente
width: originalWidth * scale,
height: originalHeight * scale,
});
}
// Salva il nuovo PDF
const pdfBytes = await newPdfDoc.save();
fs.writeFileSync(outputFile, pdfBytes);
console.log(`PDF convertito e salvato come '${outputFile}'`);
const comprimi = false;
const mostrainfo = true;
let fileout = outputFile;
if (compressione) {
const compressed = tools.removeFileExtension(outputFile) + '-compressed.pdf';
await compressPdf(outputFile, compressed, compressione);
if (mostrainfo)
extractPdfInfo(compressed);
fileout = compressed;
}
return fileout;
} catch (e) {
console.error(e);
return '';
}
}
// Endpoint POST per la conversione del PDF
router.post('/convert-pdf', upload.single('pdf'), async (req, res) => {
if (!req.file) {
return res.status(400).send('No file uploaded.');
}
const inputFile = req.file.path;
const { width, height, compressione } = req.body;
if (!width) {
fs.unlinkSync(inputFile);
return res.status(400).send('Width parameter is required');
}
let outputFile = path.join(DIR_PDF_OUT, `${tools.removeFileExtension(req.file.originalname)}-converted.pdf`);
try {
await fs.promises.mkdir(DIR_PDF_IN, { recursive: true });
await fs.promises.mkdir(DIR_PDF_OUT, { recursive: true });
// Converti il PDF
// await convertPDF_GS(inputFile, outputFile, width, height);
const fileout = await convertPDF_PdfLib(inputFile, outputFile, width, height, compressione);
if (fileout) {
// Invia il file convertito
res.download(fileout, 'output-converted.pdf', (err) => {
if (err) {
console.error('Errore durante l\'invio del file:', err);
if (!res.headersSent) {
res.status(500).send('Errore durante l\'invio del file convertito');
}
} else {
// Rimuovi i file temporanei
cleanupFiles(inputFile, outputFile);
}
});
}
} catch (error) {
console.error('Errore durante la conversione:', error);
cleanupFiles(inputFile, outputFile);
if (!res.headersSent) {
res.status(500).send(`Errore durante la conversione del PDF: ${error.message}`);
}
}
});
function cleanupFiles(inputFile, outputFile) {
if (inputFile) {
tools.deleteFile(inputFile)
.catch((err) => {
console.error('Errore durante la rimozione del file di INPUT:', err);
})
};
if (outputFile) {
tools.deleteFile(outputFile)
.catch((err) => {
console.error('Errore durante la rimozione del file di output:', err);
})
};
};
2020-04-24 10:29:25 +02:00
router.post('/updateval', authenticate, async (req, res) => {
console.log('/updateval', req.body.pairval);
2020-04-24 10:29:25 +02:00
idapp = req.body.idapp;
pair = req.body.pairval;
return await CfgServer.findOneAndUpdate(
2023-12-14 15:20:21 +01:00
{ chiave: pair.chiave, idapp, userId: pair.userId }, { $set: pair },
{ new: false }).then((item) => {
// CfgServer.find({ chiave: pair.chiave }, (err, item) => {
if (!!item) {
res.status(200).send();
} else {
res.status(400).send();
}
}).catch(err => {
console.log('ERR:', err);
res.status(400).send();
2023-12-14 15:20:21 +01:00
});
});
2024-02-06 20:12:54 +01:00
function fixURL(url) {
return url.replace(/https:\//g, 'https://');
}
async function downloadImgIfMissing(productInfo) {
if (!productInfo.image_link)
return { prodInfo: null, aggiornatoimg: false };
2024-10-26 17:11:52 +02:00
const relativeimg = productInfo.image_link.split('/').pop();
const img = 'upload/products/' + productInfo.image_link.split('/').pop();
const savePath = path.resolve(__dirname, img); // Sostituisci con il percorso dove salvare l'immagine
2024-10-26 17:11:52 +02:00
let scaricaimg = !productInfo.imagefile || !fs.existsSync(savePath);
if (!productInfo.imagefile && fs.existsSync(savePath)) {
// esiste il file, ma sul DB non è corretto
const stats = fs.statSync(savePath); // Ottieni informazioni sul file
if (stats.size > 0) { // Controlla se la dimensione del file è maggiore di zero
// Esiste il file ed è non vuoto, ma sul DB non è corretto
productInfo.imagefile = relativeimg;
return { prodInfo: productInfo, aggiornatoimg: true };
} else {
scaricaimg = true;
}
}
if (productInfo.imagefile && fs.existsSync(savePath)) {
// esiste il file, ma sul DB non è corretto
const stats = fs.statSync(savePath); // Ottieni informazioni sul file
if (stats.size <= 0) { // Controlla se la dimensione del file è maggiore di zero
scaricaimg = true;
}
}
if (scaricaimg) {
// Download image from the URL productInfo.image_link
2024-10-26 17:11:52 +02:00
productInfo.imagefile = relativeimg;
const downloader = new ImageDownloader();
2024-10-26 17:11:52 +02:00
const aggiornatoimg = await downloader.downloadImage(productInfo.image_link, savePath,
{
maxRetries: 3,
initialDelay: 300,
timeout: 15000,
}).then(result => {
if (result) {
// console.log('Download completato con successo!');
} else {
console.log('Download non riuscito.');
}
2024-10-26 17:11:52 +02:00
return result;
2024-10-26 17:11:52 +02:00
});
return { prodInfo: productInfo, aggiornatoimg };
}
2024-10-26 17:11:52 +02:00
return { prodInfo: null, aggiornatoimg: false };
}
2024-02-06 20:12:54 +01:00
2024-03-08 18:57:13 +01:00
async function completaSettaggioProduct_AndProductInfo(arrcampi_productInfo, arrcampi_product, rec, product, productInfo) {
2024-02-06 20:12:54 +01:00
try {
if (shared_consts.CAMPI_PRODUCTINFO_CONVERT.includes('weight_and_unit')) {
2024-03-08 18:57:13 +01:00
if (rec.hasOwnProperty('weight_and_unit')) {
const ris1 = tools.getWeightAndUnitByText(rec['weight_and_unit']);
if (ris1) {
productInfo.weight = ris1.weight;
productInfo.unit = ris1.unit;
}
2024-02-06 20:12:54 +01:00
}
}
if (shared_consts.CAMPI_PRODUCTINFO_CONVERT.includes('weight_and_unit_lordo')) {
2024-03-08 18:57:13 +01:00
if (rec.hasOwnProperty('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;
}
2024-02-06 20:12:54 +01:00
}
}
if (rec.hasOwnProperty('link_scheda')) {
2024-03-08 18:57:13 +01:00
if (fixURL(rec['link_scheda']))
productInfo['link_scheda'] = fixURL(rec['link_scheda'])
2024-02-06 20:12:54 +01:00
}
for (const campo of shared_consts.PRODUCTINFO.CAMPI_FIRST_UPPERCASE) {
2024-03-08 18:57:13 +01:00
2024-02-06 20:12:54 +01:00
if (rec.hasOwnProperty(campo)) {
2024-03-08 18:57:13 +01:00
let mystr = tools.capitalize(rec[campo]).trim();
if (mystr)
productInfo[campo] = mystr;
2024-02-06 20:12:54 +01:00
}
}
// Conversione in Euro
for (campoprezzo of shared_consts.CAMPI_EURO) {
if (rec.hasOwnProperty(campoprezzo)) {
product[campoprezzo] = tools.convertPriceEurToValue(rec[campoprezzo])
}
}
if (!rec.hasOwnProperty('img') && product.code) {
2024-10-22 15:26:29 +02:00
productInfo.imagefile = product.code + '.jpg';
} else {
if (rec.hasOwnProperty('img')) {
if (rec['img']) {
2024-10-22 15:26:29 +02:00
productInfo.imagefile = rec['img'];
} else {
productInfo.imagefile = '';
}
}
2024-02-06 20:12:54 +01:00
}
2024-03-08 18:57:13 +01:00
if (rec.hasOwnProperty('old_code')) {
const old_code = rec['old_code'];
let oldrec = await ProductInfo.findOne({ code: old_code }).lean();
if (oldrec) {
const precid = productInfo._id;
const preccode = productInfo.code;
productInfo = oldrec;
if (precid)
productInfo._id = precid;
else
delete productInfo._id;
2024-03-08 18:57:13 +01:00
productInfo.code = preccode;
}
}
if (rec.hasOwnProperty('productTypes')) {
productInfo.productTypes = productInfo.productTypes;
2024-05-04 14:49:02 +02:00
} else {
productInfo.productTypes = [shared_consts.PRODUCTTYPE.PRODUCT];
2024-05-04 14:49:02 +02:00
}
2024-03-08 18:57:13 +01:00
2024-02-06 20:12:54 +01:00
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;
}
2024-03-08 18:57:13 +01:00
async function extractArrayDataFromCSV(idapp, rec) {
2024-02-06 20:12:54 +01:00
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.name)) {
let myval = tools.ripulisciCampo(rec[campoobj.name]);
productInfo[campoobj.name] = (myval === 'TRUE' || myval.toUpperCase() === 'SI') ? true : ((myval === 'FALSE' || myval.toUpperCase() === 'NO') ? false : myval);
}
2024-02-06 20:12:54 +01:00
}
for (const campoobj of arrcampi_product) {
if (rec.hasOwnProperty(campoobj))
product[campoobj] = rec[campoobj];
}
2024-03-08 18:57:13 +01:00
const ris = await completaSettaggioProduct_AndProductInfo(arrcampi_productInfo, arrcampi_product, rec, product, productInfo);
2024-02-06 20:12:54 +01:00
/*
// 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;
};
2024-05-04 14:49:02 +02:00
function extractNameAndSurnameByComplete(name_complete) {
if (name_complete) {
const name = name_complete.split(' ')[0];
const surname = name_complete.split(' ')[1];
return { name, surname };
} else {
return { name: '', surname: '' };
}
}
2024-11-28 16:05:00 +01:00
function getvalueByJsonText(valore) {
if (valore && valore['#text']) {
if (valore['#text'])
return valore['#text'];
else
return value;
}
return null;
}
router.post('/import', authenticate, async (req, res) => {
try {
2024-04-29 14:58:45 +02:00
const cmd = req.body.cmd;
const idapp = req.body.idapp;
const data = req.body.data;
const options = req.body.data.options;
const liste = require('../data/liste');
let dataObjects = null;
if (cmd === shared_consts.Cmd.CITIES_SERVER) {
return await City.insertMany(liste.Comuni).then((ris) => {
return res.status(200).send(true);
});
2024-01-30 14:00:37 +01:00
} else if (cmd === shared_consts.Cmd.INVENTARIO) {
dataObjects = JSON.parse(`[${data.arrdata}]`);
2024-01-30 14:00:37 +01:00
let updated = 0;
let imported = 0;
let errors = 0;
for (const recinv of dataObjects) {
let isnuovo = false
let setta = false
let inventario = recinv;
inventario.idapp = idapp;
2024-02-06 20:12:54 +01:00
2024-01-30 14:00:37 +01:00
let risrec = await Inventariogm.findOneAndUpdate(queryprod, { $set: inventario }, { new: true, upsert: true });
}
2024-11-28 16:05:00 +01:00
} else if (cmd === shared_consts.Cmd.MACRO_DESCRELINKSITOWEB) {
let updated = 0;
let imported = 0;
let errors = 0;
const ripopola = true;
2024-12-02 19:37:53 +01:00
2024-11-28 16:05:00 +01:00
dataObjects = null;
let myarr = null;
try {
dataObjects = JSON.parse(`[${data.arrdata}]`);
myarr = dataObjects[0].item_list.item;
} catch (e) {
dataObjects = null;
}
2024-12-02 19:37:53 +01:00
if (myarr && ripopola) {
2024-11-28 16:05:00 +01:00
console.log('*** INIZIO IMPORT RIPOPOLAMENTO ... ', myarr.length);
2024-11-28 16:05:00 +01:00
// Cancella la collection ImportaMacros
2024-12-02 19:37:53 +01:00
await ImportaDescr.deleteMany({ idapp });
2024-11-28 16:05:00 +01:00
// Aggiungi i record su ImportaDescr
2024-11-28 16:05:00 +01:00
for (const recinv of myarr) {
let isnuovo = false
let setta = false
let recmacro = recinv;
recmacro.idapp = idapp;
if (recmacro.ean && recmacro.ean['#text']) {
recmacro._id = recmacro.ean['#text'];
recmacro.code = recmacro._id;
let queryprod = { idapp, code: recmacro._id };
try {
// non inserisce nuovi record, se non lo trova ! perché sono troppi !
let risrec = await ImportaDescr.findOneAndUpdate(queryprod,
{ $set: recmacro }, { new: true, upsert: true, strict: false }
);
2024-11-28 16:05:00 +01:00
if (risrec) {
imported++;
// if (imported > 1000)
// break;
if (imported % 100 === 0)
2024-12-02 19:37:53 +01:00
console.log('importato ', imported, 'su ', myarr.length);
2024-11-28 16:05:00 +01:00
}
} catch (e) {
console.error(e);
errors++;
}
}
}
}
2024-12-02 19:37:53 +01:00
// Rileggi tutti i record di ImportaDescr
dataObjects = await ImportaDescr.find({ idapp }).lean();
2024-11-28 16:05:00 +01:00
2024-12-02 19:37:53 +01:00
console.log('*** INIZIO IMPORT MACRO_DESCRELINKSITOWEB ... ');
2024-11-28 16:05:00 +01:00
let indprod = 0;
let newprod = 0;
let numprod = dataObjects.length;
for (const product of dataObjects) {
let isnuovo = false
let setta = false
let importa = true;
if (!product.code)
importa = false;
if (importa) {
let productInfo = {
idapp: product.idapp,
code: product.code,
}
const myproductInfo = await ProductInfo.findOne({ code: productInfo.code });
// IMPOSTA I VALORI SOLO SE NON ESISTONO ! ALTRIMENTI LASCIA QUELLI GIA' IMPORTATI (O MODIFICATI)
2024-11-28 16:05:00 +01:00
if (getvalueByJsonText(product.url)) {
if ((myproductInfo && !myproductInfo.link_macro) || !myproductInfo)
productInfo.link_macro = getvalueByJsonText(product.url);
2024-11-28 16:05:00 +01:00
}
if (getvalueByJsonText(product.descrizione)) {
if ((myproductInfo && !myproductInfo.descrizione_breve_macro) || !myproductInfo)
productInfo.descrizione_breve_macro = getvalueByJsonText(product.descrizione);
2024-11-28 16:05:00 +01:00
}
if (getvalueByJsonText(product.descrizione_completa)) {
if ((myproductInfo && !myproductInfo.descrizione_completa_macro) || !myproductInfo)
productInfo.descrizione_completa_macro = getvalueByJsonText(product.descrizione_completa)
2024-11-28 16:05:00 +01:00
}
if (getvalueByJsonText(product.sottotitolo)) {
if ((myproductInfo && !myproductInfo.sottotitolo) || !myproductInfo)
productInfo.sottotitolo = getvalueByJsonText(product.sottotitolo);
}
if (getvalueByJsonText(product.titolo)) {
if ((myproductInfo && !myproductInfo.name) || !myproductInfo)
productInfo.name = getvalueByJsonText(product.titolo);
2024-11-28 16:05:00 +01:00
}
2024-12-02 19:37:53 +01:00
const pagine = getvalueByJsonText(product.pagine);
let recisbn = {};
if (pagine && pagine !== '0') {
recisbn.Pagine = pagine;
}
recisbn.link_macro = productInfo.link_macro;
recisbn.descrizione_breve_macro = productInfo.descrizione_breve_macro;
recisbn.descrizione_completa_macro = productInfo.descrizione_completa_macro;
recisbn.sottotitolo = productInfo.sottotitolo;
let risisbn = await ImportaIsbn.findOneAndUpdate({ isbn: product.code }, { $set: recisbn }, { new: true, upsert: true, strict: false });
2024-11-28 16:05:00 +01:00
// Update ProductInfo, non crea nuovi record !
let risrecInfo = await ProductInfo.findOneAndUpdate({ code: productInfo.code }, { $set: productInfo }, { new: true, upsert: false });
2024-11-28 16:05:00 +01:00
indprod++;
if (indprod % 100 === 0)
2024-12-02 19:37:53 +01:00
console.log(indprod + '/' + numprod);
2024-11-28 16:05:00 +01:00
}
}
2024-12-02 19:37:53 +01:00
console.log('*** IMPORTATI: ', imported, '*** NUOVI: ', newprod, 'AGGIORNATI = ' + updated + ' (su ' + dataObjects.length + ' RECORD)');
return res.status(200).send({ updated, imported, errors });
2024-11-28 16:05:00 +01:00
} else if (cmd === shared_consts.Cmd.MACRO_RANKING) {
let updated = 0;
let imported = 0;
let errors = 0;
const ripopola = false; // SETTARE su TRUE
2024-11-28 16:05:00 +01:00
2024-12-02 19:37:53 +01:00
if (ripopola) {
2024-11-28 16:05:00 +01:00
dataObjects = null;
2024-12-02 19:37:53 +01:00
try {
dataObjects = JSON.parse(`[${data.arrdata}]`);
} catch (e) {
dataObjects = null;
}
2024-11-28 16:05:00 +01:00
2024-12-02 19:37:53 +01:00
if (dataObjects && dataObjects[0]) {
// Cancella la collection ImportaIsbn
2024-12-02 19:37:53 +01:00
await ImportaIsbn.deleteMany({ idapp });
2024-11-28 16:05:00 +01:00
2024-12-02 19:37:53 +01:00
const numtot = dataObjects[0].length
2024-11-28 16:05:00 +01:00
console.log('Numero di RECORD da Importare = ', numtot);
// Aggiungi i record su ImportaIsbn
2024-12-02 19:37:53 +01:00
for (const recinv of dataObjects[0]) {
let recmacro = recinv;
2024-11-28 16:05:00 +01:00
2024-12-02 19:37:53 +01:00
recmacro.idapp = idapp;
2024-11-28 16:05:00 +01:00
2024-12-02 19:37:53 +01:00
//recmacro._id = recmacro.id;
recmacro.sku = recmacro.IdArticolo;
2024-11-28 16:05:00 +01:00
2024-12-02 19:37:53 +01:00
if (recmacro.DataPubblicazione) {
2024-11-28 16:05:00 +01:00
2024-12-02 19:37:53 +01:00
// delete recmacro.id;
2024-11-28 16:05:00 +01:00
2024-12-02 19:37:53 +01:00
let queryprod = { idapp, sku: recmacro.sku };
try {
let risrec = await ImportaIsbn.findOneAndUpdate(queryprod, { $set: recmacro }, { new: true, upsert: true, strict: false });
if (risrec) {
imported++;
if ((imported % 100) === 0)
console.log('Importati dir TEMPORANEA ... ', imported + '/' + numtot);
2024-12-02 19:37:53 +01:00
}
} catch (e) {
console.error(e);
errors++;
}
}
2024-11-28 16:05:00 +01:00
}
}
}
2024-12-02 19:37:53 +01:00
// Rileggi tutti i record di ImportaIsbn
dataObjects = await ImportaIsbn.find({ idapp }).lean();
2024-11-28 16:05:00 +01:00
let numprod = dataObjects.length;
console.log('*** INIZIO IMPORT RANKING ... NUMRECORD = ', numprod);
2024-11-28 16:05:00 +01:00
let indprod = 0;
let newprod = 0;
if (numprod) {
// Rimuove prima tutti i valori precedenti
let risupdate = await ProductInfo.updateMany({ idapp }, {
$set: {
totVen: 0,
totFat: 0,
vLast3M: 0,
vLast6M: 0,
vLastY: 0,
vLast2Y: 0,
rank3M: 0,
rank6M: 0,
rank1Y: 0,
}
});
}
2024-11-28 16:05:00 +01:00
2024-12-02 19:37:53 +01:00
imported = 0;
2024-11-28 16:05:00 +01:00
for (const product of dataObjects) {
let isnuovo = false
let setta = false
let importa = true;
2024-12-02 19:37:53 +01:00
//if (!product.title || !product.isbn)
if (!product.sku || !product.DataPubblicazione)
2024-11-28 16:05:00 +01:00
importa = false;
if (importa) {
let versGM = product.Versione ? product.Versione : '';
// split versioneGM in array with separated ","
let arrversGM = versGM.split(",").map(x => x.trim());
const recproductInfoAttuale = await ProductInfo.findOne({ idapp, code: product.isbn });
2024-11-28 16:05:00 +01:00
let productInfo = {
idapp: product.idapp,
2024-12-02 19:37:53 +01:00
code: product.isbn ? product.isbn : product.code,
sku: product.sku,
idCatProds: recproductInfoAttuale?.idCatProds,
2024-12-02 19:37:53 +01:00
// id_wp: product._id,
2024-11-28 16:05:00 +01:00
// name: product.title,
totVen: product.totVen || 0,
totFat: product.totFat || 0,
vLast3M: product.vLast3M || 0,
fatLast3M: product.fatLast3M || 0,
vLast6M: product.vLast6M || 0,
vLastY: product.vLastY || 0,
vLast2Y: product.vLast2Y || 0,
rank3M: product.rank3M || 0,
rank6M: product.rank6M || 0,
rank1Y: product.rank1Y || 0,
}
if (!productInfo.idCatProds) {
productInfo.idCatProds = [];
}
// Aggiorna la collana solo se non è stata già impostata nel record attuale
2025-02-05 12:13:27 +01:00
//if (recproductInfoAttuale && !recproductInfoAttuale.idCollana && product.DescrizioneCollana) {
if (recproductInfoAttuale && product.DescrizioneCollana) {
const idCollanaNum = parseInt(product.IdCollana)
productInfo.idCollana = idCollanaNum;
reccollana = await Collana.findOne({ idapp, idCollana: idCollanaNum }).lean();
if (!reccollana) {
try {
// Non esiste questa collana, quindi la creo !
2025-02-05 12:13:27 +01:00
reccoll = new Collana({ idapp, idCollana: idCollanaNum, title: product.DescrizioneCollana });
ris = await reccoll.save();
} catch (e) {
console.error('Err', e);
}
}
2024-11-28 16:05:00 +01:00
}
if (recproductInfoAttuale && product.DescrArgomento) {
productInfo = await updateProductInfo(productInfo, product, idapp, product.DescrArgomento);
}
if (product.DataPubblicazione) {
productInfo.date_pub = new Date(product.DataPubblicazione);
2024-12-02 19:37:53 +01:00
// convert data to timestamp
productInfo.date_pub_ts = productInfo.date_pub.getTime();
2024-12-02 19:37:53 +01:00
}
if (product.dataUltimoOrdine) {
productInfo.dataUltimoOrdine = new Date(product.dataUltimoOrdine);
}
2024-11-28 16:05:00 +01:00
2024-11-28 16:05:00 +01:00
// Update ProductInfo
let risrecInfo = await ProductInfo.findOneAndUpdate({ idapp, code: productInfo.code }, { $set: productInfo }, { new: true, upsert: false });
2024-12-02 19:37:53 +01:00
if (risrecInfo) {
imported++;
if (imported % 100 === 0)
console.log('Importati... ', imported + '/' + numprod);
2024-12-02 19:37:53 +01:00
}
2024-11-28 16:05:00 +01:00
}
}
2024-12-02 19:37:53 +01:00
console.log('*** IMPORTATI: ', imported, ' [Prodotti = ' + indprod + '] *** NUOVI: ', newprod, 'AGGIORNATI = ' + updated + ' (su ' + dataObjects.length + ' RECORD)');
return res.status(200).send({ updated, imported, errors });
2024-04-29 14:58:45 +02:00
} else if (cmd === shared_consts.Cmd.MACRO_CATALOGO_JSON) {
let updated = 0;
let imported = 0;
let errors = 0;
2024-12-02 19:37:53 +01:00
const ripopola = true;
2024-04-29 14:58:45 +02:00
2024-12-02 19:37:53 +01:00
if (ripopola) {
2024-04-29 14:58:45 +02:00
dataObjects = null;
2024-12-02 19:37:53 +01:00
try {
dataObjects = JSON.parse(`[${data.arrdata}]`);
} catch (e) {
dataObjects = null;
}
2024-05-04 14:49:02 +02:00
2024-12-02 19:37:53 +01:00
if (dataObjects && dataObjects[0]) {
// Cancella la collection ImportaMacros
await Importamacro.deleteMany({ idapp });
2024-04-29 14:58:45 +02:00
2024-12-02 19:37:53 +01:00
// Aggiungi i record su ImportaMacros
for (const recinv of dataObjects[0]) {
let isnuovo = false
let setta = false
2024-04-29 14:58:45 +02:00
2024-12-02 19:37:53 +01:00
let recmacro = recinv;
recmacro.idapp = idapp;
2024-04-29 14:58:45 +02:00
2024-12-02 19:37:53 +01:00
recmacro._id = recmacro.id;
2024-04-29 14:58:45 +02:00
2024-12-02 19:37:53 +01:00
delete recmacro.id;
2024-04-29 14:58:45 +02:00
2024-12-02 19:37:53 +01:00
// Ottengo isbn e Pagine da ImportaIsbn
2024-04-29 14:58:45 +02:00
2024-12-02 19:37:53 +01:00
const recrankingisbn = await ImportaIsbn.findOne({ sku: recmacro.sku }).lean();
if (recrankingisbn) {
if (!recmacro.isbn) {
recmacro.isbn = recrankingisbn.isbn;
}
if ((!recmacro.Pagine || recmacro.Pagine === 0) && recrankingisbn.Pagine)
recmacro.Pagine = recrankingisbn.Pagine;
2024-12-02 19:37:53 +01:00
if (!recmacro.misure && recrankingisbn.misure) {
recmacro.misure = recrankingisbn.misure;
}
2024-04-29 14:58:45 +02:00
}
2024-12-02 19:37:53 +01:00
let queryprod = { idapp, _id: recmacro._id };
try {
let risrec = await Importamacro.findOneAndUpdate(queryprod, { $set: recmacro }, { new: true, upsert: true, strict: false });
if (risrec) {
imported++;
if (imported % 100 === 0)
2024-12-02 19:37:53 +01:00
console.log('Importati su dir Temporanea ', imported);
}
} catch (e) {
console.error(e);
errors++;
}
2024-04-29 14:58:45 +02:00
}
}
2024-12-02 19:37:53 +01:00
const cancella_categorie = false;
2024-04-29 14:58:45 +02:00
2024-12-02 19:37:53 +01:00
if (cancella_categorie) {
await CatProd.deleteMany({ idapp });
}
2024-05-04 14:49:02 +02:00
2024-12-02 19:37:53 +01:00
}
2024-04-29 14:58:45 +02:00
// Rileggi tutti i record di ImportaMacros
dataObjects = await Importamacro.find({ idapp }).lean();
2024-05-04 14:49:02 +02:00
console.log('*** INIZIO IMPORT PRODOTTI ... ');
let indprod = 0;
let newprod = 0;
let numprod = dataObjects.length;
2024-04-29 14:58:45 +02:00
for (const product of dataObjects) {
let isnuovo = false
let setta = false
2024-05-04 14:49:02 +02:00
let importa = true;
2024-12-02 19:37:53 +01:00
if (!product.title || !product.sku)
2024-05-04 14:49:02 +02:00
importa = false;
if (importa) {
let versGM = product.Versione ? product.Versione : '';
// split versioneGM in array with separated ","
let arrversGM = versGM.split(",").map(x => x.trim());
2024-05-04 14:49:02 +02:00
let productInfo = {
idapp: product.idapp,
code: product.isbn,
id_wp: product._id,
2024-12-02 19:37:53 +01:00
sku: product.sku,
2024-11-28 16:05:00 +01:00
2024-05-04 14:49:02 +02:00
name: product.title,
description: product.description,
short_descr: product.short_descr,
publisher: product.editore,
2024-05-04 14:49:02 +02:00
collezione: product.Collezione,
// author: product.Autore ? product.Autore : '',
link: product.link ? product.link : '',
idCatProds: [],
idSubCatProds: [],
//img: 'upload/products/' + product.code + '.jpg',
image_link: product.image_link ? product.image_link : '',
img2: product.img2 ? product.img2 : '',
img3: product.img3 ? product.img3 : '',
img4: product.img4 ? product.img4 : '',
checkout_link: product.checkout_link ? product.checkout_link : '',
2024-05-04 14:49:02 +02:00
}
2024-04-29 14:58:45 +02:00
let versione = 0;
2024-06-21 16:11:03 +02:00
if (indprod % 100 === 0)
2024-12-02 19:37:53 +01:00
console.log(indprod + '/' + numprod);
productInfo.productTypes = [];
// console.log('indprod', indprod, 'arrversGM', arrversGM, 'versione', product.Versione);
for (let i = 0; i < arrversGM.length; i++) {
// Download, DVD, Epub, Mobi, Nuovo, PDF, Streaming, Usato
if (arrversGM[i] === 'Nuovo')
2024-06-21 16:11:03 +02:00
vers = shared_consts.PRODUCTTYPE.NUOVO
else if (arrversGM[i] === 'Usato')
2024-06-21 16:11:03 +02:00
vers = shared_consts.PRODUCTTYPE.USATO;
else if (arrversGM[i] === 'Download')
2024-06-21 16:11:03 +02:00
vers = shared_consts.PRODUCTTYPE.DOWNLOAD;
else if (arrversGM[i] === 'DVD')
2024-06-21 16:11:03 +02:00
vers = shared_consts.PRODUCTTYPE.DVD;
else if (arrversGM[i] === 'Epub')
2024-06-21 16:11:03 +02:00
vers = shared_consts.PRODUCTTYPE.EPUB;
else if (arrversGM[i] === 'Mobi')
2024-06-21 16:11:03 +02:00
vers = shared_consts.PRODUCTTYPE.MOBI;
else if (arrversGM[i] === 'PDF')
2024-06-21 16:11:03 +02:00
vers = shared_consts.PRODUCTTYPE.PDF;
else if (arrversGM[i] === 'Streaming')
2024-06-21 16:11:03 +02:00
vers = shared_consts.PRODUCTTYPE.STREAMING;
if (i === 0) {
// salvati il primo, // nel 99,9% dei casi c'è solo 1 elemento (perchè queste sono tutte le variazioni)
versione = vers;
}
productInfo.productTypes.push(vers);
}
2024-04-29 14:58:45 +02:00
2024-12-02 19:37:53 +01:00
/*if (product.Data) {
productInfo.date_pub = new Date(product.Data * 1000);
2024-06-21 16:11:03 +02:00
// convert data to timestamp
productInfo.date_pub_ts = productInfo.date_pub.getTime();
2024-12-02 19:37:53 +01:00
}*/
2024-04-29 14:58:45 +02:00
2024-05-04 14:49:02 +02:00
productInfo.name = productInfo.name.replace(/ - Usato$| - Nuovo$| - Epub$| - Ebook$| - Mobi$| - DVD$| - Streaming$| - Download$/, "");
2024-04-29 14:58:45 +02:00
2024-05-04 14:49:02 +02:00
let reccateg = null;
2024-05-04 14:49:02 +02:00
if (product.categories) {
// Verifica prima se questa categoria è stata aggiornata !
const recrankingisbn = await ImportaIsbn.findOne({ sku: product.sku }).lean();
if (recrankingisbn && recrankingisbn.DescrArgomento) {
2024-04-29 14:58:45 +02:00
productInfo.idCatProds = []; // Azzera
2024-05-04 14:49:02 +02:00
if (tools.isArray(recrankingisbn.ListaArgomenti) && recrankingisbn.ListaArgomenti.length > 1) {
console.log('ListaArgomenti STA RITORNANDO UN ARRAY !!!! ', recrankingisbn.ListaArgomenti);
2024-05-04 14:49:02 +02:00
}
// !!!!
for (const idArgomento of recrankingisbn.ListaArgomenti) {
mycatstr = recrankingisbn.DescrArgomento;
if (mycatstr)
productInfo = await updateProductInfo(productInfo, product, idapp, mycatstr);
2024-05-04 14:49:02 +02:00
}
} else {
arrcat = product.categories.trim().split(',');
for (const mycat of arrcat) {
let mycatstr = mycat.trim();
// Controlla se ci sono le sottocategorie:
arrsubcat = mycatstr.trim().split('>');
if (arrsubcat.length > 1) {
// Ci sono delle sottocategorie
mycatstr = arrsubcat[0].trim();
product.subcat_name = arrsubcat[1].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();
console.log('CREA con ARGOMENTO VECCHIO... ', mycatstr);
reccateg = await CatProd.findOne({ idapp, name: mycatstr }).lean();
}
if (reccateg) {
productInfo.idCatProds.push(reccateg._id);
}
2024-05-04 14:49:02 +02:00
}
2024-04-29 14:58:45 +02:00
}
2024-05-04 14:49:02 +02:00
}
2024-04-29 14:58:45 +02:00
2024-05-04 14:49:02 +02:00
// "Autore" : "Silia,Marucelli, Stefano,Cattinelli",
let arrAuthor = [];
if (product.Autore) {
const arrrecauthor = product.Autore.trim().split(',');
if (arrrecauthor.length >= 1) {
try {
let author = {
name: arrrecauthor[0].trim(),
}
if (arrrecauthor.length === 1) {
author = extractNameAndSurnameByComplete(arrrecauthor[0].trim());
} else {
author.surname = arrrecauthor[1].trim();
}
arrAuthor.push(author);
if (arrrecauthor.length > 1) {
for (let i = 2; i < arrrecauthor.length; i = i + 2) {
try {
author = {
name: arrrecauthor[i].trim()
}
if (arrrecauthor.length > i + 1) {
author.surname = arrrecauthor[i + 1].trim()
2024-05-04 14:49:02 +02:00
}
arrAuthor.push(author);
} catch (e) {
}
}
}
productInfo.idAuthors = [];
for (const myauthor of arrAuthor) {
// Cerca l'Autore
recauthor = await Author.findOne({ idapp, name: myauthor.name, surname: myauthor.surname }).lean();
if (!recauthor) {
// Non esiste questo Autore, quindi lo creo !
recauthor = new Author({ idapp, name: myauthor.name, surname: myauthor.surname });
ris = await recauthor.save();
recauthor = await Author.findOne({ idapp, name: myauthor.name, surname: myauthor.surname }).lean();
}
if (recauthor) {
productInfo.idAuthors.push(recauthor._id);
}
}
} catch (e) {
console.error(e);
}
2024-04-29 14:58:45 +02:00
}
}
2024-05-04 14:49:02 +02:00
if (product.subcat_name) {
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) {
// 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();
}
2024-04-29 14:58:45 +02:00
2024-05-04 14:49:02 +02:00
if (recsubcateg) {
productInfo.idSubCatProds.push(recsubcateg._id);
}
}
}
2024-05-08 16:07:32 +02:00
if (productInfo.publisher) {
try {
publisher = productInfo.publisher.trim();
// Cerca la Sotto Categoria
let recpublisher = await Publisher.findOne({ idapp, name: publisher }).lean();
if (!recpublisher) {
// Non esiste questo Editore, quindi la creo !
recpublisher = new Publisher({ idapp, name: publisher });
ris = await recpublisher.save();
recpublisher = await Publisher.findOne({ idapp, name: publisher }).lean();
}
2024-05-08 16:07:32 +02:00
if (recpublisher) {
productInfo.idPublisher = recpublisher._id;
}
} catch (e) {
console.error(e);
2024-05-08 16:07:32 +02:00
}
}
2024-04-29 14:58:45 +02:00
2024-05-04 14:49:02 +02:00
if (!product.hasOwnProperty('active')) {
product.active = true;
}
2024-04-29 14:58:45 +02:00
2024-05-04 14:49:02 +02:00
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();
let { prodInfo, aggiornatoimg } = await downloadImgIfMissing(recnewInfo);
if (aggiornatoimg) {
await ProductInfo.findOneAndUpdate({ code: productInfo.code }, { $set: prodInfo });
}
2024-05-04 14:49:02 +02:00
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);
}
}
2024-04-29 14:58:45 +02:00
2024-05-04 14:49:02 +02:00
// Cerca il GAS
let recGas = null;
if (product.gas_name) {
// Cerca il GAS
recGas = await Gasordine.findOne({ idapp, name: product.gas_name }).lean();
}
2024-04-29 14:58:45 +02:00
2024-05-04 14:49:02 +02:00
if (!recGas && !!product.gas_name) {
recGas = new Gasordine({ idapp, name: product.gas_name, active: true });
// Non esiste questo GAS, quindi lo creo !
ris = await recGas.save();
recGas = await Gasordine.findOne({ idapp, name: product.gas_name }).lean();
2024-04-29 14:58:45 +02:00
}
2024-05-04 14:49:02 +02:00
let myproduct = {};
let recProductExist = null;
// ISBN e versione del prodotto sono le chiavi uniche
let queryprod = { idProductInfo: product.idProductInfo };
2024-05-04 14:49:02 +02:00
if (recGas) {
queryprod = { ...queryprod, idGasordine: recGas._id };
}
2024-04-29 14:58:45 +02:00
recProductExist = await Product.findOne(queryprod).lean();
2024-04-29 14:58:45 +02:00
2024-05-04 14:49:02 +02:00
if (!recProductExist) {
isnuovo = true;
}
2024-05-05 19:08:58 +02:00
let arrvariazioni = [];
if (isnuovo) {
myproduct.isbn = product.isbn;
myproduct.maxbookableGASQty = product.maxbookableGASQty ? product.maxbookableGASQty : null;
myproduct.active = product.active;
myproduct.idGasordine = recGas ? recGas._id : null;
myproduct.idProductInfo = product.idProductInfo;
myproduct.idapp = idapp;
} else {
arrvariazioni = recProductExist.arrvariazioni;
if (!arrvariazioni) {
arrvariazioni = [];
}
}
2024-04-29 14:58:45 +02:00
2024-05-05 19:08:58 +02:00
// cerca l'indice della versione in arrvariazioni
2024-06-21 16:11:03 +02:00
let ind = arrvariazioni.findIndex(x =>
x.versione === versione)
2024-05-05 19:08:58 +02:00
let nuovaVariazione = ind < 0;
//
let variazione = {};
2024-05-05 19:08:58 +02:00
if (!nuovaVariazione) {
// Mantieni intatte questi campi del RECORD su DB:
variazione.quantita = arrvariazioni[ind].quantita;
}
variazione.active = true; // ++ ??
2024-06-21 16:11:03 +02:00
variazione.versione = versione;
2024-11-19 19:18:54 +01:00
variazione.versione = versione;
variazione.status = product.Stato ? product.Stato : null;
variazione.price = product.price ? parseFloat(tools.convertPriceEurToValue(product.price)) : null;
variazione.sale_price = product.sale_price ? parseFloat(tools.convertPriceEurToValue(product.sale_price)) : null;
variazione.formato = product.formato ? product.formato : '';
variazione.tipologia = product.Tipologia ? product.Tipologia : '';
variazione.edizione = product.Edizione ? product.Edizione : '';
2024-12-02 19:37:53 +01:00
variazione.pagine = tools.isValidNumber(product.Pagine) ? tools.convstrToInt(product.Pagine) : 0;
2024-11-19 19:18:54 +01:00
variazione.misure = product.misure ? product.misure : '';
variazione.eta = product.eta ? product.eta : '';
variazione.addtocart_link = product.addtocart_link ? product.addtocart_link : '';
2024-05-08 16:07:32 +02:00
2024-05-05 19:08:58 +02:00
if (!options.aggiornaStockQty && !nuovaVariazione) {
// non aggiornare la Quantita in magazzino
} else if (product.Quantita) {
variazione.quantita = parseInt(product.Quantita);
2024-05-04 14:49:02 +02:00
}
variazione.preOrderDate = product.preOrderDate ? product.preOrderDate : null;
2024-04-29 14:58:45 +02:00
// -----------------------------
2024-04-29 14:58:45 +02:00
if (ind >= 0)
arrvariazioni[ind] = variazione; // aggiorna il record "ind" in arrvariazioni
else
arrvariazioni.push(variazione); // aggiunge un nuovo record in arrvariazioni
2024-04-29 14:58:45 +02:00
2024-05-05 19:08:58 +02:00
// Effettua l'ordinamento seguendo la "versione"
arrvariazioni.sort((a, b) => a.versione - b.versione);
// Inserisce o aggiorna il record variazione nell'array delle variazioni, in base a "versione"
if (isnuovo) {
myproduct.arrvariazioni = arrvariazioni;
2024-05-04 14:49:02 +02:00
}
2024-04-29 14:58:45 +02:00
2024-05-04 14:49:02 +02:00
let recold = await Product.findOne(queryprod).lean();
2024-04-29 14:58:45 +02:00
let risrec = null;
if (isnuovo) {
// CREA PRODUCT
risrec = await Product.findOneAndUpdate(queryprod, { $set: myproduct }, { new: true, upsert: true });
} else {
// Esiste già, pertanto ci aggiorno arrvariazioni
risrec = await Product.findOneAndUpdate(queryprod, { $set: { arrvariazioni } }, { new: true, upsert: true });
}
2024-04-29 14:58:45 +02:00
2024-05-04 14:49:02 +02:00
let recnew = await Product.findOne(queryprod).lean();
2024-04-29 14:58:45 +02:00
2024-05-04 14:49:02 +02:00
if (risrec) {
if (risrec._id) {
if (recold) {
// Record existed, so it was updated
let arrfieldchange = tools.differentObjects(recold, recnew);
if (arrfieldchange.length > 0) {
updated++;
let modif = '';
for (const field of arrfieldchange) {
2024-05-05 19:08:58 +02:00
if (field === 'arrvariazioni') {
modif += field + ': '
// Controlla quali campi sono variati tra recold.arrvariazioni e recnew.arrvariazioni
for (const variazione of recnew.arrvariazioni) {
// trova la versione in recold.arrvariazioni
let ind = recold.arrvariazioni.findIndex(x => x.versione === variazione.versione);
if (ind < 0) {
modif += 'Nuova Variazione [' + variazione.versione + '] ' + variazione.status + ' | Price: ' + variazione.price + ' -> Sale_Price: ' + variazione.sale_price + ' | ';
} else {
let oldvariazione = recold.arrvariazioni[ind];
if (oldvariazione.status !== variazione.status) {
modif += 'Variazione [' + oldvariazione.versione + '] ' + variazione.status + ' -> ' + variazione.status;
}
if (oldvariazione.price !== variazione.price) {
modif += ' | Price: ' + oldvariazione.price + ' -> ' + variazione.price;
}
if (oldvariazione.sale_price !== variazione.sale_price) {
modif += ' | Sale Price: ' + oldvariazione.sale_price + ' -> ' + variazione.sale_price;
}
if (oldvariazione.formato !== variazione.formato) {
modif += ' | Formato: ' + oldvariazione.formato + ' -> ' + variazione.formato;
}
if (oldvariazione.tipologia !== variazione.tipologia) {
modif += ' | Tipologia: ' + oldvariazione.tipologia + ' -> ' + variazione.tipologia;
}
if (oldvariazione.edizione !== variazione.edizione) {
modif += ' | Edizione: ' + oldvariazione.edizione + ' -> ' + variazione.edizione;
}
if (oldvariazione.eta !== variazione.eta) {
modif += ' | Età: ' + oldvariazione.eta + ' -> ' + variazione.eta;
}
if (oldvariazione.preOrderDate !== variazione.preOrderDate) {
modif += ' | PreOrderDate: ' + oldvariazione.preOrderDate + ' -> ' + variazione.preOrderDate;
}
if (oldvariazione.addtocart_link !== variazione.addtocart_link) {
modif += ' | AddToCart: ' + oldvariazione.addtocart_link + ' -> ' + variazione.addtocart_link;
}
}
}
} else {
modif += field + ': ' + recold[field] + ' -> ' + recnew[field] + ' | ';
}
2024-05-04 14:49:02 +02:00
}
console.log('Changed: [' + indprod + '/' + dataObjects.length + ']', productInfo.name, '[' + myproduct.idProductInfo + '] : ' + modif);
}
} else {
newprod++;
console.log('Nuovo Prodotto : [' + newprod + '/' + dataObjects.length + ']', productInfo.name);
}
} else {
// Record didn't exist, so it was created
imported++;
2024-04-29 14:58:45 +02:00
}
} else {
2024-05-04 14:49:02 +02:00
// risrec is null or undefined, indicating an error
console.error('Error: ', myproduct.productInfo.name);
errors++;
2024-04-29 14:58:45 +02:00
}
2024-05-04 14:49:02 +02:00
await Product.singlerecconvert_AfterImport_AndSave(idapp, recnew, isnuovo);
2024-04-29 14:58:45 +02:00
} else {
2024-05-04 14:49:02 +02:00
console.error('Error ProductInfo: ', product.code);
2024-04-29 14:58:45 +02:00
errors++;
}
}
2024-05-04 14:49:02 +02:00
indprod++;
2024-04-29 14:58:45 +02:00
}
2024-05-04 14:49:02 +02:00
console.log('*** IMPORTATI: ', imported, '*** NUOVI: ', newprod, 'AGGIORNATI = ' + updated + ' (su ' + dataObjects.length + ' RECORD)');
2024-04-29 14:58:45 +02:00
return res.status(200).send({ updated, imported, errors });
2023-12-14 15:20:21 +01:00
} else if (cmd === shared_consts.Cmd.PRODUCTS) {
dataObjects = JSON.parse(`[${data.arrdata}]`);
2023-12-14 15:20:21 +01:00
2023-12-18 12:11:12 +01:00
let updated = 0;
let imported = 0;
let errors = 0;
for (const product of dataObjects) {
2023-12-27 02:58:15 +01:00
let isnuovo = false
let setta = false
2023-12-29 15:19:15 +01:00
2023-12-27 02:58:15 +01:00
let productInfo = {
idapp: product.idapp,
code: product.code,
name: product.name,
link: product.link,
idCatProds: [],
2024-01-12 13:02:59 +01:00
idSubCatProds: [],
2024-10-22 15:26:29 +02:00
// img: 'upload/products/' + product.code + '.jpg',
imagefile: product.code + '.jpg',
weight: product.weight,
unit: tools.getIdUnitsByText(product.unit),
productTypes: shared_consts.PRODUCTTYPE.PRODUCT,
2023-12-27 02:58:15 +01:00
}
2024-01-16 09:05:02 +01:00
let reccateg = null;
2023-12-27 02:58:15 +01:00
if (product.cat_name) {
2023-12-29 15:19:15 +01:00
arrcat = product.cat_name.trim().split(',');
for (const mycat of arrcat) {
let mycatstr = mycat.trim();
2024-02-06 20:12:54 +01:00
2023-12-29 15:19:15 +01:00
// Cerca la Categoria
2024-01-16 09:05:02 +01:00
reccateg = await CatProd.findOne({ idapp, name: mycatstr }).lean();
2023-12-29 15:19:15 +01:00
if (!reccateg) {
// Non esiste questo produttore, quindi lo creo !
reccateg = new CatProd({ idapp, name: mycatstr });
2023-12-29 15:19:15 +01:00
ris = await reccateg.save();
reccateg = await CatProd.findOne({ idapp, name: mycatstr }).lean();
2023-12-29 15:19:15 +01:00
}
if (reccateg) {
productInfo.idCatProds.push(reccateg._id);
}
2023-12-27 02:58:15 +01:00
}
}
2023-12-29 15:19:15 +01:00
2024-01-12 13:02:59 +01:00
if (product.subcat_name) {
arrsubcat = product.subcat_name.trim().split(',');
for (const mysubcat of arrsubcat) {
let mysubcatstr = mysubcat.trim();
2024-02-06 20:12:54 +01:00
2024-01-12 13:02:59 +01:00
// 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 : ''
2024-01-16 09:05:02 +01:00
recsubcateg = new SubCatProd({ idapp, name: mysubcatstr, idCatProd });
2024-01-12 13:02:59 +01:00
ris = await recsubcateg.save();
recsubcateg = await SubCatProd.findOne({ idapp, name: mysubcatstr, idCatProd }).lean();
}
if (recsubcateg) {
productInfo.idSubCatProds.push(recsubcateg._id);
}
}
}
2023-12-18 12:11:12 +01:00
if (!product.hasOwnProperty('active')) {
product.active = true;
}
2023-12-29 15:19:15 +01:00
if (product.code)
delete product.code;
if (product.name)
delete product.name;
if (product.link)
delete product.link;
let esisteindb = await ProductInfo.findOne({ code: productInfo.code }).lean();
2023-12-27 02:58:15 +01:00
// Update ProductInfo
let risrecInfo = await ProductInfo.findOneAndUpdate({ code: productInfo.code }, { $set: productInfo }, { new: true, upsert: true });
if (risrecInfo) {
product.idProductInfo = risrecInfo._id;
2023-12-18 12:11:12 +01:00
2023-12-27 02:58:15 +01:00
recnewInfo = await ProductInfo.findOne({ code: productInfo.code }).lean();
if (risrecInfo._id) {
2023-12-18 12:11:12 +01:00
// Record existed, so it was updated
2023-12-27 02:58:15 +01:00
let arrfieldchange = tools.differentObjects(productInfo, recnewInfo);
2023-12-28 23:48:03 +01:00
if (arrfieldchange && arrfieldchange.length > 0) {
2023-12-27 02:58:15 +01:00
// updated++;
console.log('Changed: ', recnewInfo.name + ': ' + arrfieldchange);
}
}
2023-12-29 15:19:15 +01:00
2024-01-16 16:56:39 +01:00
// Cerca il GAS
let recGas = null;
2024-01-16 17:09:55 +01:00
if (product.gas_name) {
2024-01-16 16:56:39 +01:00
// Cerca il GAS
2024-01-16 17:09:55 +01:00
recGas = await Gasordine.findOne({ idapp, name: product.gas_name }).lean();
2024-01-16 16:56:39 +01:00
}
if (!recGas && !!product.gas_name) {
2024-01-16 17:09:55 +01:00
recGas = new Gasordine({ idapp, name: product.gas_name, active: true });
// Non esiste questo GAS, quindi lo creo !
ris = await recGas.save();
recGas = await Gasordine.findOne({ idapp, name: product.gas_name }).lean();
}
2024-02-06 20:12:54 +01:00
2024-01-16 16:56:39 +01:00
let recProductExist = null;
let queryprod = { idProductInfo: product.idProductInfo };
2024-02-06 20:12:54 +01:00
2024-01-16 16:56:39 +01:00
if (recGas) {
2024-02-06 20:12:54 +01:00
queryprod = { ...queryprod, idGasordine: recGas._id };
2024-01-16 16:56:39 +01:00
}
recProductExist = await Product.findOne(queryprod).lean();
2024-02-06 20:12:54 +01:00
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++;
2024-05-04 14:49:02 +02:00
console.log('Changed:', product.idProductInfo + ': ' + arrfieldchange);
2024-02-06 20:12:54 +01:00
}
} 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++;
}
}
return res.status(200).send({ updated, imported, errors });
2024-02-06 20:12:54 +01:00
} else if (cmd === shared_consts.Cmd.PRODUCTS_V2) {
let mydata = `[${data.arrdata}]`;
dataObjects = mydata.replace(/\n/g, '');
let arrrec = [];
try {
arrrec = JSON.parse(dataObjects);
} catch (e) {
console.error("Errore durante l'analisi del JSON:", e);
arrrec = [];
}
2024-02-06 20:12:54 +01:00
let updated = 0;
let imported = 0;
let errors = 0;
let ind = 0
const [, ...myarrshift] = arrrec;
for (const rec of myarrshift) {
2024-03-08 18:57:13 +01:00
let risprod = await extractArrayDataFromCSV(idapp, rec);
2024-02-06 20:12:54 +01:00
let product = risprod.product;
let productInfo = risprod.productInfo;
2024-05-04 14:49:02 +02:00
2024-02-06 20:12:54 +01:00
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);
}
}
}
2024-02-06 20:12:54 +01:00
if (!rec.hasOwnProperty('active')) {
product.active = true;
}
if (productInfo.productTypes.length === 1 && productInfo.productTypes[0] === undefined) {
productInfo.productTypes = [shared_consts.PRODUCTTYPE.PRODUCT];
}
2024-10-26 17:11:52 +02:00
2024-02-06 20:12:54 +01:00
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();
}
if (recGas) {
if (rec.hasOwnProperty('note_ordine_gas')) {
const note_ordine_gas = rec['note_ordine_gas'];
await Gasordine.findOneAndUpdate({ _id: recGas._id }, { $set: { note_ordine_gas } });
}
}
2024-02-06 20:12:54 +01:00
let recProductExist = null;
let queryprod = { idProductInfo: product.idProductInfo };
if (recGas) {
queryprod = { ...queryprod, idGasordine: recGas._id };
}
recProductExist = await Product.findOne(queryprod).lean();
2024-02-06 20:12:54 +01:00
2023-12-27 02:58:15 +01:00
if (!recProductExist) {
isnuovo = true;
}
2023-12-29 15:19:15 +01:00
2024-01-16 17:09:55 +01:00
if (!options.aggiornaStockQty && esisteindb && !isnuovo) {
2023-12-29 15:19:15 +01:00
delete product.stockQty;
delete product.maxbookableGASQty;
2023-12-29 15:19:15 +01:00
}
// AGGIORNA PRODUCT
2024-01-16 17:09:55 +01:00
let risrec = await Product.findOneAndUpdate(queryprod, { $set: product }, { new: true, upsert: true });
2023-12-27 02:58:15 +01:00
2024-01-16 17:09:55 +01:00
let recnew = await Product.findOne(queryprod).lean();
2023-12-27 02:58:15 +01:00
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++;
2023-12-18 12:11:12 +01:00
}
} else {
2023-12-27 02:58:15 +01:00
// risrec is null or undefined, indicating an error
console.error('Error: ', product.productInfo.name);
errors++;
2023-12-18 12:11:12 +01:00
}
2023-12-27 02:58:15 +01:00
await Product.singlerecconvert_AfterImport_AndSave(idapp, recnew, isnuovo);
2023-12-18 12:11:12 +01:00
} else {
2023-12-27 02:58:15 +01:00
console.error('Error ProductInfo: ', product.code);
2023-12-18 12:11:12 +01:00
errors++;
}
2024-02-06 20:12:54 +01:00
ind++;
2023-12-18 12:11:12 +01:00
}
// L'opzione ordered: false gestisce gli errori senza interrompere l'inserimento
2023-12-18 12:11:12 +01:00
/*return await Product.insertMany(dataObjects, { ordered: false })
.then((ris) => {
2024-05-04 14:49:02 +02:00
Product.convertAfterImportALLPROD(idapp, dataObjects).then((ris) => {
return res.status(200).send(true);
});
2024-05-04 14:49:02 +02:00
})
.catch((errors) => {
console.error(errors);
Product.convertAfterImportALLPROD(idapp).then((ris) => {
return res.status(200).send(true);
});
2023-12-18 12:11:12 +01:00
});*/
return res.status(200).send({ updated, imported, errors });
2023-12-14 15:20:21 +01:00
}
2023-12-14 15:20:21 +01:00
} catch (e) {
console.error('e', e);
2024-04-29 14:58:45 +02:00
return res.status(400).send();
}
2024-04-29 14:58:45 +02:00
return res.status(400).send();
});
router.post('/exec', authenticate, async (req, res) => {
try {
idapp = req.body.idapp;
console.log('/exec idapp=', idapp, req.body.script);
script = req.body.mydata.script;
listafiles = req.body.mydata.listafiles;
tokcheck = req.body.mydata.tokcheck;
extfiles = req.body.mydata.extfiles;
dir = req.body.mydata.dir;
withinput = req.body.mydata.withinput;
const TOKCHECK = 'php8.1_version_762321HSD121nJDokq@?!aFS.tar.gz'
if (!User.isAdmin(req.user.perm) || (tokcheck !== TOKCHECK)) {
// If without permissions, exit
return res.status(404).send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' });
}
let result = '';
if (withinput)
result = await tools.execScriptWithInputOnServer(idapp, script);
else
result = await tools.execScriptOnServer(idapp, script, dir, listafiles, extfiles);
return res.send(result);
} catch (e) {
console.error('e', e);
return res.status(400).send({ code: server_constants.RIS_CODE_ERR, msg: '' });
}
});
router.post('/cloudflare', authenticate, async (req, res) => {
try {
idapp = req.body.idapp;
cmd = req.body.cmd;
tok = req.body.tok;
zoneId = req.body.zoneId;
tokcheck = req.body.tokcheck;
dnsRecordId = req.body.dnsRecordId;
record = req.body.record;
// console.log('/cloudflare idapp=', idapp, req.body.script);
const CloudFlareClass = require('../modules/Cloudflare.js');
const TOKCHECK = 'php8.1_version_762321HSD121nJDokq@?!aFS.tar.gz'
if (!User.isAdmin(req.user.perm) || (tokcheck !== TOKCHECK)) {
// If without permissions, exit
return res.status(404).send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' });
}
let result = '';
let cf = new CloudFlareClass(null);
cf.init();
if (cmd === "getzones") {
result = await cf.fetchCloudflareZones(tok);
} else if (cmd === "getDNS") {
result = await cf.fetchDNSRecords(tok, zoneId);
} else if (cmd === "setRecordDNS") {
result = await cf.updateDNSRecord(tok, zoneId, dnsRecordId, record);
} else if (cmd === "delRecordDNS") {
result = await cf.deleteDNSRecord(tok, zoneId, dnsRecordId);
} else if (cmd === "setCorrectIpsOnDNS") {
result = await cf.setCorrectIpsOnDNS(record);
} else if (cmd === "gettok") {
result = process.env.CLOUDFLARE_TOKENS ? JSON.parse(process.env.CLOUDFLARE_TOKENS) : '';
}
return res.send(result);
} catch (e) {
console.error('e', e);
return res.status(400).send({ code: server_constants.RIS_CODE_ERR, msg: '' });
}
});
router.post('/miab', authenticate, async (req, res) => {
try {
idapp = req.body.idapp;
cmd = req.body.cmd;
record = req.body.record;
tokcheck = req.body.tokcheck;
const MailinaboxClass = require('../modules/Mailinabox.js');
const TOKCHECK = 'php8.1_version_762321HSD121nJDokq@?!aFS.tar.gz'
if (!User.isAdmin(req.user.perm) || (tokcheck !== TOKCHECK)) {
// If without permissions, exit
return res.status(404).send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' });
}
let result = '';
let miab = new MailinaboxClass(null);
miab.init();
if (cmd === "getEmails") {
result = await miab.MIAB_getEmails(record);
} else if (cmd === "removeEmails") {
result = await miab.removeEmail(record);
} else if (cmd === "addEmail") {
result = await miab.addEmail(record);
} else if (cmd === "setMailUserPassword") {
result = await miab.setMailUserPassword(record);
}
return res.send(result);
} catch (e) {
console.error('e', e);
return res.status(400).send({ code: server_constants.RIS_CODE_ERR, msg: '' });
}
});
module.exports = router;