- 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:
Surya Paolo
2025-05-29 18:23:20 +02:00
parent 9efd193124
commit 40214abe64
12 changed files with 1413 additions and 428 deletions

View File

@@ -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 };