diff --git a/src/server/models/myelem.js b/src/server/models/myelem.js index 78f5833..6cf616f 100755 --- a/src/server/models/myelem.js +++ b/src/server/models/myelem.js @@ -19,6 +19,7 @@ mongoose.plugin(schema => { const IElementiPagina = new Schema({ isTemplate: Boolean, linkIdTemplate: String, + linkIdTemplatePerStampa: String, name: String, pagina: IDimensioni, }); @@ -83,6 +84,7 @@ const catalogo = new Schema( print_isTemplate: Boolean, print_linkIdTemplate: String, + print_linkIdTemplatePerStampa: String, dimensioni_def: IElementiPagina, diff --git a/src/server/models/myscheda.js b/src/server/models/myscheda.js index fa73cab..95ef914 100755 --- a/src/server/models/myscheda.js +++ b/src/server/models/myscheda.js @@ -116,6 +116,7 @@ const scheletroScheda = { isTemplate: { type: Boolean }, isPagIntro: { type: Boolean }, linkIdTemplate: { type: String }, + linkIdTemplatePerStampa: { type: String }, name: { type: String }, numschede_perRiga: { type: Number }, numschede_perCol: { type: Number }, diff --git a/src/server/router/admin_router.js b/src/server/router/admin_router.js index 266a1bc..7265b96 100755 --- a/src/server/router/admin_router.js +++ b/src/server/router/admin_router.js @@ -136,18 +136,7 @@ function updateProductInfoCatProds(productInfo, reccatprod) { } } } -async function compressPdf(inputFile, outputFile, compressione) { - try { - const tempFolder = path.join(cwd, 'temp'); - const hasTempFolder = await tools.isFileExistsAsync(tempFolder); - - if (!hasTempFolder) { - console.log('creo directory', tempFolder); - await fs.mkdir(tempFolder); // Usa la versione promessa di mkdir - console.log('✅ directory creata', tempFolder); - } - - /* +/* 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: @@ -159,14 +148,49 @@ async function compressPdf(inputFile, outputFile, compressione) { /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}"`; +async function compressPdf(inputFile, outputFile, compressione) { + try { + const tempFolder = path.join(cwd, 'temp'); + const hasTempFolder = await tools.isFileExistsAsync(tempFolder); + if (!hasTempFolder) { + console.log('creo directory', tempFolder); + await fs.mkdir(tempFolder); // Usa la versione promessa di mkdir + console.log('✅ directory creata', tempFolder); + } + + // Valori ammessi per -dPDFSETTINGS di Ghostscript + const validSettings = ['screen', 'ebook', 'printer', 'prepress', 'default']; + if (!validSettings.includes(compressione)) { + console.warn(`Compressione '${compressione}' non valida, uso 'ebook'`); + compression = 'ebook'; + } + + // Costruisci comando Ghostscript per la compressione PDF + const gsCommand = [ + 'gs', + '-sDEVICE=pdfwrite', + '-dCompatibilityLevel=1.4', + `-dPDFSETTINGS=/${compressione}`, + '-dNOPAUSE', + '-dQUIET', + '-dBATCH', + `-sOutputFile="${outputFile}"`, + `"${inputFile}"`, + ].join(' '); + + console.log('Compressione del PDF in corso...'); console.log('gsCommand', gsCommand); // Esegui il comando per la compressione await execPromise(gsCommand); + // Calcola la percentuale di compressione + const origSize = (await fs.promises.stat(inputFile)).size; + const newSize = (await fs.promises.stat(outputFile)).size; + const percent = Math.round(((origSize - newSize) / origSize) * 100); + console.log(`Il file compresso è circa il ${percent}% più piccolo dell'originale`); + console.log(`PDF compresso e salvato come '${outputFile}'`); } catch (error) { console.error('Errore durante la compressione:', error); @@ -176,7 +200,7 @@ async function compressPdf(inputFile, outputFile, compressione) { async function convertPDF_GS(inputFile, outputFile, width, height) { // Verifica che il file di input esista - if (!await tools.isFileExistsAsync(inputFile)) { + if (!(await tools.isFileExistsAsync(inputFile))) { throw new Error(`Il file di input non esiste: ${inputFile}`); } @@ -256,102 +280,16 @@ async function extractPdfInfo(inputFile) { } async function convertPDF_PdfLib(idapp, inputFile, outputFile, options) { - if (!await tools.isFileExistsAsync(inputFile)) { + if (!(await tools.isFileExistsAsync(inputFile))) { throw new Error(`Il file di input non esiste: ${inputFile}`); } console.log('START convertPDF_PdfLib...'); 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 = options.width * 72; // Convertito in punti - const newHeight = options.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, - }); - } - - let addstr = ''; - - if (options.compressione) { - addstr = '_temp.pdf'; - } - - // Salva il nuovo PDF - const pdfBytes = await newPdfDoc.save(); - fs.writeFileSync(outputFile + addstr, pdfBytes); - console.log(`PDF convertito e salvato come '${outputFile}'`); - - const comprimi = false; - const mostrainfo = true; - - let fileout = outputFile; - - if (options.compressione) { - const todayDate = tools.getDateYYYYMMDD_Today(); - //const compressed = tools.removeFileExtension(outputFile) + `_${todayDate}.pdf`; - const compressed = tools.removeFileExtension(outputFile) + `_generato.pdf`; - - await compressPdf(outputFile + addstr, compressed, options.compressione); - - if (mostrainfo) extractPdfInfo(compressed); - - fileout = compressed; - } - - if (options.dir_out && options.idapp) { - // Crea directory se non esiste ! - // Salva il fileout anche su questa directory dir_out - //const fileoutdir = path.join(options.dir_out, options.file_out); - //await fs.promises.copyFile(fileout, fileoutdir); - //console.log(`File ${fileout} anche salvato in ${options.dir_out}`); - } - - let fileout_print = ''; - - // Crea anche il PDF per la stampa - if ( - options.print_left !== 0 || - options.print_top !== 0 || - options.print_right !== 0 || - options.print_bottom !== 0 - ) { - options.filenameIn = fileout; - ris = await ConvertPDF_WithMargins(options); - } - - const uscita = { - pdf_generato: tools.removePathDirByFileName(options.idapp, fileout), - pdf_generato_stampa: tools.removePathDirByFileName(options.idapp, ris.fileout_print), - }; + options.filenameIn = inputFile; + options.filenameOut = outputFile; + const uscita = await ConvertPDF_Generatore(options, options.stampa); return uscita; } catch (e) { @@ -359,20 +297,56 @@ async function convertPDF_PdfLib(idapp, inputFile, outputFile, options) { return ''; } } -async function ConvertPDF_WithMargins(options) { - let fileout_print = ''; - const marginTop = parseFloat(options.print_top) || 0; - const marginRight = parseFloat(options.print_right) || 0; - const marginBottom = parseFloat(options.print_bottom) || 0; - const marginLeft = parseFloat(options.print_left) || 0; +async function leggiDimensioniPdf(filePath) { + const pdfBytes = await fs.promises.readFile(filePath); + const pdfDoc = await PDFDocument.load(pdfBytes); + + const pages = pdfDoc.getPages(); + const primaPagina = pages[0]; + + const { width, height } = primaPagina.getSize(); + + console.log( + `Dimensioni prima pagina: larghezza = ${tools.arrotondaA2Decimali( + (width / 72) * 25.4 + )} mm, altezza = ${tools.arrotondaA2Decimali((height / 72) * 25.4)} mm` + ); + + return { width, height }; +} + +async function ConvertPDF_Generatore(options, instampa) { + let fileout = ''; + let fileout_compressed = ''; + let suffisso_filename = ''; if (!options.filenameIn) { - return { err: 'Nessun file caricato.' }; + return { err: 'Nessun file passato in Ingresso.' }; } - const outputFilename = path.basename(tools.removeFileExtension(options.filenameIn)) + '-stampabile.pdf'; - const outputPath = path.join(options.dir_out, outputFilename); + let marginTop = instampa ? parseFloat(options.print_top) : 0; + let marginRight = instampa ? parseFloat(options.print_right) : 0; + let marginBottom = instampa ? parseFloat(options.print_bottom) : 0; + let marginLeft = instampa ? parseFloat(options.print_left) : 0; + + if (instampa) { + suffisso_filename = '-stampabile'; + } + + + let outputFilename = suffisso_filename + ? tools.aggiungiSuffissoAlNomeFile(options.filenameOut, suffisso_filename) + : options.filenameOut; + + // controlla se outputFilename non ha directory allora gliela aggiungo + if (!path.dirname(outputFilename)) { + outputFilename = path.join(options.dir_out, outputFilename); + } + + const outputFullPathFileName = outputFilename; + + await leggiDimensioniPdf(options.filenameIn); try { // Leggi il PDF originale @@ -384,8 +358,12 @@ async function ConvertPDF_WithMargins(options) { for (let i = 0; i < pages.length; i++) { const page = pages[i]; + // punti PDF (pt), dove 1 punto = 1/72 di pollice. const { width, height } = page.getSize(); + // CONVERTIli in mm e stampa su console + console.log(`Dimensione pagina ${i + 1}: ${(width / 72) * 25.4} mm x ${(height / 72) * 25.4} mm`); + const newWidth = width - marginLeft - marginRight; const newHeight = height - marginTop - marginBottom; @@ -408,18 +386,40 @@ async function ConvertPDF_WithMargins(options) { // Salva il nuovo PDF const pdfBytes = await destPdfDoc.save(); - await fs.promises.mkdir(options.dir_out, { recursive: true }); + const dirUscita = path.dirname(outputFullPathFileName); + if (!(await tools.isDirectoryAsync(dirUscita))) { + await fs.promises.mkdir(dirUscita, { recursive: true }); + } - await fs.promises.writeFile(outputPath, pdfBytes); + await fs.promises.writeFile(outputFullPathFileName, pdfBytes); - fileout_print = outputPath; + fileout = outputFullPathFileName; + extractPdfInfo(fileout); + + if (options.compressione) { + const mostrainfo = true; + // const todayDate = tools.getDateYYYYMMDD_Today(); + //const compressed = tools.removeFileExtension(outputFile) + `_${todayDate}.pdf`; + fileout_compressed = tools.removeFileExtension(fileout) + `_compressed.pdf`; + + await compressPdf(fileout, fileout_compressed, options.compressione); + + // if (mostrainfo) extractPdfInfo(fileout_compressed); + } } catch (error) { - const log = 'Errore durante la creazione del PDF per la Stampa:' + error.message; + const log = `Errore durante la creazione del PDF: (instampa = ${instampa}): ` + error.message; console.error(log); - return { err: log, fileout_print: '' }; + return { + err: log, + fileout: tools.removePathDirByFileName(options.idapp, fileout), + fileout_compressed: tools.removePathDirByFileName(options.idapp, fileout_compressed), + }; } - return { fileout_print }; + return { + fileout: tools.removePathDirByFileName(options.idapp, fileout), + fileout_compressed: tools.removePathDirByFileName(options.idapp, fileout_compressed), + }; } router.post('/online-pdf', authenticate, async (req, res) => { @@ -605,76 +605,76 @@ router.post('/convert-pdf', upload.single('pdf'), async (req, res) => { print_right = '0', print_bottom = '0', print_left = '0', + stampa, + salvasufiledascaricare = 'false', } = req.body; + + if (!width) { + await fs.promises.unlink(inputFile); + return res.status(400).send('Width parameter is required'); + } + const options = { width, height, compressione, - dir_out, + dir_out: tools.getdirByIdApp(idapp) + '/' + dir_out, file_out, idapp, print_top, print_right, print_bottom, print_left, + stampa: stampa === '1', }; - if (!width) { - fs.unlinkSync(inputFile); - return res.status(400).send('Width parameter is required'); + let invia_file_convertito = false; + if (!options.file_out || options.file_out === '') { + options.file_out = `${tools.removeFileExtension(req.file.originalname)}-converted.pdf`; + invia_file_convertito = true; } - - options.dir_out = tools.getdirByIdApp(options.idapp) + '/' + options.dir_out; - // let outputFile = path.join(options.dir_out, `${tools.removeFileExtension(req.file.originalname)}-converted.pdf`); - let outputFile = path.join(options.dir_out, `${options.file_out}`); + let outputFile = path.join(options.dir_out, options.file_out); try { await fs.promises.mkdir(DIR_PDF_IN, { recursive: true }); await fs.promises.mkdir(options.dir_out, { recursive: true }); // Converti il PDF - // await convertPDF_GS(inputFile, outputFile, width, height); const risout = await convertPDF_PdfLib(idapp, inputFile, outputFile, options); - if (!options.dir_out) { - // Invia il file convertito - res.download(risout.pdf_generato, 'output-converted.pdf', (err) => { + if (salvasufiledascaricare === 'true') { + // Invia il file come download + return res.download(outputFile, options.file_out, async (err) => { + await cleanupFiles(inputFile, outputFile); if (err) { - if (err.code === 'ECONNABORTED' || err.code === 'ECONNRESET') { - console.warn('Richiesta annullata dal client:', err.message); - return; - } console.error("Errore durante l'invio del file:", err.message || err); if (!res.headersSent) { res.status(500).send("Errore durante l'invio del file convertito"); } - } else { - // Rimuovi i file temporanei - cleanupFiles(inputFile, ''); } }); } else { - cleanupFiles(inputFile, ''); + // Non inviare file, solo risposta JSON + await cleanupFiles(inputFile, ''); // pulisci solo inputFile + return res.status(200).send(risout); } - - return res.status(200).send(risout); } catch (error) { console.error('Errore durante la conversione:', error); - cleanupFiles(inputFile, ''); + await cleanupFiles(inputFile, ''); if (!res.headersSent) { - res.status(500).send(`Errore durante la conversione del PDF: ${error.message}`); + return res.status(500).send(`Errore durante la conversione del PDF: ${error.message}`); } } }); -function cleanupFiles(inputFile, outputFile) { +async function cleanupFiles(inputFile, outputFile) { if (inputFile) { - tools.deleteFile(inputFile).catch((err) => { + await tools.deleteFile(inputFile).catch((err) => { console.error('Errore durante la rimozione del file di INPUT:', err); }); } if (outputFile) { - tools.deleteFile(outputFile).catch((err) => { + await tools.deleteFile(outputFile).catch((err) => { console.error('Errore durante la rimozione del file di output:', err); }); } diff --git a/src/server/router/index_router.js b/src/server/router/index_router.js index 922b759..69851a9 100755 --- a/src/server/router/index_router.js +++ b/src/server/router/index_router.js @@ -9,8 +9,12 @@ const i18n = require('i18n'); const sharp = require('sharp'); -const { authenticate, authenticate_noerror, authenticate_noerror_WithUser, authenticate_noerror_WithUserLean } = require( - '../middleware/authenticate'); +const { + authenticate, + authenticate_noerror, + authenticate_noerror_WithUser, + authenticate_noerror_WithUserLean, +} = require('../middleware/authenticate'); const { ObjectId } = require('mongodb'); @@ -117,7 +121,8 @@ const UserCost = { 'profile.advcash_id', 'profile.link_payment', 'profile.email_paypal', - 'profile.paymenttypes'], + 'profile.paymenttypes', + ], }; router.post(process.env.LINKVERIF_REG, (req, res) => { @@ -127,40 +132,38 @@ router.post(process.env.LINKVERIF_REG, (req, res) => { // Cerco l'idlink se è ancora da Verificare - User.findByLinkreg(idapp, idlink).then((user) => { - if (!user) { - //console.log("NON TROVATO!"); - return res.status(404).send(); - } else { - console.log('user', user); - if (user.verified_email) { - res.send({ - code: server_constants.RIS_CODE_EMAIL_ALREADY_VERIFIED, - msg: tools.getres__('L\'Email è già stata Verificata', res), - }); + User.findByLinkreg(idapp, idlink) + .then((user) => { + if (!user) { + //console.log("NON TROVATO!"); + return res.status(404).send(); } else { - user.verified_email = true; - user.lasttimeonline = new Date(); - user.save().then(() => { - //console.log("TROVATOOOOOO!"); + console.log('user', user); + if (user.verified_email) { res.send({ - code: server_constants.RIS_CODE_EMAIL_VERIFIED, - msg: tools.getres__('EMAIL', res) + ' ' + - tools.getres__('VERIF', res), + code: server_constants.RIS_CODE_EMAIL_ALREADY_VERIFIED, + msg: tools.getres__("L'Email è già stata Verificata", res), }); - }); + } else { + user.verified_email = true; + user.lasttimeonline = new Date(); + user.save().then(() => { + //console.log("TROVATOOOOOO!"); + res.send({ + code: server_constants.RIS_CODE_EMAIL_VERIFIED, + msg: tools.getres__('EMAIL', res) + ' ' + tools.getres__('VERIF', res), + }); + }); + } } - } - }).catch((e) => { - console.log(process.env.LINKVERIF_REG, e.message); - res.status(400).send(); - }); - + }) + .catch((e) => { + console.log(process.env.LINKVERIF_REG, e.message); + res.status(400).send(); + }); }); - router.post(process.env.ADD_NEW_SITE, async (req, res) => { - try { const body = req.body; const idapp = body.idappSent; @@ -176,18 +179,14 @@ router.post(process.env.ADD_NEW_SITE, async (req, res) => { } else { res.status(400).send({ code: server_constants.RIS_CODE_ERR, msg: 'Errore' }); } - } catch (e) { console.log(process.env.ADD_NEW_SITE, e.message); res.status(400).send({ code: server_constants.RIS_CODE_ERR, msg: e }); } - }); - // Faccio richiesta di una Nuova Password router.post(process.env.LINK_REQUEST_NEWPASSWORD, async (req, res) => { - try { const body = _.pick(req.body, ['idapp', 'email', 'codetocheck']); const idapp = body.idapp; @@ -205,28 +204,23 @@ router.post(process.env.LINK_REQUEST_NEWPASSWORD, async (req, res) => { return false; } - console.log( - 'POST ' + process.env.LINK_REQUEST_NEWPASSWORD + ' idapp= ' + idapp + - ' email = ' + email); + console.log('POST ' + process.env.LINK_REQUEST_NEWPASSWORD + ' idapp= ' + idapp + ' email = ' + email); const reqpwd = await User.createNewRequestPwd(idapp, email, codetocheck); if (reqpwd && reqpwd.ris) { res.send({ code: server_constants.RIS_CODE_OK, msg: '', link: reqpwd.link }); } else { - return res.status(200). - send({ code: server_constants.RIS_CODE_EMAIL_NOT_EXIST, msg: '' }); + return res.status(200).send({ code: server_constants.RIS_CODE_EMAIL_NOT_EXIST, msg: '' }); } } catch (e) { console.log(process.env.LINK_REQUEST_NEWPASSWORD, e.message); res.status(400).send({ code: server_constants.RIS_CODE_ERR, msg: e }); } - }); // Invio la Nuova Password richiesta dal reset! // Ritorna il token per poter effettuare le chiamate... router.post(process.env.LINK_UPDATE_PWD, async (req, res) => { - try { const body = _.pick(req.body, ['idapp', 'email', 'tokenforgot', 'tokenforgot_code', 'password']); const idapp = body.idapp; @@ -245,7 +239,8 @@ router.post(process.env.LINK_UPDATE_PWD, async (req, res) => { user = await User.findByLinkTokenforgot(idapp, email, tokenforgot) .then((user) => { return user; - }).catch((e) => { + }) + .catch((e) => { console.log(process.env.LINK_UPDATE_PWD, e.message); res.status(400).send(); }); @@ -254,49 +249,46 @@ router.post(process.env.LINK_UPDATE_PWD, async (req, res) => { user = await User.findByLinkTokenforgotCode(idapp, email, tokenforgot_code) .then((user) => { return user; - }).catch((e) => { + }) + .catch((e) => { console.log(process.env.LINK_UPDATE_PWD, e.message); res.status(400).send(); }); } if (!user) { - return res.send( - { code: server_constants.RIS_CODE_TOKEN_RESETPASSWORD_NOT_FOUND }); + return res.send({ code: server_constants.RIS_CODE_TOKEN_RESETPASSWORD_NOT_FOUND }); } else { // aggiorna la nuova password user.password = password; user.lasttimeonline = new Date(); // Crea token - user.generateAuthToken(req).then(ris => { - user.tokenforgot = ''; // Svuota il tokenforgot perché non ti servirà più... - user.tokenforgot_code = ''; // Svuota il tokenforgot perché non ti servirà più... + user.generateAuthToken(req).then((ris) => { + user.tokenforgot = ''; // Svuota il tokenforgot perché non ti servirà più... + user.tokenforgot_code = ''; // Svuota il tokenforgot perché non ti servirà più... // Salva lo User user.save().then(() => { - res.header('x-auth', ris.token) + res + .header('x-auth', ris.token) .header('x-refrtok', ris.refreshToken) - .send({ code: server_constants.RIS_CODE_OK }); // Ritorna il token di ritorno + .send({ code: server_constants.RIS_CODE_OK }); // Ritorna il token di ritorno }); }); } } catch (e) { console.error('Error: ', e); } - }); router.post('/testServer', authenticate_noerror, async (req, res) => { - try { const test = req.body.test; let ris = { test }; if (req.user) { - await tools.sendNotificationToUser(req.user._id, 'Test Server', - 'Test Server OK', - '/', '', 'server', []); + await tools.sendNotificationToUser(req.user._id, 'Test Server', 'Test Server OK', '/', '', 'server', []); } return res.send(ris); @@ -304,19 +296,15 @@ router.post('/testServer', authenticate_noerror, async (req, res) => { console.error('testServer', e.message); return res.status(400).send(e); } - }); router.get('/test1', authenticate_noerror, async (req, res) => { - try { const test = req.query.test; let ris = { test }; if (req.user) { - await tools.sendNotificationToUser(req.user._id, 'Test Server', - 'Test Server OK', - '/', '', 'server', []); + await tools.sendNotificationToUser(req.user._id, 'Test Server', 'Test Server OK', '/', '', 'server', []); } return res.send(ris); @@ -324,7 +312,6 @@ router.get('/test1', authenticate_noerror, async (req, res) => { console.error('testServer', e.message); return res.status(400).send(e); } - }); router.post('/settable', authenticate, async (req, res) => { @@ -343,7 +330,7 @@ router.post('/settable', authenticate, async (req, res) => { return res.status(400).send('Mydata VUOTO'); } - const fieldsvalue = { 'ALL': 1 }; + const fieldsvalue = { ALL: 1 }; mydata.idapp = req.user.idapp; const idapp = mydata.idapp; @@ -355,32 +342,35 @@ router.post('/settable', authenticate, async (req, res) => { let consentito = false; try { - if (User.isAdmin(req.user.perm) || User.isManager(req.user.perm) || - User.isEditor(req.user.perm) || User.isCommerciale(req.user.perm) || User.isFacilitatore(req.user.perm)) { + if ( + User.isAdmin(req.user.perm) || + User.isManager(req.user.perm) || + User.isEditor(req.user.perm) || + User.isCommerciale(req.user.perm) || + User.isFacilitatore(req.user.perm) + ) { consentito = true; } - if ((!User.isAdmin(req.user.perm) - && !User.isManager(req.user.perm) - && !User.isEditor(req.user.perm) - && !User.isCommerciale(req.user.perm) - && !User.isGrafico(req.user.perm) - && !User.isFacilitatore(req.user.perm)) - && - await !tools.ModificheConsentite(req, params.table, fieldsvalue, mydata ? mydata._id : '')) { + if ( + !User.isAdmin(req.user.perm) && + !User.isManager(req.user.perm) && + !User.isEditor(req.user.perm) && + !User.isCommerciale(req.user.perm) && + !User.isGrafico(req.user.perm) && + !User.isFacilitatore(req.user.perm) && + (await !tools.ModificheConsentite(req, params.table, fieldsvalue, mydata ? mydata._id : '')) + ) { // If without permissions, exit - return res.status(404). - send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' }); + return res.status(404).send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' }); } if (shared_consts.TABLES_USER_ID.includes(params.table)) { - if (!mydata.userId) - mydata.userId = req.user._id; + if (!mydata.userId) mydata.userId = req.user._id; } if (shared_consts.TABLES_CREATEDBY.includes(params.table)) { - if (!mydata.createdBy) - mydata.createdBy = req.user.username; + if (!mydata.createdBy) mydata.createdBy = req.user.username; } if (shared_consts.TABLES_UPDATE_LASTMODIFIED.includes(params.table)) { @@ -396,20 +386,18 @@ router.post('/settable', authenticate, async (req, res) => { if (params.table === shared_consts.TAB_MYGROUPS) { if (shared_consts.MYGROUPS_KEY_TO_CRYPTED in mydata) { if (mydata[shared_consts.MYGROUPS_KEY_TO_CRYPTED]) { - mydata[shared_consts.MYGROUPS_KEY_TO_CRYPTED + - shared_consts.SUFFIX_CRYPTED] = tools.cryptdata( - mydata[shared_consts.MYGROUPS_KEY_TO_CRYPTED]); + mydata[shared_consts.MYGROUPS_KEY_TO_CRYPTED + shared_consts.SUFFIX_CRYPTED] = tools.cryptdata( + mydata[shared_consts.MYGROUPS_KEY_TO_CRYPTED] + ); } } - } if (shared_consts.TABLES_USER_INCLUDE_MY.includes(params.table)) { if (!mydata.admins || mydata.admins.length <= 0) { // Aggiungi solo se non esistono Admin: mydata.admins = []; - const indfind = mydata.admins.findIndex( - (rec) => (rec.username === req.user.username)); + const indfind = mydata.admins.findIndex((rec) => rec.username === req.user.username); if (indfind < 0) { mydata.admins.push({ username: req.user.username }); @@ -420,7 +408,7 @@ router.post('/settable', authenticate, async (req, res) => { delete mydata['__v']; delete mydata['__proto__']; - const isNotNew = (mydata['_id'] !== undefined && mydata['_id'] !== 0 && mydata['_id'] !== ''); + const isNotNew = mydata['_id'] !== undefined && mydata['_id'] !== 0 && mydata['_id'] !== ''; let mytablerec = null; @@ -430,20 +418,20 @@ router.post('/settable', authenticate, async (req, res) => { const mytablestrutt = globalTables.getTableByTableName(params.table); - if (isNotNew) { mytablerec.isNew = false; } - if (shared_consts.TABLES_ID_NUMBER.includes(params.table) || - shared_consts.TABLES_ID_STRING.includes(params.table)) { - + if ( + shared_consts.TABLES_ID_NUMBER.includes(params.table) || + shared_consts.TABLES_ID_STRING.includes(params.table) + ) { } else if (params.table === 'hours') { - } else { - if ((mydata['_id'] === undefined || mydata['_id'] === '' || - (mytablerec.isNew && mydata['_id'] === 0)) - && (mytablerec._id === undefined || mytablerec._id === '0')) { + if ( + (mydata['_id'] === undefined || mydata['_id'] === '' || (mytablerec.isNew && mydata['_id'] === 0)) && + (mytablerec._id === undefined || mytablerec._id === '0') + ) { mytablerec._id = new ObjectId(); mydata._id = new ObjectId(); mytablerec.isNew = true; @@ -490,34 +478,36 @@ router.post('/settable', authenticate, async (req, res) => { // then(async (rec) => { const myPromise = new Promise((resolve, reject) => { - resolve(mytablerec._id && mytable.findById(mytablerec._id)) + resolve(mytablerec._id && mytable.findById(mytablerec._id)); }); // Controlla se esiste già questo record: if (shared_consts.TABLES_FIELDS_DESCR_AND_CITY_AND_USER.includes(params.table)) { if (mytablerec.isNew) { - const trovatoDuplicato = await mytable.findOne({ idapp: mytablerec.idapp, descr: mytablerec.descr, idCity: mytablerec.idCity, userId: mytablerec.userId }).lean(); + const trovatoDuplicato = await mytable + .findOne({ + idapp: mytablerec.idapp, + descr: mytablerec.descr, + idCity: mytablerec.idCity, + userId: mytablerec.userId, + }) + .lean(); if (trovatoDuplicato) { // trovatoDuplicato return res.status(200).send({ code: server_constants.RIS_CODE_REC_DUPLICATED_DESCR_CITY_USER, msg: '' }); - - } } } return await myPromise .then(async (doupdate) => { - if (false) { let plainObject = mytablerec.toObject(); console.log(plainObject); } - if (doupdate) - return mytable.updateOne({ _id: mytablerec._id }, mydata, { new: true }) - else - return mytablerec.save() + if (doupdate) return mytable.updateOne({ _id: mytablerec._id }, mydata, { new: true }); + else return mytablerec.save(); }) .then(async (risult) => { let rec = null; @@ -534,8 +524,8 @@ router.post('/settable', authenticate, async (req, res) => { } // tools.mylog('rec', rec); - }).then(async (myrec) => { - + }) + .then(async (myrec) => { let setnotif = false; let typedir = 0; let typeid = 0; @@ -547,12 +537,11 @@ router.post('/settable', authenticate, async (req, res) => { if (shared_consts.TABLES_ADV_NOTIFICATION.includes(params.table)) { typedir = shared_consts.TypeNotifs.TYPEDIR_BACHECA; - if (params.table === shared_consts.TABLES_MYGOODS) - typeid = shared_consts.TypeNotifs.ID_BACHECA_NEW_GOOD + if (params.table === shared_consts.TABLES_MYGOODS) typeid = shared_consts.TypeNotifs.ID_BACHECA_NEW_GOOD; else if (params.table === shared_consts.TABLES_MYSKILLS) - typeid = shared_consts.TypeNotifs.ID_BACHECA_NEW_SERVICE + typeid = shared_consts.TypeNotifs.ID_BACHECA_NEW_SERVICE; else if (params.table === shared_consts.TABLES_MYHOSPS) - typeid = shared_consts.TypeNotifs.ID_BACHECA_NEW_HOSP + typeid = shared_consts.TypeNotifs.ID_BACHECA_NEW_HOSP; setnotif = true; } @@ -579,7 +568,15 @@ router.post('/settable', authenticate, async (req, res) => { if (setnotif) { const myreq = { ...req }; const myres = { ...res }; - SendNotif.createNewNotification(myreq, myres, { groupnameDest, circuitnameDest }, params.table, myrec, typedir, typeid); + SendNotif.createNewNotification( + myreq, + myres, + { groupnameDest, circuitnameDest }, + params.table, + myrec, + typedir, + typeid + ); } if (params.table === 'circuits') { @@ -589,27 +586,47 @@ router.post('/settable', authenticate, async (req, res) => { if (params.table === shared_consts.TAB_MYGROUPS && isnewrec) { // nuovo Record: // aggiungi il creatore al gruppo stesso - return await User.setGroupsCmd(mydata.idapp, req.user.username, + return await User.setGroupsCmd( + mydata.idapp, + req.user.username, myrec.groupname, - shared_consts.GROUPSCMD.SETGROUP, true, req.user.username).then((ris) => { - return res.send({ rec: myrec, ris }); - }); + shared_consts.GROUPSCMD.SETGROUP, + true, + req.user.username + ).then((ris) => { + return res.send({ rec: myrec, ris }); + }); } else if (params.table === shared_consts.TAB_MYCIRCUITS && isnewrec) { // nuovo Circuito: - await User.setCircuitCmd(mydata.idapp, req.user.username, myrec.name, - shared_consts.CIRCUITCMD.CREATE, true, req.user.username, extrarec).then((ris) => { - return res.send({ rec: myrec, ris }); - }); + await User.setCircuitCmd( + mydata.idapp, + req.user.username, + myrec.name, + shared_consts.CIRCUITCMD.CREATE, + true, + req.user.username, + extrarec + ).then((ris) => { + return res.send({ rec: myrec, ris }); + }); // aggiungi il creatore al Circuito stesso - return await User.setCircuitCmd(mydata.idapp, req.user.username, myrec.name, - shared_consts.CIRCUITCMD.SET, true, req.user.username, extrarec).then((ris) => { - return res.send({ rec: myrec, ris }); - }); + return await User.setCircuitCmd( + mydata.idapp, + req.user.username, + myrec.name, + shared_consts.CIRCUITCMD.SET, + true, + req.user.username, + extrarec + ).then((ris) => { + return res.send({ rec: myrec, ris }); + }); } return res.send({ rec: myrec, ris: null }); - }).catch(async (e) => { + }) + .catch(async (e) => { console.error('settable', e.message); if (e.code === 11000) { const id = mytablerec._id; @@ -618,11 +635,12 @@ router.post('/settable', authenticate, async (req, res) => { if (!myfields.userId) { myfields.userId = req.user._id.toString(); } - return await mytablestrutt.findByIdAndUpdate(id, { $set: myfields }). - then(async (rec) => { + return await mytablestrutt + .findByIdAndUpdate(id, { $set: myfields }) + .then(async (rec) => { return res.send({ rec }); - }). - catch((err) => { + }) + .catch((err) => { tools.mylog('error: ', err.message); return res.status(400).send(err); }); @@ -630,12 +648,10 @@ router.post('/settable', authenticate, async (req, res) => { console.log(e.message); } }); - } catch (e) { console.error('settable', e.message); return res.status(400).send(e); } - }); router.post('/setsubrec', authenticate, (req, res) => { @@ -650,47 +666,46 @@ router.post('/setsubrec', authenticate, (req, res) => { const mytablestrutt = globalTables.getTableByTableName(params.table); - const rec = mytablestrutt.createNewSubRecord(mydata.idapp, req).then(rec => { - // tools.mylog('rec', rec); - return res.send(rec); - - }).catch((e) => { - - }); + const rec = mytablestrutt + .createNewSubRecord(mydata.idapp, req) + .then((rec) => { + // tools.mylog('rec', rec); + return res.send(rec); + }) + .catch((e) => {}); return res.send(rec); - - return mytablerec.save().then(rec => { - // tools.mylog('rec', rec); - return res.send(rec); - - - }).catch((e) => { - if (e.code === 11000) { - const id = mytablerec._id; - delete mytablerec._doc['_id']; - const myfields = mytablerec._doc; - if (!myfields.userId) { - myfields.userId = req.user._id.toString(); + return mytablerec + .save() + .then((rec) => { + // tools.mylog('rec', rec); + return res.send(rec); + }) + .catch((e) => { + if (e.code === 11000) { + const id = mytablerec._id; + delete mytablerec._doc['_id']; + const myfields = mytablerec._doc; + if (!myfields.userId) { + myfields.userId = req.user._id.toString(); + } + return mytablestrutt + .findByIdAndUpdate(id, { $set: myfields }) + .then(async (rec) => { + return res.send(rec); + }) + .catch((err) => { + tools.mylog('error: ', err.message); + return res.status(400).send(err); + }); + } else { + console.log(e.message); } - return mytablestrutt.findByIdAndUpdate(id, { $set: myfields }). - then(async (rec) => { - return res.send(rec); - }). - catch((err) => { - tools.mylog('error: ', err.message); - return res.status(400).send(err); - }); - } else { - console.log(e.message); - } - }); - + }); }); router.post('/getobj', authenticate_noerror, async (req, res) => { - try { let cmd = req.body.cmd; let idapp = req.user ? req.user.idapp : sanitizeHtml(req.body.idapp); // Cambiato from params.idapp a req.body.idapp @@ -703,12 +718,13 @@ router.post('/getobj', authenticate_noerror, async (req, res) => { perm: { $bitsAnySet: 0b10000 }, }, { username: 1, name: 1, surname: 1 } - ).sort({ username: 1 }).lean(); + ) + .sort({ username: 1 }) + .lean(); } // Invia la risposta res.status(200).send({ code: server_constants.RIS_CODE_OK, data: ris }); - } catch (e) { console.error(`ERROR getobj`, e.message); res.status(200).send({ code: server_constants.RIS_CODE_OK, data: [] }); @@ -733,26 +749,24 @@ router.post('/gettable', authenticate_noerror, (req, res) => { } try { - if (req.user && req.user.username) { User.setOnLine(req.user.idapp, req.user.username); } - - return mytable.executeQueryTable(idapp, params, req.user).then(ris => { - // console.log('ris=', ris); - return res.send(ris); - - }).catch((e) => { - console.error('gettable: ' + e.message); - res.status(400).send(e); - }); + return mytable + .executeQueryTable(idapp, params, req.user) + .then((ris) => { + // console.log('ris=', ris); + return res.send(ris); + }) + .catch((e) => { + console.error('gettable: ' + e.message); + res.status(400).send(e); + }); } catch (e) { - console.error(`ERROR gettable ${params.table}: `, e.message, 'params', - params); + console.error(`ERROR gettable ${params.table}: `, e.message, 'params', params); res.status(500).send(e); } - }); router.post('/getexp', authenticate, (req, res) => { @@ -764,51 +778,46 @@ router.post('/getexp', authenticate, (req, res) => { return res.status(400).send({}); } - if ((!User.isAdmin(req.user.perm) && !User.isManager(req.user.perm) && - !User.isFacilitatore(req.user.perm))) { + if (!User.isAdmin(req.user.perm) && !User.isManager(req.user.perm) && !User.isFacilitatore(req.user.perm)) { // If without permissions, exit - return res.status(404). - send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' }); + return res.status(404).send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' }); } try { - if (params.table === 'exp') { - return myUser.find({ - idapp, - $or: [ - { deleted: { $exists: false } }, - { deleted: { $exists: true, $eq: false } }], - }, - { - username: 1, - name: 1, - surname: 1, - email: 1, - 'reported': 1, - date_report: 1, - username_who_report: 1, - 'profile.teleg_id': 1, - 'verified_by_aportador': 1, - 'profile.username_telegram': 1, - 'profile.firstname_telegram': 1, - 'profile.lastname_telegram': 1, - }).then(ris => { - + return myUser + .find( + { + idapp, + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], + }, + { + username: 1, + name: 1, + surname: 1, + email: 1, + reported: 1, + date_report: 1, + username_who_report: 1, + 'profile.teleg_id': 1, + verified_by_aportador: 1, + 'profile.username_telegram': 1, + 'profile.firstname_telegram': 1, + 'profile.lastname_telegram': 1, + } + ) + .then((ris) => { return res.send(ris); - - }).catch((e) => { + }) + .catch((e) => { console.error('getexp: ' + e.message); res.status(400).send(e); }); } - } catch (e) { - console.error(`ERROR getexp ${params.table}: `, e.message, 'params', - params); + console.error(`ERROR getexp ${params.table}: `, e.message, 'params', params); res.status(500).send(e); } - }); router.post('/pickup', authenticate_noerror, (req, res) => { @@ -821,14 +830,15 @@ router.post('/pickup', authenticate_noerror, (req, res) => { return res.status(400).send({}); } - return mytable.executeQueryPickup(idapp, params).then(ris => { - return res.send(ris); - - }).catch((e) => { - console.log(e.message); - res.status(400).send(e); - }); - + return mytable + .executeQueryPickup(idapp, params) + .then((ris) => { + return res.send(ris); + }) + .catch((e) => { + console.log(e.message); + res.status(400).send(e); + }); }); router.post('/getpage', async (req, res) => { @@ -836,19 +846,19 @@ router.post('/getpage', async (req, res) => { const idapp = req.body.idapp; const mypath = params.path; - let found = await MyPage.findOne({ idapp, path: mypath }).then((ris) => { - if (ris && ris._doc) - return res.send({ mypage: ris._doc }); - else - return null; - }).catch((e) => { - console.log(e.message); - res.status(400).send(e); - }); + let found = await MyPage.findOne({ idapp, path: mypath }) + .then((ris) => { + if (ris && ris._doc) return res.send({ mypage: ris._doc }); + else return null; + }) + .catch((e) => { + console.log(e.message); + res.status(400).send(e); + }); if (!found) { // trova quelli con il : - let regexp = new RegExp(`:`, 'ig') + let regexp = new RegExp(`:`, 'ig'); const searchpagesSpec = await MyPage.find({ idapp, path: { $regex: regexp } }); if (searchpagesSpec) { @@ -857,7 +867,6 @@ router.post('/getpage', async (req, res) => { let arrsubstr = searchpagesSpec[i].path.split('/'); if (arrsubpath.length === arrsubpath.length) { - let mypathbuild = ''; for (let j = 0; j < arrsubstr.length; j++) { @@ -880,7 +889,6 @@ router.post('/getpage', async (req, res) => { }); } return found; - }); async function duplicatePage(pageId, newpath) { @@ -901,7 +909,7 @@ async function duplicatePage(pageId, newpath) { title: newpath, inmenu: false, active: true, - date_updated: new Date() + date_updated: new Date(), }); // Salva il nuovo record di Page @@ -911,12 +919,10 @@ async function duplicatePage(pageId, newpath) { const elemsToDuplicate = await MyElem.find({ idPage: pageId }).lean(); // Duplica ogni elemento utilizzando il nuovo idPath - const duplicates = elemsToDuplicate.map(elem => { - + const duplicates = elemsToDuplicate.map((elem) => { const catalogo = elem.catalogo; if (catalogo) { - for (const recscheda of catalogo.arrSchede) { if (recscheda.scheda?.isTemplate) { // Se è un template allora devo mettergli un altro ID ! @@ -926,13 +932,12 @@ async function duplicatePage(pageId, newpath) { } } - if (catalogo) - elem.catalogo = { ...catalogo }; + if (catalogo) elem.catalogo = { ...catalogo }; const newElem = new MyElem({ ...elem, // Copia le proprietà dell'elemento _id: new mongoose.Types.ObjectId(), // Genera un nuovo ID - idPage: newPage._id.toString() // Imposta il nuovo campo IdPage + idPage: newPage._id.toString(), // Imposta il nuovo campo IdPage }); return newElem; @@ -947,15 +952,14 @@ async function duplicatePage(pageId, newpath) { console.error('Errore durante la duplicazione:', error); return false; } -}; +} async function exportPage(idapp, pageId) { try { - const myexp = { mypages: [], myelems: [], - } + }; // Trova il record di Page da duplicare const pageToExp = await MyPage.find({ _id: pageId, idapp }).lean(); @@ -980,15 +984,13 @@ async function exportPage(idapp, pageId) { } return ''; - } catch (error) { - console.error('Errore durante l\'esportazione:', error); + console.error("Errore durante l'esportazione:", error); return ''; } -}; +} async function upsertRecord(table, record, appId, newIdPage = null) { - let newId = null; const existingRecord = await table.findOne({ idapp: appId, _id: record._id }); // Assumendo che `record` ha un ID @@ -1009,8 +1011,7 @@ async function upsertRecord(table, record, appId, newIdPage = null) { const modif = await table.updateOne({ _id: existingRecPage._id }, { $set: { ...record, idapp: appId } }); const tableElems = globalTables.getTableByTableName('myelems'); - if (tableElems) - risdel = await tableElems.deleteMany({ idapp: appId, idPage: existingRecPage._id }); + if (tableElems) risdel = await tableElems.deleteMany({ idapp: appId, idPage: existingRecPage._id }); newId = existingRecPage._id.toString(); return { ImportedRecords: false, newId }; // Torna il numero di record importati (1 in questo caso) @@ -1020,7 +1021,7 @@ async function upsertRecord(table, record, appId, newIdPage = null) { const existingRecSameID = await table.findOne({ _id: record._id }); // Assumendo che `record` ha un ID if (existingRecSameID) { - // Se + // Se newId = new ObjectId(); record._id = newId; } @@ -1048,7 +1049,7 @@ async function importPage(req, idapp, jsonString) { // Assicurati che i dati siano ben strutturati if (!myexp) { - console.error('Dati non validi per l\'importazione.'); + console.error("Dati non validi per l'importazione."); return; } @@ -1079,14 +1080,11 @@ async function importPage(req, idapp, jsonString) { } } totalImportedRecords += ImportedRecordstemp; - } - if (ImportedRecordstemp > 0) - importCounts.push({ tableName, count: ImportedRecordstemp }); + if (ImportedRecordstemp > 0) importCounts.push({ tableName, count: ImportedRecordstemp }); } } - // Ciclo su ogni proprietà di myexp for (const key in myexp) { if (myexp.hasOwnProperty(key)) { @@ -1104,7 +1102,6 @@ async function importPage(req, idapp, jsonString) { ImportedRecordstemp += ImportedRecords ? 1 : 0; } } - } else if (tableName === 'myusers') { if (User.isManager(req.user.perm)) { for (const user of myexp.myusers) { @@ -1112,7 +1109,7 @@ async function importPage(req, idapp, jsonString) { ImportedRecordstemp += ImportedRecords ? 1 : 0; } } - } else if (table && (tableName !== 'mypages')) { + } else if (table && tableName !== 'mypages') { // Tutte le altre tabelle if (User.isManager(req.user.perm)) { for (const rec of myexp[key]) { @@ -1123,8 +1120,7 @@ async function importPage(req, idapp, jsonString) { } totalImportedRecords += ImportedRecordstemp; - if (ImportedRecordstemp > 0) - importCounts.push({ tableName, count: ImportedRecordstemp }); + if (ImportedRecordstemp > 0) importCounts.push({ tableName, count: ImportedRecordstemp }); } } } @@ -1134,9 +1130,8 @@ async function importPage(req, idapp, jsonString) { } return { imported: totalImportedRecords, importCounts }; - } catch (error) { - console.error('Errore durante l\'importazione:', error); + console.error("Errore durante l'importazione:", error); } } @@ -1147,7 +1142,6 @@ router.post('/duppage', authenticate, async (req, res) => { const newpath = params.newpath; try { - let found = await MyPage.findOne({ idapp, path: mypath }) .then(async (ris) => { const result = await duplicatePage(ris._id, newpath); @@ -1156,16 +1150,14 @@ router.post('/duppage', authenticate, async (req, res) => { } else { return res.send({ code: server_constants.RIS_CODE_ERR, msg: '' }); } - - }).catch((e) => { + }) + .catch((e) => { console.log(e.message); res.status(400).send(e); }); - } catch (e) { console.error('Error', e); } - }); router.post('/exppage', authenticate, async (req, res) => { @@ -1174,7 +1166,6 @@ router.post('/exppage', authenticate, async (req, res) => { const mypath = params.path; try { - let found = await MyPage.findOne({ idapp, path: mypath }) .then(async (ris) => { const resultJSon = await exportPage(idapp, ris._id); @@ -1183,16 +1174,14 @@ router.post('/exppage', authenticate, async (req, res) => { } else { return res.send({ code: server_constants.RIS_CODE_ERR, msg: '' }); } - - }).catch((e) => { + }) + .catch((e) => { console.log(e.message); res.status(400).send(e); }); - } catch (e) { console.error('Error', e); } - }); router.post('/imppage', authenticate, async (req, res) => { const params = req.body; @@ -1200,19 +1189,16 @@ router.post('/imppage', authenticate, async (req, res) => { const jsonString = params.jsonString; try { - const result = await importPage(req, idapp, jsonString); if (result) { return res.send({ code: server_constants.RIS_CODE_OK, ris: result }); } else { return res.send({ code: server_constants.RIS_CODE_ERR, ris: '' }); } - } catch (e) { console.log(e.message); res.status(400).send(e); - }; - + } }); router.patch('/setlang', authenticate, async (req, res) => { @@ -1229,8 +1215,7 @@ router.patch('/setlang', authenticate, async (req, res) => { if (!!lang) { const rec = await User.findByUsername(idapp, username, false); let ris = null; - if (!!rec) - ris = await User.findByIdAndUpdate(rec.id, { $set: fieldsvalue }); + if (!!rec) ris = await User.findByIdAndUpdate(rec.id, { $set: fieldsvalue }); if (!!ris) { return res.send({ code: server_constants.RIS_CODE_OK, msg: '' }); @@ -1238,7 +1223,6 @@ router.patch('/setlang', authenticate, async (req, res) => { res.status(400).send(); } - }); router.patch('/chval', authenticate, async (req, res) => { @@ -1257,23 +1241,20 @@ router.patch('/chval', authenticate, async (req, res) => { // tools.mylogshow('PATCH CHVAL: ', id, fieldsvalue); // If I change my record... - if (( - (!User.isAdmin(req.user.perm) - && !User.isManager(req.user.perm) - && !User.isEditor(req.user.perm) - && !User.isCommerciale(req.user.perm) - && !User.isFacilitatore(req.user.perm)) - && (await !tools.ModificheConsentite(req, mydata.table, fieldsvalue, id))) - && !((mydata.table === 'accounts') - && await Account.canEditAccountAdmins(req.user.username, mydata.id)) + if ( + !User.isAdmin(req.user.perm) && + !User.isManager(req.user.perm) && + !User.isEditor(req.user.perm) && + !User.isCommerciale(req.user.perm) && + !User.isFacilitatore(req.user.perm) && + (await !tools.ModificheConsentite(req, mydata.table, fieldsvalue, id)) && + !(mydata.table === 'accounts' && (await Account.canEditAccountAdmins(req.user.username, mydata.id))) ) { // If without permissions, exit - return res.status(404). - send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' }); + return res.status(404).send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' }); } - const camporequisiti = UserCost.FIELDS_REQUISITI.includes( - Object.keys(fieldsvalue)[0]); + const camporequisiti = UserCost.FIELDS_REQUISITI.includes(Object.keys(fieldsvalue)[0]); let allData = {}; let username = ''; @@ -1282,11 +1263,8 @@ router.patch('/chval', authenticate, async (req, res) => { allData = {}; allData.myuser = await User.getUserById(idapp, id); username = allData.myuser.username; - if (!!allData.myuser) - allData.precDataUser = await User.getInfoUser(idapp, - allData.myuser.username); - else - allData.precDataUser = null; + if (!!allData.myuser) allData.precDataUser = await User.getInfoUser(idapp, allData.myuser.username); + else allData.precDataUser = null; // allData.useraportador = await ListaIngresso.getUserByInvitante_Username(idapp, allData.myuser.aportador_solidario); // allData.precDataAportador = await getInfoUser(idapp, allData.myuser.aportador_solidario); } @@ -1336,18 +1314,17 @@ router.patch('/chval', authenticate, async (req, res) => { if (mydata.table === shared_consts.TAB_SITES) { if (shared_consts.SITES_KEY_TO_CRYPTED in fieldsvalue) { fieldsvalue[shared_consts.SITES_KEY_TO_CRYPTED] = tools.cryptdata( - fieldsvalue[shared_consts.SITES_KEY_TO_CRYPTED]); + fieldsvalue[shared_consts.SITES_KEY_TO_CRYPTED] + ); } - } - let precRec = null + let precRec = null; if (mydata.table === 'accounts') { precRec = await mytable.findById(id); } - if (mydata.table === 'arrvariazioni') { let chiave = null; let valore = null; @@ -1362,8 +1339,9 @@ router.patch('/chval', authenticate, async (req, res) => { fieldsvalue = { [`arrvariazioni.0.${chiave}`]: valore }; } } - return await mytable.findByIdAndUpdate(id, { $set: fieldsvalue }, { new: true }). - then(async (rec) => { + return await mytable + .findByIdAndUpdate(id, { $set: fieldsvalue }, { new: true }) + .then(async (rec) => { // tools.mylogshow(' REC TO MODIFY: ', rec); if (!rec) { return res.status(404).send(); @@ -1372,38 +1350,54 @@ router.patch('/chval', authenticate, async (req, res) => { if (mydata.notifBot) { // Send Notification to the BOT - await telegrambot.sendMsgTelegram(idapp, mydata.notifBot.un, - mydata.notifBot.txt); - if (!!addmsg) - await telegrambot.sendMsgTelegram(idapp, mydata.notifBot.un, - addmsg); - let addtext = '[Msg Inviato a ' + mydata.notifBot.un + ']:' + - '\n' + - mydata.notifBot.txt; + await telegrambot.sendMsgTelegram(idapp, mydata.notifBot.un, mydata.notifBot.txt); + if (!!addmsg) await telegrambot.sendMsgTelegram(idapp, mydata.notifBot.un, addmsg); + let addtext = '[Msg Inviato a ' + mydata.notifBot.un + ']:' + '\n' + mydata.notifBot.txt; telegrambot.sendMsgTelegramToTheManagers(idapp, addtext, true); - if (!!flotta) - tools.writeFlottaLog(idapp, addtext, flotta.riga, - flotta.col_prima); + if (!!flotta) tools.writeFlottaLog(idapp, addtext, flotta.riga, flotta.col_prima); } if (mydata.table === 'accounts') { let msg = ''; - if (rec.circuitId) - circuit = await Circuit.getCircuitByCircuitId(rec.circuitId); + if (rec.circuitId) circuit = await Circuit.getCircuitByCircuitId(rec.circuitId); let dest = rec.groupname ? rec.groupname : rec.username; - let valprec = 0 + let valprec = 0; if ('saldo' in fieldsvalue) { - valprec = precRec && precRec.saldo ? precRec.saldo : 0 - msg = i18n.__('SALDO_VARIATO', circuit.name, req.user.username, dest, valprec, fieldsvalue.saldo, circuit.symbol); + valprec = precRec && precRec.saldo ? precRec.saldo : 0; + msg = i18n.__( + 'SALDO_VARIATO', + circuit.name, + req.user.username, + dest, + valprec, + fieldsvalue.saldo, + circuit.symbol + ); } else if ('fidoConcesso' in fieldsvalue) { - valprec = precRec && precRec.fidoConcesso ? precRec.fidoConcesso : 0 - msg = i18n.__('FIDOCONCESSO_VARIATO', circuit.name, req.user.username, dest, valprec, fieldsvalue.fidoConcesso, circuit.symbol); + valprec = precRec && precRec.fidoConcesso ? precRec.fidoConcesso : 0; + msg = i18n.__( + 'FIDOCONCESSO_VARIATO', + circuit.name, + req.user.username, + dest, + valprec, + fieldsvalue.fidoConcesso, + circuit.symbol + ); } else if ('qta_maxConcessa' in fieldsvalue) { - valprec = precRec && precRec.qta_maxConcessa ? precRec.qta_maxConcessa : 0 - msg = i18n.__('QTAMAX_VARIATO', circuit.name, req.user.username, dest, valprec, fieldsvalue.qta_maxConcessa, circuit.symbol); + valprec = precRec && precRec.qta_maxConcessa ? precRec.qta_maxConcessa : 0; + msg = i18n.__( + 'QTAMAX_VARIATO', + circuit.name, + req.user.username, + dest, + valprec, + fieldsvalue.qta_maxConcessa, + circuit.symbol + ); } if (msg) { @@ -1412,9 +1406,7 @@ router.patch('/chval', authenticate, async (req, res) => { } } - if (mydata.table === 'users') { - if ('profile.resid_province' in fieldsvalue) { const card = fieldsvalue.hasOwnProperty('profile.resid_card') ? fieldsvalue['profile.resid_card'] : ''; // Controlla se esiste il Circuito di questa provincia, se non esiste lo crea! @@ -1428,37 +1420,34 @@ router.patch('/chval', authenticate, async (req, res) => { if ('aportador_solidario' in fieldsvalue) { let ind_order_ingr = mydata.ind_order_ingr; // SERVE SE CI METTO LE MINUSCOLE/MAIUSCOLE SBAGLIATE in invitante_username! - const myuserfound = await User.findByUsername(idapp, - fieldsvalue.aportador_solidario, false); + const myuserfound = await User.findByUsername(idapp, fieldsvalue.aportador_solidario, false); if (!!myuserfound) { if (!!myuserfound._id && !myuserfound.deleted) { - const aportador = await User.getUsernameById(idapp, - myuserfound._id); + const aportador = await User.getUsernameById(idapp, myuserfound._id); fieldsvalue.aportador_solidario = aportador; //Aggiorna record ! await mytable.findByIdAndUpdate(id, { $set: fieldsvalue }); - } } else { - res.send( - { - code: server_constants.RIS_CODE_ERR, - msg: 'Non aggiornato', - }); + res.send({ + code: server_constants.RIS_CODE_ERR, + msg: 'Non aggiornato', + }); res.status(400).send(); return false; } } else if ('deleted' in fieldsvalue) { let msg = ''; - if (fieldsvalue.deleted) - msg = 'cancellato (nascosto)'; - else - msg = 'Ripristinato'; + if (fieldsvalue.deleted) msg = 'cancellato (nascosto)'; + else msg = 'Ripristinato'; - await telegrambot.sendMsgTelegramToTheManagers(idapp, - `L\'utente ` + tools.getNomeCognomeEUserNameByUser(rec) + - ` è stato ${msg} da ` + - tools.getNomeCognomeEUserNameByUser(req.user)); + await telegrambot.sendMsgTelegramToTheManagers( + idapp, + `L\'utente ` + + tools.getNomeCognomeEUserNameByUser(rec) + + ` è stato ${msg} da ` + + tools.getNomeCognomeEUserNameByUser(req.user) + ); } } @@ -1466,43 +1455,43 @@ router.patch('/chval', authenticate, async (req, res) => { let msg = ''; if (mydata.table === 'users') { if ('aportador_solidario' in fieldsvalue) { - const nomecognomenuovo = await User.getNameSurnameByUsername( - idapp, - fieldsvalue.aportador_solidario); - const nomecognomeas = await User.getNameSurnameByUsername( - idapp, - rec.aportador_solidario); - msg = `Variato l'invitante di ` + + const nomecognomenuovo = await User.getNameSurnameByUsername(idapp, fieldsvalue.aportador_solidario); + const nomecognomeas = await User.getNameSurnameByUsername(idapp, rec.aportador_solidario); + msg = + `Variato l'invitante di ` + tools.getNomeCognomeEUserNameByUser(rec) + '\nmodificato da ' + tools.getNomeCognomeEUserNameByUser(req.user) + ' \n' + - 'Prima: ' + nomecognomeas + ' (' + + 'Prima: ' + + nomecognomeas + + ' (' + rec.aportador_solidario + ')\n' + - 'Dopo: ' + nomecognomenuovo + ' (' + - fieldsvalue.aportador_solidario + ') ]'; + 'Dopo: ' + + nomecognomenuovo + + ' (' + + fieldsvalue.aportador_solidario + + ') ]'; // Metti l'iniziale - if (!await User.AportadorOrig(id)) { - await mytable.findByIdAndUpdate(id, + if (!(await User.AportadorOrig(id))) { + await mytable.findByIdAndUpdate( + id, { $set: { aportador_iniziale: fieldsvalue.aportador_solidario } }, - { new: false }); + { new: false } + ); } } - } - if (msg !== '') - telegrambot.sendMsgTelegramToTheManagers(idapp, msg); + if (msg !== '') telegrambot.sendMsgTelegramToTheManagers(idapp, msg); } res.send({ code: server_constants.RIS_CODE_OK, msg: '' }); - } - - }). - catch((e) => { + }) + .catch((e) => { tools.mylogserr('Error patch USER: ', e.message); res.status(400).send(); }); @@ -1510,7 +1499,6 @@ router.patch('/chval', authenticate, async (req, res) => { tools.mylogserr('Error chval: ', e.message); res.status(400).send(); } - }); router.patch('/askfunz', authenticate, async (req, res) => { @@ -1524,19 +1512,21 @@ router.patch('/askfunz', authenticate, async (req, res) => { let entra = false; if (!entra) { // If I change my record... - if ((!User.isAdmin(req.user.perm) && !User.isManager(req.user.perm) && - !User.isFacilitatore(req.user.perm)) && (req.user._id.toString() !== id)) { + if ( + !User.isAdmin(req.user.perm) && + !User.isManager(req.user.perm) && + !User.isFacilitatore(req.user.perm) && + req.user._id.toString() !== id + ) { // If without permissions, exit - return res.status(404). - send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' }); + return res.status(404).send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' }); } } if (mydata.myfunc === shared_consts.CallFunz.DAMMI_PRIMO_UTENTE_LIBERO) { const userfree = await Graduatoria.getFirstUserGradFree(idapp); - if (!!userfree) - return res.send({ code: server_constants.RIS_CODE_OK, out: userfree }); + if (!!userfree) return res.send({ code: server_constants.RIS_CODE_OK, out: userfree }); /*} else if (mydata.myfunc === shared_consts.CallFunz.GET_VALBYTABLE) { const mytable = globalTables.getTableByTableName(mydata.table); const coltoshow = { @@ -1559,7 +1549,6 @@ router.patch('/askfunz', authenticate, async (req, res) => { } return res.send({ code: server_constants.RIS_CODE_ERR }); - }); router.patch('/callfunz', authenticate, async (req, res) => { @@ -1574,17 +1563,22 @@ router.patch('/callfunz', authenticate, async (req, res) => { try { let entra = false; - if (mydata.myfunc === shared_consts.CallFunz.AGGIUNGI_NUOVO_IMBARCO || - mydata.myfunc === shared_consts.CallFunz.CANCELLA_IMBARCO) { + if ( + mydata.myfunc === shared_consts.CallFunz.AGGIUNGI_NUOVO_IMBARCO || + mydata.myfunc === shared_consts.CallFunz.CANCELLA_IMBARCO + ) { entra = true; } if (!entra) { // If I change my record... - if ((!User.isAdmin(req.user.perm) && !User.isManager(req.user.perm) && - !User.isFacilitatore(req.user.perm)) && (req.user._id.toString() !== id)) { + if ( + !User.isAdmin(req.user.perm) && + !User.isManager(req.user.perm) && + !User.isFacilitatore(req.user.perm) && + req.user._id.toString() !== id + ) { // If without permissions, exit - return res.status(404). - send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' }); + return res.status(404).send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' }); } } @@ -1593,24 +1587,22 @@ router.patch('/callfunz', authenticate, async (req, res) => { let fieldsvalue = {}; if (mydata.myfunc === shared_consts.CallFunz.ZOOM_GIA_PARTECIPATO) { - if (!!myuser.username) { - let FormDaMostrare = telegrambot.getFormDaMostrare(idapp, mydata.myfunc, - myuser); + let FormDaMostrare = telegrambot.getFormDaMostrare(idapp, mydata.myfunc, myuser); - await telegrambot.sendMsgTelegramToTheManagers(idapp, + await telegrambot.sendMsgTelegramToTheManagers( + idapp, `L\'utente ${myuser.name} ${myuser.surname} (${myuser.username}) ha detto di aver già visto lo Zoom di Benvenuto`, - false, FormDaMostrare); + false, + FormDaMostrare + ); - const ris = await User.findByIdAndUpdate(myuser.id, - { $set: { 'profile.ask_zoom_partecipato': true } }); - if (ris) - return res.send({ code: server_constants.RIS_CODE_OK, msg: '' }); + const ris = await User.findByIdAndUpdate(myuser.id, { $set: { 'profile.ask_zoom_partecipato': true } }); + if (ris) return res.send({ code: server_constants.RIS_CODE_OK, msg: '' }); } } return res.send({ code: server_constants.RIS_CODE_ERR }); - } catch (e) { console.log(e.message); res.status(400).send(); @@ -1621,8 +1613,7 @@ router.get('/copyfromapptoapp/:idapporig/:idappdest', async (req, res) => { const idapporig = req.params.idapporig; const idappdest = req.params.idappdest; const idcode = req.params.code; - if (!idapporig || !idappdest || (idcode !== 'ASD3429Kjgà#@cvX')) - res.status(400).send(); + if (!idapporig || !idappdest || idcode !== 'ASD3429Kjgà#@cvX') res.status(400).send(); const mytablesstr = ['settings', 'users', 'templemail', 'destnewsletter']; @@ -1635,12 +1626,11 @@ router.get('/copyfromapptoapp/:idapporig/:idappdest', async (req, res) => { await mytable.DuplicateAllRecords(idapporig, idappdest).then((numrec) => { // tools.mylogshow(' REC TO MODIFY: ', rec); - numrectot += numrec + numrectot += numrec; }); } res.send({ code: server_constants.RIS_CODE_OK, msg: '', numrectot }); - } catch (e) { tools.mylogserr('Error copyfromapptoapp: ', e); res.status(400).send(); @@ -1658,14 +1648,16 @@ router.delete('/delrec/:table/:id', authenticate, async (req, res) => { const mytable = globalTables.getTableByTableName(tablename); - const fields = { 'ALL': 1 }; + const fields = { ALL: 1 }; - if ((!User.isAdmin(req.user.perm) && !User.isManager(req.user.perm)) && - (tablename !== 'extralist') && - await !tools.ModificheConsentite(req, tablename, fields, id, req.user)) { + if ( + !User.isAdmin(req.user.perm) && + !User.isManager(req.user.perm) && + tablename !== 'extralist' && + (await !tools.ModificheConsentite(req, tablename, fields, id, req.user)) + ) { // If without permissions, exit - return res.status(404). - send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' }); + return res.status(404).send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' }); } let cancellato = false; @@ -1676,7 +1668,6 @@ router.delete('/delrec/:table/:id', authenticate, async (req, res) => { // if (!User.isAdmin(req.user.perm) && !User.isManager(req.user.perm)) { if (true) { if (tablename === 'users') { - let fieldsvalue = { deleted: true, date_deleted: new Date(), @@ -1687,18 +1678,18 @@ router.delete('/delrec/:table/:id', authenticate, async (req, res) => { idapp = utente.idapp; await mytable.findByIdAndUpdate(id, { $set: fieldsvalue }); - // ... - let text = `L\'utente ${utente.username} (${utente.name} ${utente.surname}) si è cancellato dal sito ` + tools.getNomeAppByIdApp(utente.idapp) + ` Deleted = true`; + let text = + `L\'utente ${utente.username} (${utente.name} ${utente.surname}) si è cancellato dal sito ` + + tools.getNomeAppByIdApp(utente.idapp) + + ` Deleted = true`; telegrambot.sendMsgTelegramToTheManagers(idapp, text); - } if (!User.isAdmin(req.user.perm)) { cancellato = true; return res.send({ code: server_constants.RIS_CODE_OK, msg: '' }); } - } } @@ -1706,35 +1697,37 @@ router.delete('/delrec/:table/:id', authenticate, async (req, res) => { if (!cancellato) { // ELIMINA VERAMENTE IL RECORD !!! - ris = await mytable.deleteOne({ _id: id }).then((rec) => { - if (!rec) { - // res.status(404).send(); - return false; - } + ris = await mytable + .deleteOne({ _id: id }) + .then((rec) => { + if (!rec) { + // res.status(404).send(); + return false; + } - if (tablename === shared_consts.TAB_MYGROUPS) { - // Se è un gruppo, allora cancella anche tutti i suoi riferimenti - User.removeAllUsersFromMyGroups(rec.idapp, rec.groupname); - } else if (tablename === shared_consts.TAB_MYCIRCUITS) { - // Se è un gruppo, allora cancella anche tutti i suoi riferimenti - User.removeAllUsersFromMyCircuits(rec.idapp, rec.name); - } else if (tablename === shared_consts.TAB_MYPAGES) { - // Cancella tutti gli elementi di quella pagina - MyElem.deleteAllFromThisPage(rec._id); - } + if (tablename === shared_consts.TAB_MYGROUPS) { + // Se è un gruppo, allora cancella anche tutti i suoi riferimenti + User.removeAllUsersFromMyGroups(rec.idapp, rec.groupname); + } else if (tablename === shared_consts.TAB_MYCIRCUITS) { + // Se è un gruppo, allora cancella anche tutti i suoi riferimenti + User.removeAllUsersFromMyCircuits(rec.idapp, rec.name); + } else if (tablename === shared_consts.TAB_MYPAGES) { + // Cancella tutti gli elementi di quella pagina + MyElem.deleteAllFromThisPage(rec._id); + } - tools.refreshAllTablesInMem(rec.idapp, tablename, true, rec.username); + tools.refreshAllTablesInMem(rec.idapp, tablename, true, rec.username); - cancellato = true; + cancellato = true; - tools.mylog('DELETED ', rec._id); + tools.mylog('DELETED ', rec._id); - return true; - - }).catch((e) => { - console.log(e.message); - res.status(400).send(); - }); + return true; + }) + .catch((e) => { + console.log(e.message); + res.status(400).send(); + }); } if (cancellato) { @@ -1747,7 +1740,6 @@ router.delete('/delrec/:table/:id', authenticate, async (req, res) => { res.send({ code: server_constants.RIS_CODE_ERR, msg: '' }); return ris; - }); router.post('/duprec/:table/:id', authenticate, async (req, res) => { @@ -1760,8 +1752,7 @@ router.post('/duprec/:table/:id', authenticate, async (req, res) => { const mytable = globalTables.getTableByTableName(tablename); if (!req.user) { - return res.status(404). - send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' }); + return res.status(404).send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' }); } /* if (!User.isAdmin(req.user.perm) && !User.isManager(req.user.perm)) { @@ -1771,35 +1762,31 @@ router.post('/duprec/:table/:id', authenticate, async (req, res) => { } */ return await mytable.findById(id).then(async (mydata) => { - const datadup = tools.CloneRecordToNew(mydata, mytable.modelName); const mynewrec = new mytable(datadup); - return await mynewrec.save().then(async (rec) => { - if (!rec) { - return res.status(404).send(); - } + return await mynewrec + .save() + .then(async (rec) => { + if (!rec) { + return res.status(404).send(); + } - tools.mylog('DUPLICATED ', rec); + tools.mylog('DUPLICATED ', rec); - - // Do extra things after deleted - return await actions.doOtherThingsAfterDuplicated(tablename, rec). - then(({ myrec }) => { + // Do extra things after deleted + return await actions.doOtherThingsAfterDuplicated(tablename, rec).then(({ myrec }) => { // ... mytable.findById(myrec._id).then((record) => { - return res.send( - { code: server_constants.RIS_CODE_OK, record, msg: '' }); + return res.send({ code: server_constants.RIS_CODE_OK, record, msg: '' }); }); - }); - - }).catch((e) => { - console.error(e.message); - res.status(400).send(); - }); + }) + .catch((e) => { + console.error(e.message); + res.status(400).send(); + }); }); - }); router.get('/loadsite/:userId/:idapp', authenticate_noerror_WithUserLean, (req, res) => { @@ -1808,8 +1795,10 @@ router.get('/loadsite/:userId/:idapp', authenticate_noerror_WithUserLean, (req, // Funzione di test per misurare le performance di MongoDB async function testMongoPerformance(ind, iterations = 20) { - let logString = ""; - const log = (msg) => { logString += msg + "\n"; }; + let logString = ''; + const log = (msg) => { + logString += msg + '\n'; + }; log(`Avvio del test ${ind} di performance MongoDB con ${iterations} iterazioni...`); @@ -1822,11 +1811,11 @@ async function testMongoPerformance(ind, iterations = 20) { if (ind === 1) { await User.findOne({}).lean(); } else { - const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiJQUk9WQU1TR0AxQSIsInNtYXJ0IjoiNjIwODAwYWRjMTI5ZDFlYmE3NjBiZWNiIiwiYWNjZXNzIjoiYXV0aCIsInVuIjoic3VyeWExOTc3IiwiaWF0IjoxNzQxODcyMzEwLCJleHAiOjE3NDE4Nzk1MTB9.SXJLmsS6EZVhaU7sUWYMnaqGpiiy8RfE9K43xTdxNuU'; + const token = + 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiJQUk9WQU1TR0AxQSIsInNtYXJ0IjoiNjIwODAwYWRjMTI5ZDFlYmE3NjBiZWNiIiwiYWNjZXNzIjoiYXV0aCIsInVuIjoic3VyeWExOTc3IiwiaWF0IjoxNzQxODcyMzEwLCJleHAiOjE3NDE4Nzk1MTB9.SXJLmsS6EZVhaU7sUWYMnaqGpiiy8RfE9K43xTdxNuU'; await User.findByToken(token, 'auth', true, true); } - } catch (err) { log(`Errore nell'iterazione ${i + 1}: ${err.message}`); } @@ -1850,7 +1839,6 @@ async function testMongoPerformance(ind, iterations = 20) { return { totalTime, averageTime, minTime, maxTime, timings, log: logString }; } - // Supponendo di usare Express e di avere già definito "router" router.get('/testpao', async (req, res) => { try { @@ -1859,12 +1847,11 @@ router.get('/testpao', async (req, res) => { const result = await testMongoPerformance(ind, numval); res.status(200).json({ log: result.log }); } catch (error) { - console.error("Errore nel test di performance:", error); + console.error('Errore nel test di performance:', error); res.status(500).json({ error: error.message }); } }); - router.get('/loadsite/:userId/:idapp/:vers', authenticate_noerror_WithUserLean, async (req, res) => { try { let versionstr = req.params.vers; @@ -1872,7 +1859,6 @@ router.get('/loadsite/:userId/:idapp/:vers', authenticate_noerror_WithUserLean, let version = tools.getVersionint(versionstr); return await load(req, res, version); - } catch (error) { console.error('Errore durante il caricamento del sito:', error); res.status(500).json({ error: 'Errore interno del server' }); @@ -1885,7 +1871,7 @@ async function measurePromises(promises) { const startTotal = process.hrtime(); // tempo iniziale totale // Avvolgo ogni promise per misurare il tempo - const wrappedPromises = keys.map(key => { + const wrappedPromises = keys.map((key) => { const promise = promises[key]; return (async () => { const start = process.hrtime(); // inizio timer per questa promise @@ -1918,7 +1904,6 @@ async function measurePromises(promises) { return { data, totalTime, slowCalls }; } - async function load(req, res, version = '0') { try { // console.log(' ... 1) richiesta LOAD'); @@ -1938,23 +1923,21 @@ async function load(req, res, version = '0') { const token = req.header('x-auth'); // Se non ho il token, vado cmq stato a 200 if (!token && status === server_constants.RIS_CODE_HTTP_INVALID_TOKEN) { - status = 200; + status = 200; } // Determina se l'utente ha determinati permessi - const gestoredelSito = req.user && - (User.isAdmin(req.user.perm) || User.isManager(req.user.perm) || User.isEditor(req.user.perm)) - ? '1' - : '0'; + const gestoredelSito = + req.user && (User.isAdmin(req.user.perm) || User.isManager(req.user.perm) || User.isEditor(req.user.perm)) + ? '1' + : '0'; const socioresidente = req.user && req.user.profile ? req.user.profile.socioresidente : false; - // Costruzione dell'oggetto delle promesse const promises = { - bookedevent: userId !== '0' - ? Booking.findAllByUserIdAndIdApp(userId, idapp, gestoredelSito) - : Promise.resolve([]), + bookedevent: + userId !== '0' ? Booking.findAllByUserIdAndIdApp(userId, idapp, gestoredelSito) : Promise.resolve([]), eventlist: MyEvent.findAllIdApp(socioresidente, idapp), operators: Operator.findAllIdApp(idapp), wheres: Where.findAllIdApp(idapp), @@ -1962,31 +1945,21 @@ async function load(req, res, version = '0') { settings: Settings.findAllIdApp(idapp, false, false), permissions: Permission.findAllIdApp(), disciplines: Discipline.findAllIdApp(idapp), - newstosent: gestoredelSito - ? Newstosent.findAllIdApp(idapp) - : Promise.resolve([]), + newstosent: gestoredelSito ? Newstosent.findAllIdApp(idapp) : Promise.resolve([]), mailinglist: Promise.resolve([]), - mypage: version > 91 - ? MyPage.findOnlyStruttRec(idapp) - : MyPage.findAllIdApp(idapp), - gallery: gestoredelSito - ? Gallery.findAllIdApp(idapp) - : Promise.resolve([]), + mypage: version > 91 ? MyPage.findOnlyStruttRec(idapp) : MyPage.findAllIdApp(idapp), + gallery: gestoredelSito ? Gallery.findAllIdApp(idapp) : Promise.resolve([]), paymenttype: PaymentType.findAllIdApp(idapp), - calcstat: req.user - ? User.calculateStat(idapp, req.user.username) - : Promise.resolve(null), + calcstat: req.user ? User.calculateStat(idapp, req.user.username) : Promise.resolve(null), calzoom: CalZoom.findAllIdApp(idapp), producers: Producer.findAllIdApp(idapp), - cart: req.user - ? Cart.getCartByUserId(req.user.id, idapp) - : Promise.resolve(null), + cart: req.user ? Cart.getCartByUserId(req.user.id, idapp) : Promise.resolve(null), storehouses: Storehouse.findAllIdApp(idapp), departments: Department.findAllIdApp(idapp), orderscart: req.user - ? (User.isManager(req.user.perm) + ? User.isManager(req.user.perm) ? OrdersCart.getOrdersCartByUserId('ALL', idapp, 0, false) - : OrdersCart.getOrdersCartByUserId(req.user.id, idapp, 0, false)) + : OrdersCart.getOrdersCartByUserId(req.user.id, idapp, 0, false) : Promise.resolve(null), groups: Group.findAllIdApp(idapp), resps: User.getusersRespList(idapp), @@ -2032,9 +2005,7 @@ async function load(req, res, version = '0') { tipoformato: version >= 91 ? T_WEB_TipiFormato.findAllIdApp() : Promise.resolve([]), crons: version >= 91 ? Cron.findAllIdApp() : Promise.resolve([]), raccoltacataloghis: version >= 91 ? RaccoltaCataloghi.findAllIdApp(idapp) : Promise.resolve([]), - myuserextra: req.user - ? User.addExtraInfo(idapp, req.user, version) - : Promise.resolve(null) + myuserextra: req.user ? User.addExtraInfo(idapp, req.user, version) : Promise.resolve(null), }; // Esecuzione parallela di tutte le promesse @@ -2086,7 +2057,7 @@ async function load(req, res, version = '0') { resps: data.resps, workers: data.workers, myuser, - internalpages: data.internalpages + internalpages: data.internalpages, }; } else { responseData = { @@ -2151,8 +2122,7 @@ async function load(req, res, version = '0') { crons: data.crons, raccoltacataloghis: data.raccoltacataloghis, }; - } - + } // console.log(' ... 2) load dati caricati ...'); res.status(status).send(responseData); @@ -2160,7 +2130,7 @@ async function load(req, res, version = '0') { console.error('Errore in load:', e); res.status(400).send({ error: e.message }); } -}; +} router.get(process.env.LINK_CHECK_UPDATES, authenticate_noerror, async (req, res) => { const idapp = req.query.idapp; @@ -2170,88 +2140,83 @@ router.get(process.env.LINK_CHECK_UPDATES, authenticate_noerror, async (req, res return res.status(200).send(); } - await CfgServer.find({ idapp }).then(async (arrcfgrec) => { + await CfgServer.find({ idapp }) + .then(async (arrcfgrec) => { + if (arrcfgrec.length === 0) { + if (User.isAdmin(req.user.perm)) { + // crea un nuovo record + const mycfgServer = new CfgServer(); + mycfgServer.idapp = idapp; + mycfgServer.chiave = 'vers'; + mycfgServer.userId = 'ALL'; + mycfgServer.valore = await tools.getVersServer(); - if (arrcfgrec.length === 0) { - if (User.isAdmin(req.user.perm)) { - // crea un nuovo record - const mycfgServer = new CfgServer(); - mycfgServer.idapp = idapp; - mycfgServer.chiave = 'vers'; - mycfgServer.userId = 'ALL'; - mycfgServer.valore = await tools.getVersServer(); + mycfgServer.save(); - mycfgServer.save(); - - arrcfgrec = await CfgServer.find({ idapp }) - } else { - return res.status(404).send(); - } - - } - - - // ++Add to Log Stat .... - - let last_msgs = null; - let last_notifs = null; - let last_notifcoins = null; - let usersList = null; - let last_notifcoins_inattesa = null; - // const sall = '0'; - - // msgs = SendMsg.findAllByUserIdAndIdApp(userId, req.user.username, req.user.idapp); - if (req.user) { - - const userId = req.user._id; - if (!ObjectId.isValid(userId)) { - return res.status(404).send(); - } - - last_msgs = SendMsg.findLastGroupByUserIdAndIdApp(userId, req.user.username, idapp); - last_notifs = SendNotif.findLastNotifsByUserIdAndIdApp(req.user.username, idapp, 40); - // Se sono il Gestore, le ricevo tutte quante: - if (User.isAdmin(req.user.perm)) { - last_notifcoins_inattesa = SendNotif.findAllNotifCoinsAllIdAndIdApp(idapp); - } else { - last_notifcoins_inattesa = SendNotif.findLastNotifCoinsByUserIdAndIdApp(req.user.username, idapp, 200, true); - } - last_notifcoins = SendNotif.findLastNotifCoinsByUserIdAndIdApp(req.user.username, idapp, 1, false); - - if (req.user) { - // If User is Admin, then send user Lists - if (User.isAdmin(req.user.perm) || User.isEditor(req.user.perm) || - User.isManager(req.user.perm)) { - - // Send UsersList - usersList = User.getUsersList(idapp); - // usersList = null; + arrcfgrec = await CfgServer.find({ idapp }); + } else { + return res.status(404).send(); } } - } - return Promise.all([usersList, last_msgs, last_notifs, last_notifcoins, last_notifcoins_inattesa]).then((arrdata) => { - // console.table(arrdata); - return res.send({ - CfgServer: arrcfgrec, - usersList: arrdata[0], - last_msgs: arrdata[1], - last_notifs: arrdata[2], - last_notifcoins: [...arrdata[4], ...arrdata[3]], - }); + // ++Add to Log Stat .... + + let last_msgs = null; + let last_notifs = null; + let last_notifcoins = null; + let usersList = null; + let last_notifcoins_inattesa = null; + // const sall = '0'; + + // msgs = SendMsg.findAllByUserIdAndIdApp(userId, req.user.username, req.user.idapp); + if (req.user) { + const userId = req.user._id; + if (!ObjectId.isValid(userId)) { + return res.status(404).send(); + } + + last_msgs = SendMsg.findLastGroupByUserIdAndIdApp(userId, req.user.username, idapp); + last_notifs = SendNotif.findLastNotifsByUserIdAndIdApp(req.user.username, idapp, 40); + // Se sono il Gestore, le ricevo tutte quante: + if (User.isAdmin(req.user.perm)) { + last_notifcoins_inattesa = SendNotif.findAllNotifCoinsAllIdAndIdApp(idapp); + } else { + last_notifcoins_inattesa = SendNotif.findLastNotifCoinsByUserIdAndIdApp(req.user.username, idapp, 200, true); + } + last_notifcoins = SendNotif.findLastNotifCoinsByUserIdAndIdApp(req.user.username, idapp, 1, false); + + if (req.user) { + // If User is Admin, then send user Lists + if (User.isAdmin(req.user.perm) || User.isEditor(req.user.perm) || User.isManager(req.user.perm)) { + // Send UsersList + usersList = User.getUsersList(idapp); + // usersList = null; + } + } + } + + return Promise.all([usersList, last_msgs, last_notifs, last_notifcoins, last_notifcoins_inattesa]).then( + (arrdata) => { + // console.table(arrdata); + return res.send({ + CfgServer: arrcfgrec, + usersList: arrdata[0], + last_msgs: arrdata[1], + last_notifs: arrdata[2], + last_notifcoins: [...arrdata[4], ...arrdata[3]], + }); + } + ); + }) + .catch((e) => { + console.log(e.message); + res.status(400).send({ code: server_constants.RIS_CODE_ERR, msg: e }); }); - - }).catch((e) => { - console.log(e.message); - res.status(400).send({ code: server_constants.RIS_CODE_ERR, msg: e }); - }); - }); router.post('/upload_from_other_server/:dir', authenticate, (req, res) => { // const dir = req.params.dir; // const idapp = req.user.idapp; - /* const form = new formidable.IncomingForm(); @@ -2308,166 +2273,58 @@ router.post('/upload_from_other_server/:dir', authenticate, (req, res) => { console.log('Error', e) } */ - }); -function uploadFile(req, res, version) { - // console.log('/upload dir:' + dir); +// Funzione principale che gestisce l'upload +async function uploadFile(req, res, version, options) { + quality = options?.quality || 'original'; const dir = tools.invertescapeslash(req.params.dir); - console.log('uploadFile = ', dir); const idapp = req.user.idapp; const form = new formidable.IncomingForm(); - form.parse(req); - let dirmain = '/statics'; - if (version > 0) { - if (tools.sulServer()) { - dirmain = ''; - } else { - dirmain = server_constants.DIR_PUBLIC_LOCALE; - } - } - + let dirmain = version > 0 && tools.sulServer() ? '' : server_constants.DIR_PUBLIC_LOCALE; const mydir2 = folder + '/' + dir; tools.mkdirpath(mydir2); form.uploadDir = mydir2; - try { + try { form.on('fileBegin', async function (name, file) { console.log('1) Uploading ' + file.originalFilename); const mydir = folder + '/' + file.newFilename; - // tools.mkdirpath(mydir); - file.path = mydir + file.path = mydir; }); form.on('file', async function (name, file) { try { console.log('2) Uploading ' + file.originalFilename); - const mydir = tools.getdirByIdApp(idapp) + dirmain + - server_constants.DIR_UPLOAD + '/' + dir; + const mydir = tools.getdirByIdApp(idapp) + dirmain + server_constants.DIR_UPLOAD + '/' + dir; + await tools.mkdirpath(mydir); - // console.log('mydir', mydir); + file.name = file.originalFilename; + const resized_img = mydir + server_constants.PREFIX_IMG + file.originalFilename; + const oldpath = file.newFilename; + const fromfile = '.' + server_constants.DIR_UPLOAD + '/' + dir + '/' + oldpath; + const tofile = '.' + server_constants.DIR_UPLOAD + '/' + dir + '/' + file.originalFilename; - // Create Dir if doesn't exist: - const rismk = await tools.mkdirpath(mydir); + + // Copia del file + await moveFile(fromfile, tofile, res); - let filename = file.originalFilename; - let ext = path.extname(filename); - - //++Todo: Modifica del nomefile... da passare al frontend - //if (mydir.includes('profile')) { - // filename = uuidv4() + ext; - //} - - file.name = filename; - let resized_img = mydir + '/' + server_constants.PREFIX_IMG + filename; - - oldpath = file.newFilename; - - - let fromfile = '.' + server_constants.DIR_UPLOAD + '/' + dir + '/' + oldpath; - let tofile = '.' + server_constants.DIR_UPLOAD + '/' + dir + '/' + file.originalFilename; - let mydircurrent = process.cwd() + '/src/server/router/upload/' + dir; - fromfile = mydircurrent + '/' + oldpath; - tofile = mydir + '/' + file.originalFilename; - - // ------------ - // ++TODO: Questo non funziona perché dovrei passargli il nomefile aggiornato a Vue.js - // tofile = tools.cleanFileName(tofile) - // ------------ - - let newname = tofile; - file.path = newname; - - console.log('fromfile', fromfile, 'tofile', tofile) - - - if (!tools.sulServer()) { - // Se faccio eseguire questo in Locale, lui mi fa l'aggiornamento della pagina, quindi poi non posso salvare! - // allora mi conviene che lo faccio dopo, manualmente. - - console.log('Dovresti copiare fromfile', fromfile, 'tofile', tofile); - console.log('sudo cp -R \'' + fromfile + '\' \'' + tofile + '\''); - await tools.execScriptNoOutput('sudo cp -R \'' + fromfile + '\' \'' + tofile + '\''); - // await tools.execScriptNoOutput('sudo cp -R ' + fromfile + ' ' + tofile) - res.end(); - return; - } - - - // Move in the folder application ! - await tools.move(fromfile, tofile, (err) => { - if (err) { - console.log('err uploadDir:', err); - res.status(400).send(); - } else { - - // Salva le immagini in formato compresso - try { - let resized_img_small = tools.extractFilePath(newname) + '/' + - server_constants.PREFIX_IMG_SMALL + - tools.extractFileName(newname); - // SMALL - - // questa opzione 'failOnError' serve per risolvere l'errore (Error: VipsJpeg: Invalid SOS parameters for sequential JPEG - sharp(newname, { failOnError: false }). - resize(64, 64). - withMetadata(). - toFile(resized_img_small); - - // MEDIUM - let resized_img = tools.extractFilePath(newname) + '/' + server_constants.PREFIX_IMG + tools.extractFileName(newname); - sharp(newname, { failOnError: false }). - resize({ - width: 512, - // height: 512, - //fit: sharp.fit.cover, - fit: sharp.fit.contain, - // position: sharp.strategy.entropy, - }).withMetadata().toFile(resized_img, async function (err) { - - // console.log('3) Ridimensionata Immagine ' + newname, 'in', resized_img); - - if (await tools.isFileExistsAsync(resized_img)) { - // console.log('4) Cancella l \'immagine grande originale:', newname); - // DELETE THE ORIGINAL BIG - tools.delete(newname, false, () => { }); - - // console.log('5) Rinomina l\'immagine Media da', resized_img, 'a:', newname); - // RENAME THE MEDIUM IN THE ORIGINAL NAME - tools.move(resized_img, newname, (err) => { - if (err) - console.error('err', err); - else - console.log('move', newname); - }); - } - - if (err) - console.error('Error Upload: ', err); - }); - } catch (e) { - console.error('Error Upload(2) ', e); - } - } - - res.end(); - // console.log('res.end'); - // return res.send({filename: newname }); - - }); + // Ridimensionamento immagine + await handleImageResizing(tofile, quality); + res.end(); } catch (e) { - console.log('error', e); + console.log('Error during file processing: ', e); res.status(400).send(); } }); form.on('end', function () { - console.log('-> upload done'); + console.log('-> Upload completed'); }); form.on('aborted', () => { @@ -2476,18 +2333,71 @@ function uploadFile(req, res, version) { }); form.on('error', (err) => { - console.error('Error Uploading', err); + console.error('Error Uploading', err?.message); res.status(400).send(); }); - } catch (e) { console.log('Error', e); } } -router.post('/upload/:dir', authenticate, (req, res) => { - return uploadFile(req, res, 0); +// Funzione per muovere il file nella destinazione finale +async function moveFile(fromfile, tofile, res) { + console.log('Moving file from ' + fromfile + ' to ' + tofile); + try { + if (!tools.sulServer()) { + console.log('Copying file (locally):', fromfile, 'to', tofile); + await tools.execScriptNoOutput("sudo cp -R '" + fromfile + "' '" + tofile + "'"); + res.end(); + return; + } + await tools.move(fromfile, tofile); + } catch (error) { + console.log('Error moving file:', error); + res.status(400).send(); + } +} +// Funzione per gestire il ridimensionamento dell'immagine +async function handleImageResizing(filePath, quality) { + const resizedImgPath = + tools.extractFilePath(filePath) + '/' + server_constants.PREFIX_IMG + tools.extractFileName(filePath); + const resizedSmallPath = + tools.extractFilePath(filePath) + '/' + server_constants.PREFIX_IMG_SMALL + tools.extractFileName(filePath); + + try { + // Ridimensionamento per la qualità "small" + + if (quality === 'small' || quality === 'both') { + await resizeImage(filePath, resizedSmallPath, 64, 64); + } + + // Ridimensionamento per la qualità "medium" + if (quality === 'medium' || quality === 'both') { + await resizeImage(filePath, resizedImgPath, 512, 512); + } + + // Se la qualità è "original", non fare il ridimensionamento + if (quality === 'original') { + console.log('Keeping original size for image: ' + filePath); + return; + } + } catch (err) { + console.error('Error resizing image: ', err); + } +} + +// Funzione per ridimensionare l'immagine +async function resizeImage(inputPath, outputPath, width, height) { + try { + await sharp(inputPath).resize(width, height, { fit: sharp.fit.contain }).withMetadata().toFile(outputPath); + console.log('Image resized to ' + width + 'x' + height + ' and saved as ' + outputPath); + } catch (err) { + console.error('Error resizing image:', err); + } +} +router.post('/upload/:dir', authenticate, (req, res) => { + return uploadFile(req, res, 0, req.body.options); }); router.post('/uploadnew/:vers/:dir/', authenticate, (req, res) => { @@ -2495,27 +2405,24 @@ router.post('/uploadnew/:vers/:dir/', authenticate, (req, res) => { let version = tools.getVersionint(versionstr); try { - return uploadFile(req, res, version); - + return uploadFile(req, res, version, req.body.options); } catch (e) { console.log('error', e); res.status(400).send(); } - }); -router.delete('/delfile/:vers', authenticate, (req, res) => { +router.delete('/delfile/:vers', authenticate, async (req, res) => { let versionstr = req.params.vers; let version = tools.getVersionint(versionstr); - deleteFile(req, res, version); + await deleteFile(req, res, version); }); -router.delete('/delfile', authenticate, (req, res) => { - deleteFile(req, res, 0); +router.delete('/delfile', authenticate, async (req, res) => { + await deleteFile(req, res, 0); }); - -function deleteFile(req, res, version) { +async function deleteFile(req, res, version) { const relativefile = req.query.filename; const idapp = req.user.idapp; @@ -2534,23 +2441,19 @@ function deleteFile(req, res, version) { try { console.log('Delete file ' + relativefile); // ++ Move in the folder application ! - let fullpathfile = tools.getdirByIdApp(idapp) + dirmain + '/' + - relativefile.replace(/^\//, ''); + let fullpathfile = tools.getdirByIdApp(idapp) + dirmain + '/' + relativefile.replace(/^\//, ''); - tools.delete(fullpathfile, true, (err) => { + await tools.delete(fullpathfile, true, (err) => { if (err) console.log('err', err); - if (err === undefined || err.errno === -2) - return res.send({ code: server_constants.RIS_CODE_OK, msg: '' }); + if (err === undefined || err.errno === -2) return res.send({ code: server_constants.RIS_CODE_OK, msg: '' }); }); - } catch (e) { - console.log('error', e); + console.log('error', e?.message); res.status(400).send(); } } catch (e) { - console.log('Error', e); + console.log('Error', e?.message); } - } module.exports = router; diff --git a/src/server/tools/general.js b/src/server/tools/general.js index 8256f99..25b31fe 100755 --- a/src/server/tools/general.js +++ b/src/server/tools/general.js @@ -546,6 +546,15 @@ module.exports = { FIRST_PROJ: '__PROJECTS', EXECUTE_CALCPROJ: true, + isDirectoryAsync: async function (dir) { + try { + const stats = await fs.promises.stat(dir); + return stats.isDirectory(); + } catch (e) { + return false; + } + }, + isFileExistsAsync: async function (filename) { try { let fileExists = await fs.promises @@ -3999,33 +4008,40 @@ module.exports = { async deleteFile(filePath) { try { await fs.promises.unlink(filePath); - console.log(`File eliminato con successo: ${filePath}`); + // console.log(`File eliminato con successo: ${filePath}`); } catch (err) { console.error(`Errore durante l'eliminazione del file: ${filePath}`, err); throw err; } }, - delete(mypath, alsothumb, callback) { - fs.unlink(mypath, function (err) { - if (alsothumb) { - try { - let img_small = path.dirname(mypath) + '/' + server_constants.PREFIX_IMG_SMALL + path.basename(mypath); - fs.unlink(img_small, function (err) { - if (err) console.log('Errore durante la Cancellazione del file', mypath); - else console.log('deleted file', mypath); - }); - } catch (e) { - console.error(err); + async delete(mypath, alsothumb, callback) { + try { + if (await this.isFileExistsAsync(mypath)) { + await fs.promises.unlink(mypath); + // console.log(`deleted file ${mypath}`); + if (alsothumb) { + let img_small = ''; + try { + img_small = path.dirname(mypath) + '/' + server_constants.PREFIX_IMG_SMALL + path.basename(mypath); + if (await this.isFileExistsAsync(img_small)) { + await fs.promises.unlink(img_small); + console.log(`deleted file ${img_small}`); + } else { + // console.warn(`File not found: ${img_small}`); + } + console.log(`deleted file ${img_small}`); + } catch (e) { + console.error(`Error deleting file ${img_small}`, e?.message); + } } } - if (err) { - console.error(err); - callback(err); - return; - } - callback(); - }); + } catch (e) { + console.error(`Error deleting file ${mypath}`, e?.message); + callback(e); + return; + } + callback(); }, async mkdirpath(dirPath) { @@ -5974,7 +5990,6 @@ module.exports = { } } - let fileesistente = false; if (productInfo.imagefile) { // controlla se esiste il file @@ -6102,12 +6117,14 @@ module.exports = { removePathDirByFileName(idapp, fullfilename) { const mydir = this.getdirByIdApp(idapp); - - // ++ remove mydir from fullfilename and add myhost to generate a URL - const filename = fullfilename.replace(mydir, '').replace(/\\/g, '/'); // Replace backslashes with slashes + let filename = fullfilename.replace(mydir, '').replace(/\\/g, '/'); // Sostituisce backslash con slash + // Rimuove la barra iniziale se presente + if (filename.startsWith('/')) { + filename = filename.substring(1); + } return filename; }, - + isDateValid(mydate) { try { return ( @@ -6117,4 +6134,13 @@ module.exports = { return false; } }, + + aggiungiSuffissoAlNomeFile(filePath, suffisso) { + const dir = path.dirname(filePath); + const estensione = path.extname(filePath); + const nomeFile = path.basename(filePath, estensione); + + const nuovoNomeFile = nomeFile + suffisso + estensione; + return path.join(dir, nuovoNomeFile); + }, }; diff --git a/src/server/tools/shared_nodejs.js b/src/server/tools/shared_nodejs.js index 54c35ac..88b5bd2 100755 --- a/src/server/tools/shared_nodejs.js +++ b/src/server/tools/shared_nodejs.js @@ -1219,8 +1219,10 @@ module.exports = { END_NORMALLY: 1, END_WITHERROR: -50, TOOLONGTIME: -10, - } + }, // Download, DVD, Epub, Mobi, Nuovo, PDF, Streaming, Usato + PUNTI_PER_POLLICE: 96 + };