- generazione del PDF riscritto totalmente
- ora è possibile generarlo anche da backend - FIX: corretto la qualità del PDF e la dimensione non esatta in pixel...
This commit is contained in:
@@ -21,7 +21,8 @@ const authenticateMiddleware = async (req, res, next, withUser = false, lean = f
|
||||
req.user = null;
|
||||
req.token = null;
|
||||
req.code = server_constants.RIS_CODE_HTTP_INVALID_TOKEN;
|
||||
console.log(` ## ${logPrefix}_TOKEN INVALIDO ❌ ...`);
|
||||
if (!noError)
|
||||
console.log(` ## ${logPrefix}_TOKEN INVALIDO ❌ ...`);
|
||||
return noError ? next() : res.status(req.code).send();
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
const mongoose = require('mongoose').set('debug', false)
|
||||
const mongoose = require('mongoose').set('debug', false);
|
||||
const Schema = mongoose.Schema;
|
||||
|
||||
const tools = require('../tools/general');
|
||||
@@ -6,102 +6,91 @@ const { ObjectId } = require('mongodb');
|
||||
|
||||
const { MySchedaSchema, IDimensioni, IImg, IText, IAreaDiStampa } = require('../models/myscheda');
|
||||
|
||||
|
||||
mongoose.Promise = global.Promise;
|
||||
mongoose.level = "F";
|
||||
|
||||
mongoose.level = 'F';
|
||||
|
||||
// Resolving error Unknown modifier: $pushAll
|
||||
mongoose.plugin(schema => {
|
||||
schema.options.usePushEach = true
|
||||
mongoose.plugin((schema) => {
|
||||
schema.options.usePushEach = true;
|
||||
});
|
||||
|
||||
const IElementiPagina = new Schema({
|
||||
isTemplate: Boolean,
|
||||
linkIdTemplate: String,
|
||||
linkIdTemplatePerStampa: String,
|
||||
name: String,
|
||||
pagina: IDimensioni,
|
||||
});
|
||||
|
||||
const myCard = new Schema(
|
||||
{
|
||||
imagefile: String,
|
||||
vers_img: Number,
|
||||
alt: String,
|
||||
description: String,
|
||||
style: String,
|
||||
size: String,
|
||||
color: String,
|
||||
content: String,
|
||||
colorsub: String,
|
||||
link: String,
|
||||
}
|
||||
)
|
||||
const animation = new Schema(
|
||||
{
|
||||
name: String,
|
||||
clduration: String,
|
||||
cldelay: String,
|
||||
timingtype: String,
|
||||
}
|
||||
);
|
||||
const myCard = new Schema({
|
||||
imagefile: String,
|
||||
vers_img: Number,
|
||||
alt: String,
|
||||
description: String,
|
||||
style: String,
|
||||
size: String,
|
||||
color: String,
|
||||
content: String,
|
||||
colorsub: String,
|
||||
link: String,
|
||||
});
|
||||
const animation = new Schema({
|
||||
name: String,
|
||||
clduration: String,
|
||||
cldelay: String,
|
||||
timingtype: String,
|
||||
});
|
||||
|
||||
const elemText = new Schema(
|
||||
{
|
||||
text: String,
|
||||
color: String,
|
||||
class: String,
|
||||
size: String,
|
||||
anim: animation,
|
||||
}
|
||||
);
|
||||
const elemText = new Schema({
|
||||
text: String,
|
||||
color: String,
|
||||
class: String,
|
||||
size: String,
|
||||
anim: animation,
|
||||
});
|
||||
|
||||
const catalogo = new Schema({
|
||||
//++AddCATALOGO_FIELDS
|
||||
idCatalogSel: { type: String },
|
||||
productTypes: [{ type: Number }],
|
||||
excludeproductTypes: [{ type: Number }],
|
||||
editore: [{ type: String }],
|
||||
argomenti: [{ type: String }],
|
||||
idCollane: [{ type: String }],
|
||||
idTipologia: [{ type: Number }],
|
||||
idTipoFormato: [{ type: Number }],
|
||||
sort_field: { type: String },
|
||||
sort_dir: { type: Number },
|
||||
pdf: { type: Boolean },
|
||||
pdf_filename: { type: String },
|
||||
printable: { type: Boolean },
|
||||
indebug: { type: Boolean },
|
||||
maxnumlibri: { type: Number },
|
||||
showListaArgomenti: { type: Boolean },
|
||||
showOnlyCatalogoPDF: { type: Boolean },
|
||||
showListaCollane: { type: Boolean },
|
||||
|
||||
const catalogo = new Schema(
|
||||
{
|
||||
//++AddCATALOGO_FIELDS
|
||||
productTypes: [{ type: Number }],
|
||||
excludeproductTypes: [{ type: Number }],
|
||||
editore: [{ type: String }],
|
||||
argomenti: [{ type: String }],
|
||||
idCollane: [{ type: String }],
|
||||
idTipologia: [{ type: Number }],
|
||||
idTipoFormato: [{ type: Number }],
|
||||
sort_field: { type: String },
|
||||
sort_dir: { type: Number },
|
||||
pdf: { type: Boolean },
|
||||
pdf_filename: { type: String },
|
||||
printable: { type: Boolean },
|
||||
indebug: { type: Boolean },
|
||||
maxnumlibri: { type: Number },
|
||||
showListaArgomenti: { type: Boolean},
|
||||
showListaCollane: { type: Boolean},
|
||||
first_page: IDimensioni,
|
||||
last_page: IDimensioni,
|
||||
areadistampa: IAreaDiStampa,
|
||||
|
||||
first_page: IDimensioni,
|
||||
last_page: IDimensioni,
|
||||
areadistampa: IAreaDiStampa,
|
||||
print_isTemplate: Boolean,
|
||||
print_linkIdTemplate: String,
|
||||
|
||||
print_isTemplate: Boolean,
|
||||
print_linkIdTemplate: String,
|
||||
print_linkIdTemplatePerStampa: String,
|
||||
dimensioni_def: IElementiPagina,
|
||||
|
||||
dimensioni_def: IElementiPagina,
|
||||
|
||||
// -------------------
|
||||
arrSchede: [
|
||||
{
|
||||
scheda: MySchedaSchema,
|
||||
order: { type: Number },
|
||||
numPagineMax: { type: Number },
|
||||
/*arrProdToShow: {
|
||||
// -------------------
|
||||
arrSchede: [
|
||||
{
|
||||
scheda: MySchedaSchema,
|
||||
order: { type: Number },
|
||||
numPagineMax: { type: Number },
|
||||
/*arrProdToShow: {
|
||||
type: [[mongoose.Schema.Types.Mixed]], // Definizione tipo
|
||||
select: false // Imposta il campo come non selezionabile
|
||||
},*/
|
||||
}
|
||||
],
|
||||
}
|
||||
);
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const MyElemSchema = new Schema({
|
||||
idapp: {
|
||||
@@ -245,25 +234,25 @@ const MyElemSchema = new Schema({
|
||||
list: [
|
||||
{
|
||||
imagefile: {
|
||||
type: String
|
||||
type: String,
|
||||
},
|
||||
vers_img: {
|
||||
type: Number,
|
||||
},
|
||||
order: {
|
||||
type: Number
|
||||
type: Number,
|
||||
},
|
||||
alt: {
|
||||
type: String
|
||||
type: String,
|
||||
},
|
||||
description: {
|
||||
type: String
|
||||
}
|
||||
}
|
||||
type: String,
|
||||
},
|
||||
},
|
||||
],
|
||||
date_created: {
|
||||
type: Date,
|
||||
default: Date.now
|
||||
default: Date.now,
|
||||
},
|
||||
date_updated: {
|
||||
type: Date,
|
||||
@@ -279,8 +268,10 @@ MyElemSchema.pre('save', async function (next) {
|
||||
});
|
||||
|
||||
MyElemSchema.statics.getFieldsForSearch = function () {
|
||||
return [{ field: 'title', type: tools.FieldType.string },
|
||||
{ field: 'content', type: tools.FieldType.string }]
|
||||
return [
|
||||
{ field: 'title', type: tools.FieldType.string },
|
||||
{ field: 'content', type: tools.FieldType.string },
|
||||
];
|
||||
};
|
||||
|
||||
MyElemSchema.statics.executeQueryTable = function (idapp, params, user) {
|
||||
@@ -300,7 +291,7 @@ MyElemSchema.statics.SetIdPageInsteadThePah = async function (idapp) {
|
||||
|
||||
// Utilizza una mappa per accoppiare i path con i loro Id
|
||||
const pathToIdMap = {};
|
||||
pages.forEach(page => {
|
||||
pages.forEach((page) => {
|
||||
pathToIdMap[page.path] = page._id; // Mappa il path all'ID del documento MyPage
|
||||
});
|
||||
|
||||
@@ -315,7 +306,7 @@ MyElemSchema.statics.SetIdPageInsteadThePah = async function (idapp) {
|
||||
idPage: id,
|
||||
oldpath: path,
|
||||
},
|
||||
$unset: { path: "" } // Rimuove il campo path
|
||||
$unset: { path: '' }, // Rimuove il campo path
|
||||
} // Imposta IdPage all'ID del documento corrispondente
|
||||
);
|
||||
}
|
||||
@@ -324,7 +315,7 @@ MyElemSchema.statics.SetIdPageInsteadThePah = async function (idapp) {
|
||||
if (false) {
|
||||
// Utilizza una mappa per accoppiare i path con i loro Id
|
||||
const pathToIdMap2 = {};
|
||||
pages.forEach(page => {
|
||||
pages.forEach((page) => {
|
||||
pathToIdMap2[page.path] = page._id.toString(); // Mappa il path all'ID del documento MyPage
|
||||
});
|
||||
|
||||
@@ -333,7 +324,7 @@ MyElemSchema.statics.SetIdPageInsteadThePah = async function (idapp) {
|
||||
await MyElem.updateMany(
|
||||
{ oldpath: path }, // Condizione per aggiornare dove il path corrisponde
|
||||
{
|
||||
$unset: { idPage: "" } // Rimuove il campo path
|
||||
$unset: { idPage: '' }, // Rimuove il campo path
|
||||
} // Imposta IdPage all'ID del documento corrispondente
|
||||
);
|
||||
}
|
||||
@@ -342,14 +333,14 @@ MyElemSchema.statics.SetIdPageInsteadThePah = async function (idapp) {
|
||||
await MyElem.updateMany(
|
||||
{ oldpath: oldpath }, // Condizione per aggiornare dove il path corrisponde
|
||||
{
|
||||
$set: { idPage: id }
|
||||
$set: { idPage: id },
|
||||
} // Imposta IdPage all'ID del documento corrispondente
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const pathToIdMap2 = {};
|
||||
pages.forEach(page => {
|
||||
pages.forEach((page) => {
|
||||
pathToIdMap2[page.path] = page._id.toString(); // Mappa il path all'ID del documento MyPage
|
||||
});
|
||||
|
||||
@@ -358,26 +349,23 @@ MyElemSchema.statics.SetIdPageInsteadThePah = async function (idapp) {
|
||||
{ idapp },
|
||||
{ oldpath: oldpath }, // Condizione per aggiornare dove il path corrisponde
|
||||
{
|
||||
$set: { idPage: id }
|
||||
$set: { idPage: id },
|
||||
} // Imposta IdPage all'ID del documento corrispondente
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
console.log('Aggiornamenti effettuati con successo.');
|
||||
return 'Aggiornamenti effettuati con successo.';
|
||||
} catch (error) {
|
||||
console.error('Errore durante l\'aggiornamento:', error);
|
||||
return 'Errore durante l\'aggiornamento:', error;
|
||||
console.error("Errore durante l'aggiornamento:", error);
|
||||
return "Errore durante l'aggiornamento:", error;
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
MyElemSchema.statics.deleteAllFromThisPage = async function (id) {
|
||||
const MyElem = this;
|
||||
|
||||
return MyElem.deleteMany({ idPage: id });
|
||||
|
||||
};
|
||||
MyElemSchema.statics.findAllIdApp = async function (idapp) {
|
||||
const MyElem = this;
|
||||
@@ -405,17 +393,16 @@ MyElemSchema.statics.findAllIdApp = async function (idapp) {
|
||||
|
||||
async function deleteOldMyElems(idapp) {
|
||||
try {
|
||||
|
||||
const { MyPage } = require('../models/mypage');
|
||||
|
||||
// 1. Recupera tutti gli _id dalle pagine
|
||||
const existingPages = await MyPage.find({idapp}).select('_id').lean();
|
||||
const existingPageIds = existingPages.map(page => page._id.toString());
|
||||
const existingPages = await MyPage.find({ idapp }).select('_id').lean();
|
||||
const existingPageIds = existingPages.map((page) => page._id.toString());
|
||||
|
||||
// 2. Trova gli MyElem che hanno idPage non esistenti in MyPage
|
||||
const elemsToDelete = await MyElem.find({
|
||||
idapp,
|
||||
idPage: { $nin: existingPageIds }
|
||||
idPage: { $nin: existingPageIds },
|
||||
});
|
||||
|
||||
if (elemsToDelete.length > 0) {
|
||||
@@ -446,24 +433,22 @@ MyElemSchema.statics.findallSchedeTemplate = async function (idapp) {
|
||||
const MyElem = this;
|
||||
|
||||
try {
|
||||
|
||||
const { MyPage } = require('../models/mypage');
|
||||
|
||||
const ris = await MyElem.find({ idapp }).lean();
|
||||
|
||||
const schedeTemplate = ris.flatMap(elem =>
|
||||
elem.catalogo && elem.catalogo.arrSchede ?
|
||||
elem.catalogo.arrSchede
|
||||
.filter(scheda => scheda.scheda?.isTemplate)
|
||||
.map(scheda => ({
|
||||
...scheda, // mantieni i dati originali della scheda
|
||||
idPageOrig: elem.idPage // aggiungi l'idPage
|
||||
}))
|
||||
const schedeTemplate = ris.flatMap((elem) =>
|
||||
elem.catalogo && elem.catalogo.arrSchede
|
||||
? elem.catalogo.arrSchede
|
||||
.filter((scheda) => scheda.scheda?.isTemplate)
|
||||
.map((scheda) => ({
|
||||
...scheda, // mantieni i dati originali della scheda
|
||||
idPageOrig: elem.idPage, // aggiungi l'idPage
|
||||
}))
|
||||
: []
|
||||
);
|
||||
|
||||
if (idapp === '18') {
|
||||
|
||||
const duplicateIds = schedeTemplate.reduce((acc, scheda) => {
|
||||
const id = scheda.scheda._id; // Ottieni l'ID della scheda
|
||||
if (!acc[id]) {
|
||||
@@ -479,7 +464,7 @@ MyElemSchema.statics.findallSchedeTemplate = async function (idapp) {
|
||||
.map(([id, pages]) => ({ id, pages })); // Ottieni ID e pagine corrispondenti
|
||||
|
||||
// Recupera i dettagli delle pagine
|
||||
const pageIds = duplicates.flatMap(dup => dup.pages); // Estrai tutti gli idPage
|
||||
const pageIds = duplicates.flatMap((dup) => dup.pages); // Estrai tutti gli idPage
|
||||
const pages = await MyPage.find({ idapp, _id: { $in: pageIds } }).lean();
|
||||
|
||||
// Crea una mappatura tra idPage e title
|
||||
@@ -489,19 +474,18 @@ MyElemSchema.statics.findallSchedeTemplate = async function (idapp) {
|
||||
}, {});
|
||||
|
||||
// Associa i titoli delle pagine agli ID duplicati
|
||||
const resultWithTitles = duplicates.map(dup => ({
|
||||
const resultWithTitles = duplicates.map((dup) => ({
|
||||
id: dup.id,
|
||||
pages: dup.pages.map(_id => ({
|
||||
pages: dup.pages.map((_id) => ({
|
||||
_id,
|
||||
title: pageMap[_id] || 'Titolo non trovato' // Usa la mappatura per trovare il titolo
|
||||
}))
|
||||
title: pageMap[_id] || 'Titolo non trovato', // Usa la mappatura per trovare il titolo
|
||||
})),
|
||||
}));
|
||||
|
||||
if (resultWithTitles.length > 0) {
|
||||
console.log('Duplicati e titoli delle pagine:', JSON.stringify(resultWithTitles, null, 2));
|
||||
await deleteOldMyElems(idapp);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return schedeTemplate;
|
||||
@@ -511,13 +495,13 @@ MyElemSchema.statics.findallSchedeTemplate = async function (idapp) {
|
||||
};
|
||||
|
||||
/**
|
||||
* Ricerca tra tutte le schede, contenute in catalogo, se esiste un nome di template uguale,
|
||||
* Ricerca tra tutte le schede, contenute in catalogo, se esiste un nome di template uguale,
|
||||
* se non lo trova allora è quello giusto per crearne uno nuovo
|
||||
*
|
||||
*
|
||||
* @param {string} idapp - ID dell'app
|
||||
* @param {string} idPageOrig - ID della pagina originale
|
||||
* @param {string} nomeTemplate - Nome del template
|
||||
*
|
||||
*
|
||||
* @returns {string} Il nome del template libero
|
||||
*/
|
||||
MyElemSchema.statics.getNewFreeNameTemplate = async function (idapp, idPageOrig, nomeTemplate) {
|
||||
@@ -529,23 +513,23 @@ MyElemSchema.statics.getNewFreeNameTemplate = async function (idapp, idPageOrig,
|
||||
{
|
||||
idapp,
|
||||
'catalogo.arrSchede.scheda.isTemplate': true,
|
||||
'catalogo.arrSchede.scheda.idPage': { $ne: idPageOrig }
|
||||
'catalogo.arrSchede.scheda.idPage': { $ne: idPageOrig },
|
||||
},
|
||||
{
|
||||
'catalogo.arrSchede.scheda.name': 1,
|
||||
'catalogo.arrSchede.scheda.isTemplate': 1,
|
||||
'catalogo.arrSchede.scheda.isPagIntro': 1,
|
||||
'catalogo.arrSchede.scheda.idPage': 1
|
||||
});
|
||||
'catalogo.arrSchede.scheda.idPage': 1,
|
||||
}
|
||||
);
|
||||
|
||||
// Recupera i nomi dei template già esistenti
|
||||
const existingNames = new Set(
|
||||
ris.flatMap(elem =>
|
||||
elem.catalogo?.arrSchede?.filter(scheda =>
|
||||
scheda.scheda?.isTemplate &&
|
||||
scheda.scheda?.idPage !== idPageOrig
|
||||
)
|
||||
.map(scheda => scheda.scheda?.name) || []
|
||||
ris.flatMap(
|
||||
(elem) =>
|
||||
elem.catalogo?.arrSchede
|
||||
?.filter((scheda) => scheda.scheda?.isTemplate && scheda.scheda?.idPage !== idPageOrig)
|
||||
.map((scheda) => scheda.scheda?.name) || []
|
||||
)
|
||||
);
|
||||
|
||||
@@ -568,8 +552,9 @@ MyElemSchema.statics.getNewFreeNameTemplate = async function (idapp, idPageOrig,
|
||||
const MyElem = mongoose.model('MyElem', MyElemSchema);
|
||||
|
||||
MyElem.createIndexes()
|
||||
.then(() => { })
|
||||
.catch((err) => { throw err; });
|
||||
|
||||
.then(() => {})
|
||||
.catch((err) => {
|
||||
throw err;
|
||||
});
|
||||
|
||||
module.exports = { MyElem };
|
||||
|
||||
@@ -140,6 +140,9 @@ const MyPageSchema = new Schema({
|
||||
sottoMenu: [{
|
||||
type: String
|
||||
}],
|
||||
hideHeader: {
|
||||
type: Boolean,
|
||||
},
|
||||
date_created: {
|
||||
type: Date,
|
||||
default: Date.now
|
||||
|
||||
@@ -65,10 +65,13 @@ const IAreaDiStampa = new Schema({
|
||||
margini: IBorders,
|
||||
unit: String,
|
||||
format: [{ type: Number }],
|
||||
format_printable: [{ type: Number }],
|
||||
orientation: String,
|
||||
compress: Boolean,
|
||||
scale: Number,
|
||||
scale_printable: Number,
|
||||
scalex: Number,
|
||||
scaley: Number,
|
||||
scale_printablex: Number,
|
||||
scale_printabley: Number,
|
||||
scalecanvas: Number,
|
||||
});
|
||||
|
||||
@@ -116,7 +119,8 @@ const scheletroScheda = {
|
||||
isTemplate: { type: Boolean },
|
||||
isPagIntro: { type: Boolean },
|
||||
linkIdTemplate: { type: String },
|
||||
linkIdTemplatePerStampa: { type: String },
|
||||
scalexscheda: Number,
|
||||
scaleyscheda: Number,
|
||||
name: { type: String },
|
||||
numschede_perRiga: { type: Number },
|
||||
numschede_perCol: { type: Number },
|
||||
|
||||
@@ -30,6 +30,7 @@ const { Circuit } = require('../models/circuit');
|
||||
const { Province } = require('../models/province');
|
||||
const { City } = require('../models/city');
|
||||
const { Account } = require('../models/account');
|
||||
const { Catalog } = require('../models/catalog');
|
||||
|
||||
const Macro = require('../modules/Macro');
|
||||
|
||||
@@ -37,71 +38,91 @@ class CronMod {
|
||||
constructor() {}
|
||||
|
||||
async eseguiDbOp(idapp, mydata, req, res) {
|
||||
|
||||
let ris = await User.DbOp(idapp, mydata);
|
||||
|
||||
mydata.idapp = idapp;
|
||||
|
||||
const populate = require("../populate/populate");
|
||||
const populate = require('../populate/populate');
|
||||
|
||||
const globalTables = require("../tools/globalTables");
|
||||
const { Reaction } = require("../models/reaction");
|
||||
const globalTables = require('../tools/globalTables');
|
||||
const { Reaction } = require('../models/reaction');
|
||||
|
||||
const AmazonBookScraper = require('../modules/Scraping');
|
||||
|
||||
let mystr = "";
|
||||
const GenPdf = require('../modules/GenPdf');
|
||||
|
||||
let mystr = '';
|
||||
|
||||
try {
|
||||
if (mydata.dbop === "") {
|
||||
if (mydata.dbop === '') {
|
||||
// } else if (mydata.dbop === 'rigeneraTutto') {
|
||||
// await ListaIngresso.Esegui_CronTab(idapp, mydata);
|
||||
} else if (mydata.dbop === "ScraperMultipleDataAmazon") {
|
||||
mystr = await AmazonBookScraper.ScraperMultipleDataAmazon(idapp, {update: true, aggiornasoloSeVuoti: true, forzaricarica: false});
|
||||
} else if (mydata.dbop === 'ScraperMultipleDataAmazon') {
|
||||
mystr = await AmazonBookScraper.ScraperMultipleDataAmazon(idapp, {
|
||||
update: true,
|
||||
aggiornasoloSeVuoti: true,
|
||||
forzaricarica: false,
|
||||
});
|
||||
ris = { mystr };
|
||||
} else if (mydata.dbop === "ScraperEstraiDatiAmazon-NoUpdate") {
|
||||
mystr = await AmazonBookScraper.ScraperMultipleDataAmazon(idapp, {update: false, aggiornasoloSeVuoti: false, forzaricarica: true, caricatutti: true});
|
||||
} else if (mydata.dbop === 'ScraperEstraiDatiAmazon-NoUpdate') {
|
||||
mystr = await AmazonBookScraper.ScraperMultipleDataAmazon(idapp, {
|
||||
update: false,
|
||||
aggiornasoloSeVuoti: false,
|
||||
forzaricarica: true,
|
||||
caricatutti: true,
|
||||
});
|
||||
ris = { mystr };
|
||||
} else if (mydata.dbop === "ScraperGeneraCSV") {
|
||||
} else if (mydata.dbop === 'ScraperGeneraCSV') {
|
||||
mystr = await AmazonBookScraper.ScraperGeneraCSV(idapp, mydata.options, res);
|
||||
ris = { mystr };
|
||||
} else if (mydata.dbop === "removeDuplicateVariations") {
|
||||
} else if (mydata.dbop === 'removeDuplicateVariations') {
|
||||
mystr = await AmazonBookScraper.removeDuplicateVariations(idapp, mydata.options);
|
||||
ris = { mystr };
|
||||
} else if (mydata.dbop === "ScraperAzzeraFlagProducts") {
|
||||
} else if (mydata.dbop === 'ScraperAzzeraFlagProducts') {
|
||||
mystr = await AmazonBookScraper.ScraperAzzeraFlagProducts(idapp, mydata.options);
|
||||
ris = { mystr };
|
||||
} else if (mydata.dbop === "ReplaceAllCircuits") {
|
||||
} else if (mydata.dbop === 'GeneraPdfCatalogo') {
|
||||
|
||||
const genPdf = new GenPdf(idapp);
|
||||
|
||||
await genPdf.launch();
|
||||
|
||||
return await genPdf.generatePdfFromIdCatalog(mydata.options);
|
||||
} else if (mydata.dbop === 'ReplaceAllCircuits') {
|
||||
// ++ Replace All Circuitname with 'Circuito RIS %s'
|
||||
await Circuit.replaceAllCircuitNames(idapp);
|
||||
} else if (mydata.dbop === "eliminaCatProds") {
|
||||
} else if (mydata.dbop === 'eliminaCatProds') {
|
||||
await CatProd.deleteMany({ idapp });
|
||||
await SubCatProd.deleteMany({ idapp });
|
||||
} else if (mydata.dbop === "removeProductInfoWithoutDateUpdatedFromGM") {
|
||||
} else if (mydata.dbop === 'removeProductInfoWithoutDateUpdatedFromGM') {
|
||||
mystr = await ProductInfo.removeProductInfoWithoutDateUpdatedFromGM(idapp);
|
||||
ris = { mystr };
|
||||
} else if (mydata.dbop === "StatMacro") {
|
||||
} else if (mydata.dbop === 'StatMacro') {
|
||||
const macro = new Macro(idapp, {});
|
||||
mystr = await macro.getStat();
|
||||
ris = { mystr };
|
||||
} else if (mydata.dbop === "updateAllBook") {
|
||||
} else if (mydata.dbop === 'updateAllBook') {
|
||||
// chiama updateAllBook
|
||||
const { updateAllBook } = require("../controllers/articleController");
|
||||
const { updateAllBook } = require('../controllers/articleController');
|
||||
|
||||
mystr = await updateAllBook(idapp, mydata.options);
|
||||
|
||||
ris = { mystr };
|
||||
} else if (mydata.dbop === "updateAllBooksAndRemoveCanc") {
|
||||
} else if (mydata.dbop === 'updateAllBooksAndRemoveCanc') {
|
||||
// chiama updateAllBooksAndRemoveCanc
|
||||
|
||||
const { updateAllBook } = require("../controllers/articleController");
|
||||
const { updateAllBook } = require('../controllers/articleController');
|
||||
|
||||
console.log('updateAllBooksAndRemoveCanc...');
|
||||
|
||||
|
||||
mystr = await updateAllBook(idapp, {usaDBGMLocale: false, caricatutti: true, rimuovieventualiCancellati: true});
|
||||
mystr = await updateAllBook(idapp, {
|
||||
usaDBGMLocale: false,
|
||||
caricatutti: true,
|
||||
rimuovieventualiCancellati: true,
|
||||
});
|
||||
|
||||
ris = { mystr };
|
||||
} else if (mydata.dbop === "creaUtentiTest") {
|
||||
} else if (mydata.dbop === 'creaUtentiTest') {
|
||||
let num = 0;
|
||||
lastrec = await User.find({ idapp }).sort({ _id: -1 }).limit(1);
|
||||
let last = 1;
|
||||
@@ -117,17 +138,17 @@ class CronMod {
|
||||
myuser._id = new ObjectId();
|
||||
myuser.index = last + ind + 1;
|
||||
myuser.idapp = idapp;
|
||||
myuser.password = "$2a$12$DEaX1h5saTUVC43f7kubyOAlah1xHDgqQTfSIux0.RFDT9WGbyCaG";
|
||||
myuser.lang = "it";
|
||||
myuser.email = "miaemail@email.it";
|
||||
myuser.name = "U" + myuser.index;
|
||||
myuser.surname = "Ar" + myuser.index;
|
||||
myuser.password = '$2a$12$DEaX1h5saTUVC43f7kubyOAlah1xHDgqQTfSIux0.RFDT9WGbyCaG';
|
||||
myuser.lang = 'it';
|
||||
myuser.email = 'miaemail@email.it';
|
||||
myuser.name = 'U' + myuser.index;
|
||||
myuser.surname = 'Ar' + myuser.index;
|
||||
myuser.verified_email = true;
|
||||
myuser.verified_by_aportador = true;
|
||||
if (myuser.index < 2) myuser.perm = "3";
|
||||
myuser.username = "Userna_" + myuser.name;
|
||||
if (myuser.index < 2) myuser.perm = '3';
|
||||
myuser.username = 'Userna_' + myuser.name;
|
||||
myuser.profile.special_req = true;
|
||||
myuser.profile.nationality = "IT";
|
||||
myuser.profile.nationality = 'IT';
|
||||
await myuser.save();
|
||||
num++;
|
||||
}
|
||||
@@ -156,57 +177,57 @@ class CronMod {
|
||||
|
||||
ris = { mystr };
|
||||
*/
|
||||
} else if (mydata.dbop === "CorreggiTabHours") {
|
||||
} else if (mydata.dbop === 'CorreggiTabHours') {
|
||||
ris = await Hours.correggiHours(idapp);
|
||||
} else if (mydata.dbop === "setVerifiedByAportadorToALL") {
|
||||
} else if (mydata.dbop === 'setVerifiedByAportadorToALL') {
|
||||
ris = await User.setVerifiedByAportadorToALL();
|
||||
} else if (mydata.dbop === "RewriteContribType") {
|
||||
ris = populate.rewriteTable("contribtypes");
|
||||
} else if (mydata.dbop === "ReplaceUsername") {
|
||||
} else if (mydata.dbop === 'RewriteContribType') {
|
||||
ris = populate.rewriteTable('contribtypes');
|
||||
} else if (mydata.dbop === 'ReplaceUsername') {
|
||||
if (User.isAdmin(req.user.perm)) {
|
||||
ris = globalTables.replaceUsername(req.body.idapp, mydata.search_username, mydata.replace_username);
|
||||
}
|
||||
} else if (mydata.dbop === "ExitFromAllCircuitWithZero") {
|
||||
} else if (mydata.dbop === 'ExitFromAllCircuitWithZero') {
|
||||
if (User.isAdmin(req.user.perm)) {
|
||||
ris = globalTables.ExitFromAllCircuitWithZero(req.body.idapp, mydata.search_username);
|
||||
}
|
||||
} else if (mydata.dbop === "replaceAportadorSolidario") {
|
||||
} else if (mydata.dbop === 'replaceAportadorSolidario') {
|
||||
if (User.isAdmin(req.user.perm)) {
|
||||
ris = globalTables.replaceAportadorSolidario(req.body.idapp, mydata.search_username, mydata.replace_username);
|
||||
}
|
||||
} else if (mydata.dbop === "SearchString") {
|
||||
} else if (mydata.dbop === 'SearchString') {
|
||||
if (User.isAdmin(req.user.perm)) {
|
||||
mystr = await globalTables.SearchString(req.body.idapp, mydata.search);
|
||||
}
|
||||
ris = { mystr };
|
||||
} else if (mydata.dbop === "UpdateCatDeleteEmpty") {
|
||||
} else if (mydata.dbop === 'UpdateCatDeleteEmpty') {
|
||||
mystr = await CatProd.updateCatDeleteEmpty(req.body.idapp);
|
||||
ris = { mystr };
|
||||
} else if (mydata.dbop === "UpdateStatFatturato") {
|
||||
} else if (mydata.dbop === 'UpdateStatFatturato') {
|
||||
mystr = await ProductInfo.updateProductInfoByStats(req.body.idapp);
|
||||
ris = { mystr };
|
||||
} else if (mydata.dbop === "MigrateMSSQLToMongoDb") {
|
||||
const { mssqlmigrateTables } = require("../controllers/articleController");
|
||||
} else if (mydata.dbop === 'MigrateMSSQLToMongoDb') {
|
||||
const { mssqlmigrateTables } = require('../controllers/articleController');
|
||||
|
||||
mystr = await mssqlmigrateTables(req);
|
||||
|
||||
ris = { mystr };
|
||||
} else if (mydata.dbop === "copyFrom1To14") {
|
||||
} else if (mydata.dbop === 'copyFrom1To14') {
|
||||
const idapporig = 1;
|
||||
const idappdest = 14;
|
||||
if (!idapporig || !idappdest) return;
|
||||
|
||||
const globalTables = require("../tools/globalTables");
|
||||
const globalTables = require('../tools/globalTables');
|
||||
|
||||
//++ Todo: TO FIXIT !
|
||||
const mytablesstr = ["settings", "users", "templemail", "destnewsletter", "contribtypes", "bots", "cfgservers"];
|
||||
const mytablesstr = ['settings', 'users', 'templemail', 'destnewsletter', 'contribtypes', 'bots', 'cfgservers'];
|
||||
|
||||
try {
|
||||
let numrectot = 0;
|
||||
for (const table of mytablesstr) {
|
||||
const mytable = globalTables.getTableByTableName(table);
|
||||
|
||||
tools.mylogshow("copyfromapptoapp: ", table, mytable);
|
||||
tools.mylogshow('copyfromapptoapp: ', table, mytable);
|
||||
|
||||
await mytable.DuplicateAllRecords(idapporig, idappdest).then((numrec) => {
|
||||
// tools.mylogshow(' REC TO MODIFY: ', rec);
|
||||
@@ -216,40 +237,40 @@ class CronMod {
|
||||
|
||||
ris = true;
|
||||
} catch (e) {
|
||||
console.log("e", e);
|
||||
console.log('e', e);
|
||||
}
|
||||
} else if (mydata.dbop === "removeRecordsFav") {
|
||||
} else if (mydata.dbop === 'removeRecordsFav') {
|
||||
// Passa le tabelle da users sulle nuove tabelle:
|
||||
await User.removerecordsFavorite();
|
||||
} else if (mydata.dbop === "updateReactionsCounts") {
|
||||
} else if (mydata.dbop === 'updateReactionsCounts') {
|
||||
await Reaction.updateReactionsCounts();
|
||||
} else if (mydata.dbop === "GeneraCSVOrdineProdotti") {
|
||||
} else if (mydata.dbop === 'GeneraCSVOrdineProdotti') {
|
||||
await Order.GeneraCSVOrdineProdotti();
|
||||
} else if (mydata.dbop === "RemoveDeletedOrdersInOrderscart") {
|
||||
} else if (mydata.dbop === 'RemoveDeletedOrdersInOrderscart') {
|
||||
await Order.RemoveDeletedOrdersInOrderscart();
|
||||
} else if (mydata.dbop === "CheckTransazioniCircuiti") {
|
||||
} else if (mydata.dbop === 'CheckTransazioniCircuiti') {
|
||||
await Circuit.CheckTransazioniCircuiti(false);
|
||||
} else if (mydata.dbop === "CorreggiTransazioniCircuiti") {
|
||||
} else if (mydata.dbop === 'CorreggiTransazioniCircuiti') {
|
||||
await Circuit.CheckTransazioniCircuiti(true);
|
||||
} else if (mydata.dbop === "RemovePendentTransactions") {
|
||||
} else if (mydata.dbop === 'RemovePendentTransactions') {
|
||||
ris = await SendNotif.RemovePendentTransactions(idapp);
|
||||
} else if (mydata.dbop === "RemoveOldNotif90") {
|
||||
} else if (mydata.dbop === 'RemoveOldNotif90') {
|
||||
await SendNotif.RemoveOldNotif90(idapp);
|
||||
} else if (mydata.dbop === "RemoveOldNotif30") {
|
||||
} else if (mydata.dbop === 'RemoveOldNotif30') {
|
||||
await SendNotif.RemoveOldNotif30(idapp);
|
||||
} else if (mydata.dbop === "UpdateCoordProv") {
|
||||
} else if (mydata.dbop === 'UpdateCoordProv') {
|
||||
await Province.setCoordinatesOnDB();
|
||||
} else if (mydata.dbop === "insertGeojsonToMongoDB") {
|
||||
await City.insertGeojsonToMongoDB("comuni_italia.geojson");
|
||||
} else if (mydata.dbop === "listCollectionsBySize") {
|
||||
} else if (mydata.dbop === 'insertGeojsonToMongoDB') {
|
||||
await City.insertGeojsonToMongoDB('comuni_italia.geojson');
|
||||
} else if (mydata.dbop === 'listCollectionsBySize') {
|
||||
mystr = await tools.listCollectionsBySize();
|
||||
ris = { mystr };
|
||||
} else if (mydata.dbop === "EnableNewsOn_ToAll") {
|
||||
} else if (mydata.dbop === 'EnableNewsOn_ToAll') {
|
||||
mystr = await User.setNewsletterToAll(idapp);
|
||||
} else if (mydata.dbop === "MyElemSetIdPageInsteadThePah") {
|
||||
} else if (mydata.dbop === 'MyElemSetIdPageInsteadThePah') {
|
||||
mystr = await MyElem.SetIdPageInsteadThePah(idapp);
|
||||
ris = { mystr };
|
||||
} else if (mydata.dbop === "AbilitaNewsletterALL") {
|
||||
} else if (mydata.dbop === 'AbilitaNewsletterALL') {
|
||||
await User.updateMany(
|
||||
{
|
||||
$or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }],
|
||||
@@ -257,44 +278,44 @@ class CronMod {
|
||||
{ $set: { news_on: true } },
|
||||
{ new: false }
|
||||
);
|
||||
} else if (mydata.dbop === "SvuotaTuttiGliAccessiOnlineConToken") {
|
||||
} else if (mydata.dbop === 'SvuotaTuttiGliAccessiOnlineConToken') {
|
||||
await User.SvuotaTuttiGliAccessiOnlineConToken(idapp);
|
||||
} else if (mydata.dbop === "SettaAdTypeOffro_In_Hosps") {
|
||||
const { MyHosp } = require("../models/myhosp");
|
||||
} else if (mydata.dbop === 'SettaAdTypeOffro_In_Hosps') {
|
||||
const { MyHosp } = require('../models/myhosp');
|
||||
|
||||
await MyHosp.SettaAdTypeOffro_In_Hosps(idapp);
|
||||
} else if (mydata.dbop === "removeRegulations") {
|
||||
await Circuit.updateMany({}, { $set: { regulation: "" } });
|
||||
} else if (mydata.dbop === "newRecordsFav") {
|
||||
} else if (mydata.dbop === 'removeRegulations') {
|
||||
await Circuit.updateMany({}, { $set: { regulation: '' } });
|
||||
} else if (mydata.dbop === 'newRecordsFav') {
|
||||
// Passa le tabelle da users sulle nuove tabelle:
|
||||
await User.moverecordsFavorite(1);
|
||||
await User.moverecordsFavorite(2);
|
||||
await User.moverecordsFavorite(3);
|
||||
await User.moverecordsFavorite(4);
|
||||
await User.moverecordsFavorite(5);
|
||||
} else if (mydata.dbop === "emptyTabCatServiziBeni") {
|
||||
const { Sector } = require("../models/sector");
|
||||
const { SectorGood } = require("../models/sectorgood");
|
||||
const { Skill } = require("../models/skill");
|
||||
const { Good } = require("../models/good");
|
||||
} else if (mydata.dbop === 'emptyTabCatServiziBeni') {
|
||||
const { Sector } = require('../models/sector');
|
||||
const { SectorGood } = require('../models/sectorgood');
|
||||
const { Skill } = require('../models/skill');
|
||||
const { Good } = require('../models/good');
|
||||
|
||||
await Sector.deleteMany({});
|
||||
await SectorGood.deleteMany({});
|
||||
await Skill.deleteMany({});
|
||||
ris = await Good.deleteMany({});
|
||||
} else if (mydata.dbop === "emptyDbSkill") {
|
||||
} else if (mydata.dbop === 'emptyDbSkill') {
|
||||
// Svuota e Ricrea
|
||||
|
||||
const { Sector } = require("../models/sector");
|
||||
const { SectorGood } = require("../models/sectorgood");
|
||||
const { Skill } = require("../models/skill");
|
||||
const { Good } = require("../models/good");
|
||||
const { SubSkill } = require("../models/subskill");
|
||||
const { Contribtype } = require("../models/contribtype");
|
||||
const { AdType } = require("../models/adtype");
|
||||
const { AdTypeGood } = require("../models/adtypegood");
|
||||
const { StatusSkill } = require("../models/statusSkill");
|
||||
const { CatGrp } = require("../models/catgrp");
|
||||
const { Sector } = require('../models/sector');
|
||||
const { SectorGood } = require('../models/sectorgood');
|
||||
const { Skill } = require('../models/skill');
|
||||
const { Good } = require('../models/good');
|
||||
const { SubSkill } = require('../models/subskill');
|
||||
const { Contribtype } = require('../models/contribtype');
|
||||
const { AdType } = require('../models/adtype');
|
||||
const { AdTypeGood } = require('../models/adtypegood');
|
||||
const { StatusSkill } = require('../models/statusSkill');
|
||||
const { CatGrp } = require('../models/catgrp');
|
||||
|
||||
await Sector.deleteMany({});
|
||||
await SectorGood.deleteMany({});
|
||||
@@ -308,19 +329,19 @@ class CronMod {
|
||||
await CatGrp.deleteMany({});
|
||||
|
||||
ris = await populate.popolaTabelleNuove();
|
||||
} else if (mydata.dbop === "ricreaTabCitiesProvinces") {
|
||||
} else if (mydata.dbop === 'ricreaTabCitiesProvinces') {
|
||||
// Svuota e Ricrea
|
||||
|
||||
const { City } = require("../models/city");
|
||||
const { Province } = require("../models/province");
|
||||
const { City } = require('../models/city');
|
||||
const { Province } = require('../models/province');
|
||||
|
||||
await City.deleteMany({});
|
||||
await Province.deleteMany({});
|
||||
|
||||
ris = await populate.popolaTabelleNuove();
|
||||
} else if (mydata.dbop === "PopulateTables") {
|
||||
} else if (mydata.dbop === 'PopulateTables') {
|
||||
ris = populate.popolaTabelleNuove();
|
||||
} else if (mydata.dbop === "dropProducts") {
|
||||
} else if (mydata.dbop === 'dropProducts') {
|
||||
if (idapp) {
|
||||
const deleteProducts = await Product.deleteMany({ idapp });
|
||||
console.log(`Cancellati ${deleteProducts.deletedCount} record dalla collezione Product.`);
|
||||
@@ -331,11 +352,11 @@ class CronMod {
|
||||
}
|
||||
|
||||
ris = deleteProductInfo ? true : false;
|
||||
} else if (mydata.dbop === "dropCatProd") {
|
||||
} else if (mydata.dbop === 'dropCatProd') {
|
||||
const deleteCatProd = await CatProd.deleteMany({ idapp });
|
||||
} else if (mydata.dbop === "dropSubCatProd") {
|
||||
} else if (mydata.dbop === 'dropSubCatProd') {
|
||||
const deleteSubCatProd = await SubCatProd.deleteMany({ idapp });
|
||||
} else if (mydata.dbop === "dropAllOrders") {
|
||||
} else if (mydata.dbop === 'dropAllOrders') {
|
||||
try {
|
||||
const deleteOrder = await Order.deleteMany({ idapp });
|
||||
const deleteOrdersCart = await OrdersCart.deleteMany({ idapp });
|
||||
@@ -343,9 +364,9 @@ class CronMod {
|
||||
|
||||
ris = deleteCart;
|
||||
} catch (e) {
|
||||
console.error("Err:", e);
|
||||
console.error('Err:', e);
|
||||
}
|
||||
} else if (mydata.dbop === "SistemaGasOrdine") {
|
||||
} else if (mydata.dbop === 'SistemaGasOrdine') {
|
||||
const arrrec = await Product.find({}).lean();
|
||||
for (const rec of arrrec) {
|
||||
if (tools.isArray(rec.idGasordines) && rec.idGasordines.length > 0) {
|
||||
@@ -354,7 +375,7 @@ class CronMod {
|
||||
await Product.findByIdAndUpdate(rec._id, { $set: { idGasordine: null } });
|
||||
}
|
||||
}
|
||||
} else if (mydata.dbop === "CopyPriceToCalc") {
|
||||
} else if (mydata.dbop === 'CopyPriceToCalc') {
|
||||
try {
|
||||
const arrrec = await OrdersCart.find({}).lean();
|
||||
for (const rec of arrrec) {
|
||||
@@ -366,30 +387,30 @@ class CronMod {
|
||||
await Order.findByIdAndUpdate(rec._id, { $set: { TotalPriceProductCalc: rec.TotalPriceProduct } });
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("Err:", e);
|
||||
console.error('Err:', e);
|
||||
}
|
||||
} else if (mydata.dbop === "dropAllCarts") {
|
||||
} else if (mydata.dbop === 'dropAllCarts') {
|
||||
ris = await Cart.deleteMany({ idapp });
|
||||
} else if (mydata.dbop === "RewriteCitiesTable") {
|
||||
ris = populate.rewriteTable("cities");
|
||||
} else if (mydata.dbop === "RewriteLevelsTable") {
|
||||
ris = populate.rewriteTable("levels");
|
||||
} else if (mydata.dbop === "RewriteProvincesTable") {
|
||||
ris = populate.rewriteTable("provinces");
|
||||
} else if (mydata.dbop === "emptyCityProvinces") {
|
||||
const { City } = require("../models/city");
|
||||
const { Province } = require("../models/province");
|
||||
} else if (mydata.dbop === 'RewriteCitiesTable') {
|
||||
ris = populate.rewriteTable('cities');
|
||||
} else if (mydata.dbop === 'RewriteLevelsTable') {
|
||||
ris = populate.rewriteTable('levels');
|
||||
} else if (mydata.dbop === 'RewriteProvincesTable') {
|
||||
ris = populate.rewriteTable('provinces');
|
||||
} else if (mydata.dbop === 'emptyCityProvinces') {
|
||||
const { City } = require('../models/city');
|
||||
const { Province } = require('../models/province');
|
||||
|
||||
await City.deleteMany({});
|
||||
await Province.deleteMany({});
|
||||
} else if (mydata.dbop === "ConvTablesFromIntToString") {
|
||||
const { MySkill } = require("../models/myskill");
|
||||
const { MyBacheca } = require("../models/mybacheca");
|
||||
const { MyHosp } = require("../models/myhosp");
|
||||
const { MyGood } = require("../models/mygood");
|
||||
} else if (mydata.dbop === 'ConvTablesFromIntToString') {
|
||||
const { MySkill } = require('../models/myskill');
|
||||
const { MyBacheca } = require('../models/mybacheca');
|
||||
const { MyHosp } = require('../models/myhosp');
|
||||
const { MyGood } = require('../models/mygood');
|
||||
// const { MyGroup } = require('../models/mygroup');
|
||||
|
||||
console.log("INIZIO - Conversioni");
|
||||
console.log('INIZIO - Conversioni');
|
||||
// 'myskills',
|
||||
// 'mybachecas',
|
||||
// 'myhosps',
|
||||
@@ -402,15 +423,15 @@ class CronMod {
|
||||
await ConvertiDaIntAStr(MyGood);
|
||||
await ConvertiDaIntAStr(MyGroup);
|
||||
|
||||
console.log("FINE - Conversioni");
|
||||
} else if (mydata.dbop === "Removeinteger") {
|
||||
const { MySkill } = require("../models/myskill");
|
||||
const { MyBacheca } = require("../models/mybacheca");
|
||||
const { MyHosp } = require("../models/myhosp");
|
||||
const { MyGood } = require("../models/mygood");
|
||||
console.log('FINE - Conversioni');
|
||||
} else if (mydata.dbop === 'Removeinteger') {
|
||||
const { MySkill } = require('../models/myskill');
|
||||
const { MyBacheca } = require('../models/mybacheca');
|
||||
const { MyHosp } = require('../models/myhosp');
|
||||
const { MyGood } = require('../models/mygood');
|
||||
// const { MyGroup } = require('../models/mygroup');
|
||||
|
||||
console.log("INIZIO - Rimozione");
|
||||
console.log('INIZIO - Rimozione');
|
||||
|
||||
await RimuoviInteri(MySkill);
|
||||
await RimuoviInteri(MyBacheca);
|
||||
@@ -418,45 +439,45 @@ class CronMod {
|
||||
await RimuoviInteri(MyGood);
|
||||
await RimuoviInteri(MyGroup);
|
||||
|
||||
console.log("FINE - Rimozione");
|
||||
} else if (mydata.dbop === "createAllCircuits") {
|
||||
const { Province } = require("../models/province");
|
||||
console.log('FINE - Rimozione');
|
||||
} else if (mydata.dbop === 'createAllCircuits') {
|
||||
const { Province } = require('../models/province');
|
||||
|
||||
const arrProv = await Province.find({});
|
||||
for (const recprov of arrProv) {
|
||||
await Circuit.createCircuitIfNotExist(req, idapp, recprov.prov);
|
||||
}
|
||||
} else if (mydata.dbop === "correggiProductTypes") {
|
||||
} else if (mydata.dbop === 'correggiProductTypes') {
|
||||
await ProductInfo.correggiProductTypes();
|
||||
} else if (mydata.dbop === "replaceProductImgToImageFile") {
|
||||
} else if (mydata.dbop === 'replaceProductImgToImageFile') {
|
||||
await ProductInfo.replaceProductImgToImageFile(true);
|
||||
} else if (mydata.dbop === "removeUploadProducts_Path") {
|
||||
} else if (mydata.dbop === 'removeUploadProducts_Path') {
|
||||
await ProductInfo.replaceProductImgToImageFile(false);
|
||||
} else if (mydata.dbop === "correggiCircuitiANull") {
|
||||
await User.updateMany({}, { $pull: { "profile.mycircuits": { circuitname: null } } });
|
||||
} else if (mydata.dbop === "ImpostaMinMaxPersonali") {
|
||||
await Account.SetMinMaxPersonali(idapp, mydata.valmin, mydata.valmax, "");
|
||||
} else if (mydata.dbop === "ImpostaMinMaxPersonaliCircuito") {
|
||||
} else if (mydata.dbop === 'correggiCircuitiANull') {
|
||||
await User.updateMany({}, { $pull: { 'profile.mycircuits': { circuitname: null } } });
|
||||
} else if (mydata.dbop === 'ImpostaMinMaxPersonali') {
|
||||
await Account.SetMinMaxPersonali(idapp, mydata.valmin, mydata.valmax, '');
|
||||
} else if (mydata.dbop === 'ImpostaMinMaxPersonaliCircuito') {
|
||||
await Account.SetMinMaxPersonali(idapp, mydata.valmin, mydata.valmax, mydata.circuitId);
|
||||
} else if (mydata.dbop === "ImpostaMinMaxComunitari") {
|
||||
} else if (mydata.dbop === 'ImpostaMinMaxComunitari') {
|
||||
await Account.SetMinMaxComunitari(idapp, mydata.valmin, mydata.valmax);
|
||||
} else if (mydata.dbop === "ImpostaMinMaxCollettivi") {
|
||||
} else if (mydata.dbop === 'ImpostaMinMaxCollettivi') {
|
||||
await Account.SetMinMaxCollettivi(idapp, mydata.valmin, mydata.valmax);
|
||||
} else if (mydata.dbop === "ImpostaDefMinMaxPersonali") {
|
||||
} else if (mydata.dbop === 'ImpostaDefMinMaxPersonali') {
|
||||
await Circuit.SetDefMinMaxPersonali(idapp, mydata.valmin, mydata.valmax, mydata.circuitId);
|
||||
} else if (mydata.dbop === "ImpostaDefMinMaxCollettivi") {
|
||||
} else if (mydata.dbop === 'ImpostaDefMinMaxCollettivi') {
|
||||
await Circuit.SetDefMinMaxCollettivi(idapp, mydata.valmin, mydata.valmax, mydata.circuitId);
|
||||
} else if (mydata.dbop === "AbilitaTuttiCircuiti") {
|
||||
} else if (mydata.dbop === 'AbilitaTuttiCircuiti') {
|
||||
await Circuit.AbilitaTuttiCircuiti(idapp);
|
||||
} else if (mydata.dbop === "AzzeraRegolamentiTuttiCircuiti") {
|
||||
} else if (mydata.dbop === 'AzzeraRegolamentiTuttiCircuiti') {
|
||||
await Circuit.AzzeraRegolamentiTuttiCircuiti(idapp);
|
||||
} else if (mydata.dbop === "setstrProvByIdCityCircuits") {
|
||||
} else if (mydata.dbop === 'setstrProvByIdCityCircuits') {
|
||||
await Circuit.setstrProvByIdCityCircuits(idapp);
|
||||
} else if (mydata.dbop === "updateSaldoAndTransato_AllAccounts") {
|
||||
} else if (mydata.dbop === 'updateSaldoAndTransato_AllAccounts') {
|
||||
await Account.updateSaldoAndTransato_AllAccounts(idapp);
|
||||
} else if (mydata.dbop === "generateBotMenuRecords") {
|
||||
} else if (mydata.dbop === 'generateBotMenuRecords') {
|
||||
await MyBot.generateBotMenuRecords(idapp);
|
||||
} else if (mydata.dbop === "GenerateVapiKey") {
|
||||
} else if (mydata.dbop === 'GenerateVapiKey') {
|
||||
await tools.generateVapiKey();
|
||||
|
||||
/*} else if (mydata.dbop === 'visuNave') {
|
||||
|
||||
401
src/server/modules/GenPdf.js
Normal file
401
src/server/modules/GenPdf.js
Normal file
@@ -0,0 +1,401 @@
|
||||
const puppeteer = require('puppeteer');
|
||||
const path = require('path');
|
||||
const fs = require('fs').promises;
|
||||
|
||||
const gs = require('ghostscript4js');
|
||||
|
||||
const { PDFDocument, rgb } = require('pdf-lib');
|
||||
|
||||
const { Catalog } = require('../models/catalog');
|
||||
const { MyPage } = require('../models/mypage');
|
||||
|
||||
const tools = require('../tools/general');
|
||||
const shared_consts = require('../tools/shared_nodejs');
|
||||
|
||||
class GenPdf {
|
||||
constructor(idapp) {
|
||||
this.idapp = idapp;
|
||||
this.browser = null;
|
||||
}
|
||||
|
||||
async launch() {
|
||||
this.browser = await puppeteer.launch();
|
||||
}
|
||||
|
||||
async close() {
|
||||
if (this.browser) {
|
||||
await this.browser.close();
|
||||
this.browser = null;
|
||||
}
|
||||
}
|
||||
|
||||
inchesToPixels(inches, stampa) {
|
||||
if (stampa) {
|
||||
return Math.floor(inches * 300);
|
||||
} else {
|
||||
return Math.floor(inches * 96);
|
||||
}
|
||||
}
|
||||
|
||||
mmToInches(mm) {
|
||||
return mm / 25.4;
|
||||
}
|
||||
|
||||
async autoScroll(page) {
|
||||
console.log('inizia a scrollare')
|
||||
await page.evaluate(async () => {
|
||||
await new Promise((resolve) => {
|
||||
let totalHeight = 0;
|
||||
console.log('autoScroll...')
|
||||
const distance = 100;
|
||||
const timer = setInterval(() => {
|
||||
window.scrollBy(0, distance);
|
||||
totalHeight += distance;
|
||||
|
||||
if (totalHeight >= document.body.scrollHeight) {
|
||||
clearInterval(timer);
|
||||
resolve();
|
||||
}
|
||||
}, 40);
|
||||
|
||||
|
||||
});
|
||||
});
|
||||
console.log(' FINE: autoScroll...')
|
||||
}
|
||||
|
||||
async generatePdfFromUrl(url, filenameOut, options = {}) {
|
||||
if (!this.browser) {
|
||||
throw new Error('Browser non avviato. Chiama launch() prima.');
|
||||
}
|
||||
|
||||
const page = await this.browser.newPage();
|
||||
|
||||
try {
|
||||
await page.goto(url, { waitUntil: 'networkidle0' });
|
||||
await tools.attendiNSecondi(5);
|
||||
await page.waitForSelector('#q-notify', { timeout: 60000 });
|
||||
|
||||
await this.autoScroll(page);
|
||||
|
||||
await tools.attendiNSecondi(5);
|
||||
|
||||
|
||||
// Seleziona tutte le sezioni da stampare
|
||||
let sectionHandles = await page.$$('.pdf-section');
|
||||
let numTentativi = 0;
|
||||
const maxTentativi = 3;
|
||||
while (sectionHandles.length === 0 && numTentativi < maxTentativi) {
|
||||
console.log(`Nessuna sezione .pdf-section trovata nella pagina, quindi ASPETTO DI PIU ${numTentativi + 1}/${maxTentativi}`);
|
||||
await tools.attendiNSecondi(5);
|
||||
sectionHandles = await page.$$('.pdf-section');
|
||||
numTentativi++;
|
||||
}
|
||||
|
||||
if (sectionHandles.length === 0) {
|
||||
throw new Error(`Nessuna sezione .pdf-section trovata nella pagina dopo ${maxTentativi} tentativi`);
|
||||
}
|
||||
|
||||
const pdfBuffers = [];
|
||||
|
||||
for (const sectionHandle of sectionHandles) {
|
||||
// Nascondi tutte le sezioni
|
||||
await page.evaluate(() => {
|
||||
document.querySelectorAll('.pdf-section').forEach((el) => (el.style.display = 'none'));
|
||||
});
|
||||
|
||||
// Mostra solo la sezione corrente
|
||||
await sectionHandle.evaluate((el) => (el.style.display = 'block'));
|
||||
|
||||
// Calcola dimensioni della sezione
|
||||
const { width, height } = await sectionHandle.evaluate((el) => ({
|
||||
width: el.scrollWidth, // piccolo padding
|
||||
height: el.scrollHeight, // piccolo padding
|
||||
}));
|
||||
|
||||
console.log(`Larghezza: ${width}px, Altezza: ${height}px`);
|
||||
|
||||
|
||||
// Imposta viewport dinamico
|
||||
await page.setViewport({ width, height });
|
||||
|
||||
// Genera pdf buffer per questa pagina
|
||||
const pdfBuffer = await page.pdf({
|
||||
printBackground: true,
|
||||
width: `${width}px`,
|
||||
height: `${height}px`,
|
||||
margin: { top: '0', bottom: '0', left: '0', right: '0' },
|
||||
});
|
||||
|
||||
pdfBuffers.push(pdfBuffer);
|
||||
}
|
||||
|
||||
// Unisci tutti i PDF
|
||||
const mergedPdf = await PDFDocument.create();
|
||||
|
||||
for (const pdfBytes of pdfBuffers) {
|
||||
const pdf = await PDFDocument.load(pdfBytes);
|
||||
const copiedPages = await mergedPdf.copyPages(pdf, pdf.getPageIndices());
|
||||
copiedPages.forEach((page) => mergedPdf.addPage(page));
|
||||
}
|
||||
|
||||
const mergedPdfFile = await mergedPdf.save();
|
||||
|
||||
const finalFilePath = path.resolve(process.cwd(), filenameOut);
|
||||
await fs.writeFile(finalFilePath, mergedPdfFile);
|
||||
|
||||
// Ripristina tutte le sezioni visibili
|
||||
await page.evaluate(() => {
|
||||
document.querySelectorAll('.pdf-section').forEach((el) => (el.style.display = 'block'));
|
||||
});
|
||||
|
||||
console.log(`PDF finale generato: ${finalFilePath}`);
|
||||
|
||||
return finalFilePath;
|
||||
} catch (error) {
|
||||
console.error('Errore durante generazione PDF:', error);
|
||||
throw error;
|
||||
} finally {
|
||||
await page.close();
|
||||
}
|
||||
}
|
||||
|
||||
async convertPDF_ChildProcess(inputFile, outputFile, widthpx, heightpx, compressionLevel = 'screen') {
|
||||
const { spawn } = require('child_process');
|
||||
const path = require('path');
|
||||
|
||||
widthpx = widthpx * 2;
|
||||
heightpx = heightpx * 2;
|
||||
|
||||
console.log('=== CONVERSIONE CON CHILD_PROCESS E COMPRESSIONE ===');
|
||||
|
||||
// Verifica input
|
||||
if (!(await tools.isFileExistsAsync(inputFile))) {
|
||||
throw new Error(`File input non trovato: ${inputFile}`);
|
||||
}
|
||||
|
||||
// Assicurati che la directory output esista
|
||||
const outputDir = path.dirname(outputFile);
|
||||
const fs = require('fs').promises;
|
||||
try {
|
||||
await fs.mkdir(outputDir, { recursive: true });
|
||||
} catch (error) {
|
||||
// Directory già esistente, ok
|
||||
}
|
||||
|
||||
// Parametri di compressione ottimizzati
|
||||
const compressionSettings = {
|
||||
/*maximum: [
|
||||
'-dPDFSETTINGS=/screen',
|
||||
'-dDownsampleColorImages=true',
|
||||
'-dColorImageResolution=72',
|
||||
'-dDownsampleGrayImages=true',
|
||||
'-dGrayImageResolution=72',
|
||||
'-dDownsampleMonoImages=true',
|
||||
'-dMonoImageResolution=72',
|
||||
],
|
||||
high: [
|
||||
'-dPDFSETTINGS=/ebook',
|
||||
'-dDownsampleColorImages=true',
|
||||
'-dColorImageResolution=150',
|
||||
'-dDownsampleGrayImages=true',
|
||||
'-dGrayImageResolution=150',
|
||||
],*/
|
||||
printer: ['-dPDFSETTINGS=/printer', '-dDownsampleColorImages=true', '-dColorImageResolution=300'],
|
||||
screen: [
|
||||
'-dPDFSETTINGS=/screen',
|
||||
'-dDownsampleColorImages=true',
|
||||
'-dColorImageResolution=96',
|
||||
'-dDownsampleGrayImages=true',
|
||||
'-dGrayImageResolution=96',
|
||||
],
|
||||
};
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const args = [
|
||||
'-sDEVICE=pdfwrite',
|
||||
'-dCompatibilityLevel=1.4',
|
||||
'-dNOPAUSE',
|
||||
'-dQUIET',
|
||||
'-dBATCH',
|
||||
'-dSAFER',
|
||||
|
||||
// Parametri di compressione
|
||||
...(compressionSettings[compressionLevel] || compressionSettings['screen']),
|
||||
'-dCompressFonts=true',
|
||||
'-dSubsetFonts=true',
|
||||
'-dColorImageFilter=/DCTEncode',
|
||||
'-dGrayImageFilter=/DCTEncode',
|
||||
'-dEmbedAllFonts=true',
|
||||
|
||||
// Dimensioni pagina
|
||||
`-g${widthpx}x${heightpx}`,
|
||||
'-dFIXEDMEDIA',
|
||||
// '-dPDFFitPage',
|
||||
|
||||
// Output
|
||||
`-sOutputFile=${outputFile}`,
|
||||
inputFile,
|
||||
];
|
||||
|
||||
console.log('Spawning gs with compression args:', args.join(' '));
|
||||
|
||||
const gsProcess = spawn('gs', args, {
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
shell: process.platform === 'win32',
|
||||
});
|
||||
|
||||
let stdout = '';
|
||||
let stderr = '';
|
||||
|
||||
gsProcess.stdout.on('data', (data) => {
|
||||
stdout += data.toString();
|
||||
if (stdout.length < 1000) {
|
||||
// Evita log troppo lunghi
|
||||
console.log('GS OUT:', data.toString().trim());
|
||||
}
|
||||
});
|
||||
|
||||
gsProcess.stderr.on('data', (data) => {
|
||||
stderr += data.toString();
|
||||
if (stderr.length < 1000) {
|
||||
console.log('GS ERR:', data.toString().trim());
|
||||
}
|
||||
});
|
||||
|
||||
gsProcess.on('close', async (code) => {
|
||||
console.log(`GS process closed with code: ${code}`);
|
||||
|
||||
if (code === 0) {
|
||||
// Attendi e verifica
|
||||
setTimeout(async () => {
|
||||
try {
|
||||
const exists = await tools.isFileExistsAsync(outputFile);
|
||||
if (exists) {
|
||||
// Verifica dimensioni per confermare compressione
|
||||
try {
|
||||
const originalStats = await tools.getFileStatsAsync(inputFile);
|
||||
const newStats = await tools.getFileStatsAsync(outputFile);
|
||||
const compressionRatio = (((originalStats.size - newStats.size) / originalStats.size) * 100).toFixed(
|
||||
1
|
||||
);
|
||||
|
||||
console.log(`📁 File originale: ${(originalStats.size / 1024 / 1024).toFixed(2)} MB`);
|
||||
console.log(`📁 File compresso: ${(newStats.size / 1024 / 1024).toFixed(2)} MB`);
|
||||
console.log(`🗜️ Compressione: ${compressionRatio}%`);
|
||||
console.log('✅ SUCCESS: File generato e compresso');
|
||||
} catch (statsError) {
|
||||
console.log('Warning: impossibile calcolare statistiche compressione');
|
||||
}
|
||||
|
||||
resolve(outputFile);
|
||||
} else {
|
||||
console.log('❌ FAIL: File non generato nonostante exit code 0');
|
||||
reject(new Error('File non generato nonostante successo processo'));
|
||||
}
|
||||
} catch (error) {
|
||||
reject(error);
|
||||
}
|
||||
}, 1000);
|
||||
} else {
|
||||
reject(new Error(`Ghostscript failed with code ${code}: ${stderr}`));
|
||||
}
|
||||
});
|
||||
|
||||
gsProcess.on('error', (error) => {
|
||||
console.log('GS process error:', error);
|
||||
reject(new Error(`Failed to start Ghostscript: ${error.message}`));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async generatePdfFromUrls(urls, outputFilename) {
|
||||
if (!this.browser) {
|
||||
throw new Error('Browser non avviato. Chiama launch() prima.');
|
||||
}
|
||||
const pdfBuffers = [];
|
||||
|
||||
outputFilename = tools.getdirByIdApp(idapp) + '/';
|
||||
|
||||
try {
|
||||
for (const url of urls) {
|
||||
// ............
|
||||
}
|
||||
|
||||
const mergedPdf = await PDFDocument.create();
|
||||
|
||||
for (const pdfBytes of pdfBuffers) {
|
||||
const pdf = await PDFDocument.load(pdfBytes);
|
||||
const copiedPages = await mergedPdf.copyPages(pdf, pdf.getPageIndices());
|
||||
copiedPages.forEach((page) => mergedPdf.addPage(page));
|
||||
}
|
||||
|
||||
const mergedPdfFile = await mergedPdf.save();
|
||||
|
||||
const outputPath = path.resolve(process.cwd(), outputFilename);
|
||||
await fs.writeFile(outputPath, mergedPdfFile);
|
||||
|
||||
console.log(`PDF unito generato: ${outputPath}`);
|
||||
return outputPath;
|
||||
} catch (error) {
|
||||
console.error('Errore durante la generazione PDF:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async getPathByPage(idpage) {
|
||||
const mypage = await MyPage.findById(idpage);
|
||||
|
||||
if (mypage) {
|
||||
return mypage.path;
|
||||
}
|
||||
|
||||
return '';
|
||||
}
|
||||
|
||||
async generatePdfFromIdCatalog(options) {
|
||||
try {
|
||||
if (!options) {
|
||||
console.error('Opzioni non passate !');
|
||||
return null;
|
||||
}
|
||||
let filenamerelative = '';
|
||||
let fullnamepath = '';
|
||||
let stampa = options.stampa;
|
||||
|
||||
/*if (stampa) {
|
||||
options.width = '227.3mm';
|
||||
options.height = '313.5mm';
|
||||
} else {
|
||||
options.width = '210mm';
|
||||
options.height = '297mm';
|
||||
}*/
|
||||
|
||||
const catalog = await Catalog.findById(options.idCatalog);
|
||||
if (catalog) {
|
||||
const url = tools.getHostByIdApp(this.idapp) + '/cataloghi?id=' + catalog._id + '&stampa=' + (stampa ? '1' : '0');
|
||||
|
||||
if (url) {
|
||||
const myfilenameout = await this.getPathByPage(catalog.idPageAssigned);
|
||||
|
||||
|
||||
let addstr = (stampa) ? '_stampabile' : '';
|
||||
|
||||
filenamerelative = options.path + `${myfilenameout}${addstr}_generato.pdf`;
|
||||
|
||||
fullnamepath = tools.getdirByIdApp(this.idapp) + '/' + filenamerelative;
|
||||
await this.generatePdfFromUrl(url, fullnamepath, options);
|
||||
}
|
||||
}
|
||||
|
||||
return {fileout: filenamerelative, filesize: await tools.getSizeFile(fullnamepath)};
|
||||
} catch (error) {
|
||||
console.error('Errore durante la generazione del PDF dal catalogo ID:', error);
|
||||
return {fileout: '', filesize: 0, error: 'Errore durante la generazione del PDF dal catalogo ID:' + error?.message};
|
||||
}
|
||||
|
||||
return {fileout: '', filesize: 0 };
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = GenPdf;
|
||||
@@ -60,6 +60,14 @@ const { exec } = require('child_process');
|
||||
|
||||
const execPromise = util.promisify(exec);
|
||||
|
||||
const GenPdf = require('../modules/GenPdf');
|
||||
|
||||
const genPdf = new GenPdf();
|
||||
|
||||
(async () => {
|
||||
await genPdf.launch();
|
||||
})();
|
||||
|
||||
async function updateProductInfo(recproductInfoAttuale, product, idapp, mycatstr) {
|
||||
if (!recproductInfoAttuale || !mycatstr) return recproductInfoAttuale;
|
||||
|
||||
@@ -160,7 +168,7 @@ async function compressPdf(inputFile, outputFile, compressione) {
|
||||
}
|
||||
|
||||
// Valori ammessi per -dPDFSETTINGS di Ghostscript
|
||||
const validSettings = ['screen', 'ebook', 'printer', 'prepress', 'default'];
|
||||
const validSettings = ['screen', 'printer', 'high', 'maximum'];
|
||||
if (!validSettings.includes(compressione)) {
|
||||
console.warn(`Compressione '${compressione}' non valida, uso 'ebook'`);
|
||||
compressione = 'ebook';
|
||||
@@ -228,56 +236,204 @@ async function compressPdfWithPs2Pdf(inputFile, outputFile, compression = 'ebook
|
||||
}
|
||||
}
|
||||
|
||||
async function convertPDF_GS(inputFile, outputFile, width, height) {
|
||||
// Verifica che il file di input esista
|
||||
if (!(await tools.isFileExistsAsync(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(' ');
|
||||
|
||||
// DIAGNOSI COMPLETA DEL PROBLEMA
|
||||
async function diagnosePDFProblem() {
|
||||
console.log('=== DIAGNOSI COMPLETA SISTEMA ===');
|
||||
|
||||
// 1. Test ambiente Node.js
|
||||
console.log('Node.js version:', process.version);
|
||||
console.log('Platform:', process.platform);
|
||||
console.log('Architecture:', process.arch);
|
||||
console.log('Current working directory:', process.cwd());
|
||||
|
||||
// 2. Test moduli disponibili
|
||||
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 (await tools.isFileExistsAsync(outputFile)) {
|
||||
console.log('File di output generato:', outputFile);
|
||||
} else {
|
||||
console.error('Il File di output NON è stato generato! :', outputFile);
|
||||
}
|
||||
console.log('Testing gs module...');
|
||||
console.log('gs object:', typeof gs, Object.keys(gs || {}));
|
||||
} 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}`);
|
||||
}
|
||||
console.log('gs module error:', error.message);
|
||||
}
|
||||
|
||||
// 3. Test comando di sistema
|
||||
const { exec } = require('child_process');
|
||||
const util = require('util');
|
||||
const execAsync = util.promisify(exec);
|
||||
|
||||
try {
|
||||
console.log('Testing gs command from system...');
|
||||
const { stdout, stderr } = await execAsync('gs -version');
|
||||
console.log('GS Version stdout:', stdout);
|
||||
console.log('GS Version stderr:', stderr);
|
||||
} catch (error) {
|
||||
console.log('System gs command failed:', error.message);
|
||||
}
|
||||
|
||||
// 4. Test scrittura file
|
||||
const fs = require('fs').promises;
|
||||
const path = require('path');
|
||||
const testFile = path.join(process.cwd(), 'test_write.txt');
|
||||
|
||||
try {
|
||||
await fs.writeFile(testFile, 'test content');
|
||||
console.log('File write test: SUCCESS');
|
||||
await fs.unlink(testFile);
|
||||
} catch (error) {
|
||||
console.log('File write test: FAILED -', error.message);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// ALTERNATIVA 1: Usando child_process direttamente
|
||||
async function convertPDF_ChildProcess(inputFile, outputFile, width, height, compressionLevel = 'screen') {
|
||||
const { spawn } = require('child_process');
|
||||
const path = require('path');
|
||||
|
||||
console.log('=== CONVERSIONE CON CHILD_PROCESS E COMPRESSIONE ===');
|
||||
|
||||
// Verifica input
|
||||
if (!(await tools.isFileExistsAsync(inputFile))) {
|
||||
throw new Error(`File input non trovato: ${inputFile}`);
|
||||
}
|
||||
|
||||
// Assicurati che la directory output esista
|
||||
const outputDir = path.dirname(outputFile);
|
||||
const fs = require('fs').promises;
|
||||
try {
|
||||
await fs.mkdir(outputDir, { recursive: true });
|
||||
} catch (error) {
|
||||
// Directory già esistente, ok
|
||||
}
|
||||
|
||||
// const widthPt = Math.round(width * 28.34646);
|
||||
// const heightPt = Math.round(height * 28.34646);
|
||||
const widthPt = Math.round(width * 28.34646* 10);
|
||||
const heightPt = Math.round(height * 28.34646 * 10);
|
||||
|
||||
// Parametri di compressione ottimizzati
|
||||
const compressionSettings = {
|
||||
'maximum': [
|
||||
'-dPDFSETTINGS=/screen',
|
||||
'-dDownsampleColorImages=true',
|
||||
'-dColorImageResolution=72',
|
||||
'-dDownsampleGrayImages=true',
|
||||
'-dGrayImageResolution=72',
|
||||
'-dDownsampleMonoImages=true',
|
||||
'-dMonoImageResolution=72'
|
||||
],
|
||||
'high': [
|
||||
'-dPDFSETTINGS=/ebook',
|
||||
'-dDownsampleColorImages=true',
|
||||
'-dColorImageResolution=150',
|
||||
'-dDownsampleGrayImages=true',
|
||||
'-dGrayImageResolution=150'
|
||||
],
|
||||
'printer': [
|
||||
'-dPDFSETTINGS=/printer',
|
||||
'-dDownsampleColorImages=true',
|
||||
'-dColorImageResolution=300'
|
||||
],
|
||||
'screen': [
|
||||
'-dPDFSETTINGS=/screen',
|
||||
'-dDownsampleColorImages=true',
|
||||
'-dColorImageResolution=96',
|
||||
'-dDownsampleGrayImages=true',
|
||||
'-dGrayImageResolution=96'
|
||||
]
|
||||
};
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const args = [
|
||||
'-sDEVICE=pdfwrite',
|
||||
'-dCompatibilityLevel=1.4',
|
||||
'-dNOPAUSE',
|
||||
'-dQUIET',
|
||||
'-dBATCH',
|
||||
'-dSAFER',
|
||||
|
||||
// Parametri di compressione
|
||||
...compressionSettings[compressionLevel] || compressionSettings['screen'],
|
||||
'-dCompressFonts=true',
|
||||
'-dSubsetFonts=true',
|
||||
'-dColorImageFilter=/DCTEncode',
|
||||
'-dGrayImageFilter=/DCTEncode',
|
||||
'-dEmbedAllFonts=true',
|
||||
|
||||
// Dimensioni pagina
|
||||
`-g${widthPt}x${heightPt}`,
|
||||
'-dFIXEDMEDIA',
|
||||
// '-dPDFFitPage',
|
||||
|
||||
// Output
|
||||
`-sOutputFile=${outputFile}`,
|
||||
inputFile
|
||||
];
|
||||
|
||||
console.log('Spawning gs with compression args:', args.join(' '));
|
||||
|
||||
const gsProcess = spawn('gs', args, {
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
shell: process.platform === 'win32'
|
||||
});
|
||||
|
||||
let stdout = '';
|
||||
let stderr = '';
|
||||
|
||||
gsProcess.stdout.on('data', (data) => {
|
||||
stdout += data.toString();
|
||||
if (stdout.length < 1000) { // Evita log troppo lunghi
|
||||
console.log('GS OUT:', data.toString().trim());
|
||||
}
|
||||
});
|
||||
|
||||
gsProcess.stderr.on('data', (data) => {
|
||||
stderr += data.toString();
|
||||
if (stderr.length < 1000) {
|
||||
console.log('GS ERR:', data.toString().trim());
|
||||
}
|
||||
});
|
||||
|
||||
gsProcess.on('close', async (code) => {
|
||||
console.log(`GS process closed with code: ${code}`);
|
||||
|
||||
if (code === 0) {
|
||||
// Attendi e verifica
|
||||
setTimeout(async () => {
|
||||
try {
|
||||
const exists = await tools.isFileExistsAsync(outputFile);
|
||||
if (exists) {
|
||||
// Verifica dimensioni per confermare compressione
|
||||
try {
|
||||
const originalStats = await tools.getFileStatsAsync(inputFile);
|
||||
const newStats = await tools.getFileStatsAsync(outputFile);
|
||||
const compressionRatio = ((originalStats.size - newStats.size) / originalStats.size * 100).toFixed(1);
|
||||
|
||||
console.log(`📁 File originale: ${(originalStats.size / 1024 / 1024).toFixed(2)} MB`);
|
||||
console.log(`📁 File compresso: ${(newStats.size / 1024 / 1024).toFixed(2)} MB`);
|
||||
console.log(`🗜️ Compressione: ${compressionRatio}%`);
|
||||
console.log('✅ SUCCESS: File generato e compresso');
|
||||
} catch (statsError) {
|
||||
console.log('Warning: impossibile calcolare statistiche compressione');
|
||||
}
|
||||
|
||||
resolve(outputFile);
|
||||
} else {
|
||||
console.log('❌ FAIL: File non generato nonostante exit code 0');
|
||||
reject(new Error('File non generato nonostante successo processo'));
|
||||
}
|
||||
} catch (error) {
|
||||
reject(error);
|
||||
}
|
||||
}, 1000);
|
||||
} else {
|
||||
reject(new Error(`Ghostscript failed with code ${code}: ${stderr}`));
|
||||
}
|
||||
});
|
||||
|
||||
gsProcess.on('error', (error) => {
|
||||
console.log('GS process error:', error);
|
||||
reject(new Error(`Failed to start Ghostscript: ${error.message}`));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function extractPdfInfo(inputFile) {
|
||||
@@ -436,9 +592,11 @@ async function ConvertPDF_Generatore(options, instampa) {
|
||||
if (options.compressione) {
|
||||
const mostrainfo = true;
|
||||
fileout_compressed = tools.removeFileExtension(fileout) + `_compressed.pdf`;
|
||||
await diagnosePDFProblem();
|
||||
|
||||
// await compressPdf(fileout, fileout_compressed, options.compressione);
|
||||
await compressPdfWithPs2Pdf(fileout, fileout_compressed, options.compressione);
|
||||
// await compressPdfWithPs2Pdf(fileout, fileout_compressed, options.compressione);
|
||||
await convertPDF_ChildProcess(fileout, fileout_compressed, options.width, options.height, options.compressione);
|
||||
|
||||
// if (mostrainfo) extractPdfInfo(fileout_compressed);
|
||||
}
|
||||
@@ -2489,4 +2647,21 @@ router.post('/miab', authenticate, async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/generate-pdf', async (req, res) => {
|
||||
const { url, filename } = req.body;
|
||||
|
||||
if (!url || !filename) {
|
||||
return res.status(400).json({ error: 'url e filename sono richiesti' });
|
||||
}
|
||||
|
||||
try {
|
||||
const pdfPath = await genPdf.generatePdfFromUrl(url, filename);
|
||||
res.download(pdfPath);
|
||||
} catch (error) {
|
||||
console.error('Errore generazione PDF:', error);
|
||||
res.status(500).json({ error: 'Errore generazione PDF' });
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
module.exports = router;
|
||||
|
||||
@@ -2019,7 +2019,7 @@ async function load(req, res, version = '0') {
|
||||
|
||||
const { data, totalTime, slowCalls } = await measurePromises(promises);
|
||||
// console.log('Risultati delle promise:', data);
|
||||
console.log('Tempo di esecuzione:', totalTime, 'secondi');
|
||||
// console.log('Tempo di esecuzione:', totalTime, 'secondi');
|
||||
//console.log('Le 10 chiamate più lente:', slowCalls);
|
||||
|
||||
// Aggiornamento delle informazioni dell'utente, se presente
|
||||
@@ -2276,68 +2276,63 @@ router.post('/upload_from_other_server/:dir', authenticate, (req, res) => {
|
||||
});
|
||||
|
||||
// Funzione principale che gestisce l'upload
|
||||
async function uploadFile(req, res, version, options) {
|
||||
quality = options?.quality || 'original';
|
||||
const dir = tools.invertescapeslash(req.params.dir);
|
||||
async function uploadFile(req, res, version, options = {}) {
|
||||
const quality = options.quality || 'original';
|
||||
const dirParam = req.params.dir || '';
|
||||
const dir = tools.invertescapeslash(dirParam);
|
||||
const idapp = req.user.idapp;
|
||||
|
||||
const form = new formidable.IncomingForm();
|
||||
form.parse(req);
|
||||
// Determina la cartella base
|
||||
const dirmain = version > 0 && tools.sulServer() ? '' : server_constants.DIR_PUBLIC_LOCALE;
|
||||
const baseUploadFolder = tools.getdirByIdApp(idapp) + dirmain + server_constants.DIR_UPLOAD;
|
||||
|
||||
let dirmain = version > 0 && tools.sulServer() ? '' : server_constants.DIR_PUBLIC_LOCALE;
|
||||
const mydir2 = folder + '/' + dir;
|
||||
tools.mkdirpath(mydir2);
|
||||
form.uploadDir = mydir2;
|
||||
// Directory di upload specifica
|
||||
const uploadDir = path.join(baseUploadFolder, dir);
|
||||
|
||||
try {
|
||||
form.on('fileBegin', async function (name, file) {
|
||||
console.log('1) Uploading ' + file.originalFilename);
|
||||
const mydir = folder + '/' + file.newFilename;
|
||||
file.path = mydir;
|
||||
// Crea la cartella se non esiste
|
||||
await tools.mkdirpath(uploadDir);
|
||||
|
||||
// Configura formidable
|
||||
const form = new formidable.IncomingForm({ uploadDir });
|
||||
|
||||
// Promisifica il parsing per usare await
|
||||
const files = await new Promise((resolve, reject) => {
|
||||
form.parse(req, (err, fields, files) => {
|
||||
if (err) reject(err);
|
||||
else resolve(files);
|
||||
});
|
||||
});
|
||||
|
||||
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;
|
||||
await tools.mkdirpath(mydir);
|
||||
// files può contenere uno o più file: gestiamo uno per semplicità
|
||||
for (const key in files) {
|
||||
if (Object.prototype.hasOwnProperty.call(files, key)) {
|
||||
const file = files[key];
|
||||
|
||||
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;
|
||||
console.log('File ricevuto:', file[0].originalFilename);
|
||||
|
||||
|
||||
const oldFIle = file[0].filepath || file[0].path;
|
||||
|
||||
// Copia del file
|
||||
await moveFile(fromfile, tofile, res);
|
||||
// Nuovo percorso per il file rinominato
|
||||
const newFilePath = path.join(uploadDir, file[0].originalFilename);
|
||||
|
||||
// Ridimensionamento immagine
|
||||
await handleImageResizing(tofile, quality);
|
||||
// Sposta e rinomina il file (move è la funzione ottimizzata)
|
||||
// await move(file[0].filepath || file[0].path, newFilePath);
|
||||
await tools.move(oldFIle, newFilePath);
|
||||
|
||||
res.end();
|
||||
} catch (e) {
|
||||
console.log('Error during file processing: ', e);
|
||||
res.status(400).send();
|
||||
// Eventuale ridimensionamento immagine
|
||||
await handleImageResizing(newFilePath, quality);
|
||||
|
||||
console.log(`File processato e salvato in: ${newFilePath}`);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
form.on('end', function () {
|
||||
console.log('-> Upload completed');
|
||||
});
|
||||
|
||||
form.on('aborted', () => {
|
||||
console.error('Request aborted by the user');
|
||||
res.status(400).send();
|
||||
});
|
||||
|
||||
form.on('error', (err) => {
|
||||
console.error('Error Uploading', err?.message);
|
||||
res.status(400).send();
|
||||
});
|
||||
} catch (e) {
|
||||
console.log('Error', e);
|
||||
res.status(200).send('Upload completato con successo');
|
||||
} catch (err) {
|
||||
console.error('Errore durante uploadFile:', err);
|
||||
if (!res.headersSent) {
|
||||
res.status(500).send("Errore durante l'upload");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2345,7 +2340,7 @@ async function uploadFile(req, res, version, options) {
|
||||
async function moveFile(fromfile, tofile, res) {
|
||||
console.log('Moving file from ' + fromfile + ' to ' + tofile);
|
||||
try {
|
||||
if (!tools.sulServer()) {
|
||||
if (false && !tools.sulServer()) {
|
||||
console.log('Copying file (locally):', fromfile, 'to', tofile);
|
||||
await tools.execScriptNoOutput("sudo cp -R '" + fromfile + "' '" + tofile + "'");
|
||||
res.end();
|
||||
@@ -2367,7 +2362,7 @@ async function handleImageResizing(filePath, quality) {
|
||||
|
||||
try {
|
||||
// Ridimensionamento per la qualità "small"
|
||||
|
||||
|
||||
if (quality === 'small' || quality === 'both') {
|
||||
await resizeImage(filePath, resizedSmallPath, 64, 64);
|
||||
}
|
||||
|
||||
@@ -3948,45 +3948,58 @@ module.exports = {
|
||||
this.writelogfile(mystr, FILENAVE);
|
||||
},
|
||||
|
||||
async move(oldPath, newPath, callback) {
|
||||
try {
|
||||
const ris = await fs.promises.rename(oldPath, newPath);
|
||||
console.log('... File Rinominato:', oldPath, 'in:', newPath, 'ris', ris);
|
||||
callback(); // Chiamare il callback senza errori
|
||||
} catch (err) {
|
||||
if (err.code === 'EXDEV') {
|
||||
await copy(); // Se EXDEV, utilizza la funzione copy
|
||||
} else {
|
||||
console.error('Errore durante lo spostamento:', err);
|
||||
callback(err); // Passa l'errore al callback
|
||||
}
|
||||
}
|
||||
async copyFile(src, dest) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const readStream = fs.createReadStream(src);
|
||||
const writeStream = fs.createWriteStream(dest);
|
||||
|
||||
async function copy() {
|
||||
const readStream = fs.createReadStream(oldPath);
|
||||
const writeStream = fs.createWriteStream(newPath);
|
||||
|
||||
readStream.on('error', (err) => {
|
||||
console.error('Errore nella lettura del file:', err);
|
||||
callback(err); // Passa l'errore al callback
|
||||
});
|
||||
writeStream.on('error', (err) => {
|
||||
console.error('Errore nella scrittura del file:', err);
|
||||
callback(err); // Passa l'errore al callback
|
||||
});
|
||||
readStream.on('error', reject);
|
||||
writeStream.on('error', reject);
|
||||
writeStream.on('finish', resolve);
|
||||
|
||||
readStream.pipe(writeStream);
|
||||
});
|
||||
},
|
||||
|
||||
writeStream.on('finish', async () => {
|
||||
console.log('File copiato, ora rimuovo il file di origine:', oldPath);
|
||||
try {
|
||||
await fs.promises.unlink(oldPath); // Rimuovi il file originale
|
||||
callback(); // Chiama il callback al termine
|
||||
} catch (err) {
|
||||
console.error('Errore nella rimozione del file originale:', err);
|
||||
callback(err); // Passa l'errore al callback
|
||||
/**
|
||||
* Sposta un file da oldPath a newPath.
|
||||
* Se rename fallisce con EXDEV (diverso device), fa copia + delete.
|
||||
* Se la cartella di destinazione non esiste, la crea.
|
||||
* @param {string} oldPath
|
||||
* @param {string} newPath
|
||||
* @param {(err?: Error) => void} [callback] - opzionale, se non passato ritorna Promise
|
||||
*/
|
||||
async move(oldPath, newPath, callback) {
|
||||
const moveOp = async () => {
|
||||
// Assicurati che la cartella di destinazione esista
|
||||
const dir = path.dirname(newPath);
|
||||
await fs.promises.mkdir(dir, { recursive: true });
|
||||
|
||||
try {
|
||||
const newOldPath = oldPath.replace(/\/$/, '');
|
||||
const newNewPath = newPath.replace(/\/$/, '');
|
||||
await fs.promises.rename(newOldPath, newNewPath);
|
||||
console.log(`File spostato: ${oldPath} -> ${newPath}`);
|
||||
} catch (err) {
|
||||
if (err.code === 'EXDEV') {
|
||||
// Spostamento tra device diversi: copia + elimina
|
||||
await copyFile(oldPath, newPath);
|
||||
await fs.promises.unlink(oldPath);
|
||||
console.log(`File copiato e cancellato: ${oldPath} -> ${newPath}`);
|
||||
} else if (err.code === 'ENOENT') {
|
||||
throw new Error(`File non trovato: ${oldPath}`);
|
||||
} else {
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
if (callback && typeof callback === 'function') {
|
||||
moveOp()
|
||||
.then(() => callback())
|
||||
.catch(callback);
|
||||
} else {
|
||||
return moveOp();
|
||||
}
|
||||
},
|
||||
|
||||
@@ -5744,13 +5757,24 @@ module.exports = {
|
||||
return 'upload/';
|
||||
},
|
||||
|
||||
getDirByTable(idapp, table) {
|
||||
let mydir = this.getdirByIdApp(idapp) + '/';
|
||||
|
||||
if (table === 'catalog') {
|
||||
mydir = 'upload/cataloghi/';
|
||||
}
|
||||
|
||||
return mydir;
|
||||
|
||||
},
|
||||
|
||||
getURLImg(idapp, table, username, img, checkifExist) {
|
||||
let dirmain = '';
|
||||
|
||||
try {
|
||||
// let dir = this.getdirByIdApp(idapp) + dirmain + '/' + this.getDirUpload();
|
||||
let dir =
|
||||
this.getHostByIdApp(idapp) +
|
||||
this.getdirByIdApp(idapp)
|
||||
'/' +
|
||||
this.getDirUpload() +
|
||||
shared_consts.getDirectoryImgByTable(table, username) +
|
||||
@@ -6159,4 +6183,8 @@ module.exports = {
|
||||
const nuovoNomeFile = nomeFile + suffisso + estensione;
|
||||
return path.join(dir, nuovoNomeFile);
|
||||
},
|
||||
|
||||
async attendiNSecondi(numsec) {
|
||||
await new Promise(resolve => setTimeout(resolve, numsec * 1000));
|
||||
}
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user