From 3521a88395a9593c95889a811da3ef3f49ac6bcc Mon Sep 17 00:00:00 2001 From: Surya Paolo Date: Thu, 15 May 2025 18:22:43 +0200 Subject: [PATCH] - ottimizzato il caricamento del sito - ottimizzato il caricamento del catalogo. --- src/server/models/author.js | 24 ++-- src/server/models/catalog.js | 166 +++++++++++++---------- src/server/models/catprod.js | 4 +- src/server/models/raccoltacataloghi.js | 6 +- src/server/models/t_web_statiprodotto.js | 9 ++ src/server/models/t_web_tipiformato.js | 9 +- src/server/models/t_web_tipologie.js | 10 +- src/server/router/catalogs_router.js | 49 +++++++ src/server/server.js | 3 +- 9 files changed, 190 insertions(+), 90 deletions(-) create mode 100755 src/server/router/catalogs_router.js diff --git a/src/server/models/author.js b/src/server/models/author.js index 42f9811..fdf5535 100755 --- a/src/server/models/author.js +++ b/src/server/models/author.js @@ -1,14 +1,14 @@ -mongoose = require('mongoose').set('debug', false) +mongoose = require('mongoose').set('debug', false); const Schema = mongoose.Schema; const tools = require('../tools/general'); 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 AuthorSchema = new Schema({ @@ -29,13 +29,13 @@ const AuthorSchema = new Schema({ }, }); -var Author = module.exports = mongoose.model('Author', AuthorSchema); +var Author = (module.exports = mongoose.model('Author', AuthorSchema)); module.exports.getFieldsForSearch = function () { return [ { field: 'name', type: tools.FieldType.string }, { field: 'surname', type: tools.FieldType.string }, - ] + ]; }; module.exports.executeQueryTable = function (idapp, params) { @@ -46,10 +46,12 @@ module.exports.executeQueryTable = function (idapp, params) { module.exports.findAllIdApp = async function (idapp) { const myfind = { idapp }; - return await Author.find(myfind).sort({name: 1, surname: 1}); + return await Author.find(myfind).sort({ name: 1, surname: 1 }).select({ idapp: 0 }).lean(); }; -module.exports.createIndexes() - .then(() => { }) - .catch((err) => { throw err; }); - +module.exports + .createIndexes() + .then(() => {}) + .catch((err) => { + throw err; + }); diff --git a/src/server/models/catalog.js b/src/server/models/catalog.js index 335c73b..091a8ee 100755 --- a/src/server/models/catalog.js +++ b/src/server/models/catalog.js @@ -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'); @@ -7,15 +7,13 @@ const { ObjectId } = require('mongodb'); const { IImg } = 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 CatalogSchema = new Schema({ idapp: { type: String, @@ -30,16 +28,22 @@ const CatalogSchema = new Schema({ }, foto_collana: IImg, - idCollane: [{ - type: String, - }], - idTipoFormato: [{ - type: Number, - }], + idCollane: [ + { + type: String, + }, + ], + idTipoFormato: [ + { + type: Number, + }, + ], - argomenti: [{ - type: String, - }], + argomenti: [ + { + type: String, + }, + ], condition_andor: { type: Number, default: 0, @@ -56,9 +60,11 @@ const CatalogSchema = new Schema({ idPageAssigned_stampa: { type: String, }, - referenti: [{ - type: String, - }], + referenti: [ + { + type: String, + }, + ], img_bordata: IImg, img_intro: IImg, @@ -93,15 +99,17 @@ const CatalogSchema = new Schema({ date_created: { type: Date, - default: Date.now + default: Date.now, }, date_updated: { type: Date, }, - lista_prodotti: [{ - type: Schema.Types.ObjectId, - ref: 'Product', - }], + lista_prodotti: [ + { + type: Schema.Types.ObjectId, + ref: 'Product', + }, + ], isCatalogoGenerale: Boolean, }); @@ -117,7 +125,7 @@ CatalogSchema.pre('save', async function (next) { */ CatalogSchema.statics.getFieldsForSearch = function () { - return [{ field: 'title', type: tools.FieldType.string }] + return [{ field: 'title', type: tools.FieldType.string }]; }; CatalogSchema.statics.executeQueryTable = function (idapp, params, user) { @@ -151,85 +159,95 @@ CatalogSchema.statics.executeQueryTable = function (idapp, params, user) { };*/ CatalogSchema.statics.findAllIdApp = async function (idapp) { + + try { + const arrrec = await this.aggregate([ + { $match: { idapp } }, + { $addFields: { num_lista_prodotti: { $size: { $ifNull: ['$lista_prodotti', []] } } } }, + { $project: { lista_prodotti: 0 } }, + { $sort: { title: 1 } }, + ]); + return arrrec; + } catch (err) { + console.error('Errore:', err); + throw err; + } + +}; + +CatalogSchema.statics.getCatalogById = async function (id) { const Catalog = this; try { - let arrrec = await Catalog.find({ idapp }) - .sort({ title: 1 }) // Ordina i risultati per titolo - /*.populate({ - path: "idCollane", // Popola il campo idCollane - model: "Collana" // Specifica il modello della collezione Collana - })*/ + let arrrec = await Catalog.find({ _id: id }) .populate({ - path: "lista_prodotti", // Popola il campo lista_prodotti + path: 'lista_prodotti', // Popola il campo lista_prodotti populate: { - path: "idProductInfo", - model: "ProductInfo", + path: 'idProductInfo', + model: 'ProductInfo', populate: [ { - path: "idCatProds", - model: "CatProd" + path: 'idCatProds', + model: 'CatProd', }, { - path: "idSubCatProds", - model: "SubCatProd" + path: 'idSubCatProds', + model: 'SubCatProd', }, { - path: "idAuthors", - model: "Author" - } + path: 'idAuthors', + model: 'Author', + }, ], }, }) .populate({ - path: "lista_prodotti", + path: 'lista_prodotti', populate: { - path: "idProducer", - model: "Producer" - } + path: 'idProducer', + model: 'Producer', + }, }) .populate({ - path: "lista_prodotti", + path: 'lista_prodotti', populate: { - path: "idProvider", - model: "Provider" - } + path: 'idProvider', + model: 'Provider', + }, }) .populate({ - path: "lista_prodotti", + path: 'lista_prodotti', populate: { - path: "idStorehouses", - model: "Storehouse" - } + path: 'idStorehouses', + model: 'Storehouse', + }, }) .populate({ - path: "lista_prodotti", + path: 'lista_prodotti', populate: { - path: "idScontisticas", - model: "Scontistica" - } + path: 'idScontisticas', + model: 'Scontistica', + }, }) .populate({ - path: "lista_prodotti", + path: 'lista_prodotti', populate: { - path: "idGasordine", - model: "Gasordine" - } - }) - ; - + path: 'idGasordine', + model: 'Gasordine', + }, + }); // controlla prima se nella lista ci sono dei product che non esistono piu allora li devi rimuovere ! for (const catalog of arrrec) { const originalLength = catalog.lista_prodotti.length; - catalog.lista_prodotti = catalog.lista_prodotti.filter(product => product.idProductInfo); + catalog.lista_prodotti = catalog.lista_prodotti.filter((product) => product.idProductInfo); if (catalog.lista_prodotti.length !== originalLength) { await catalog.save(); } } - const transformedArrRec = arrrec.map(catalog => ({ + const transformedArrRec = arrrec.map((catalog) => ({ ...catalog.toObject(), // Converte il documento Mongoose in un oggetto JavaScript puro - lista_prodotti: catalog.lista_prodotti.map(product => ({ + lista_prodotti: catalog.lista_prodotti.map((product) => ({ ...product.toObject(), productInfo: { ...product.idProductInfo.toObject(), // Copia tutti i campi di idProductInfo @@ -242,12 +260,14 @@ CatalogSchema.statics.findAllIdApp = async function (idapp) { storehouse: product.idStorehouses, scontisticas: product.idScontisticas, gasordine: product.idGasordine, + idProductInfo: product.idProductInfo._id, // CHECK })), })); - return transformedArrRec; + return transformedArrRec && transformedArrRec.length > 0 ? transformedArrRec[0] : null; } catch (err) { - console.error('Errore: ', err); + console.error('Errore: ', err); + return null; } }; @@ -268,16 +288,16 @@ CatalogSchema.statics.executeQueryPickup = async function (idapp, params) { .limit(10) .select('title _id') .lean(); - + return arrrec; }; - const Catalog = mongoose.model('Catalog', CatalogSchema); Catalog.createIndexes() - .then(() => { }) - .catch((err) => { throw err; }); - + .then(() => {}) + .catch((err) => { + throw err; + }); module.exports = { Catalog }; diff --git a/src/server/models/catprod.js b/src/server/models/catprod.js index ce5d06c..fd65f45 100755 --- a/src/server/models/catprod.js +++ b/src/server/models/catprod.js @@ -136,7 +136,7 @@ CatProdSchema.statics.getCatProdWithTitleCount = async function (idapp, updateda icon: 1, color: 1, quanti: { $size: '$myproducts' }, // Conta il numero di prodotti per ciascun CatProd - products: { + /*products: { $map: { input: "$myproducts", as: "prod", @@ -144,7 +144,7 @@ CatProdSchema.statics.getCatProdWithTitleCount = async function (idapp, updateda name: "$$prod.name" } } - } + }*/ } }, { $sort: { name: 1 } } // Ordina i risultati per nome diff --git a/src/server/models/raccoltacataloghi.js b/src/server/models/raccoltacataloghi.js index a2dd826..3d30e46 100755 --- a/src/server/models/raccoltacataloghi.js +++ b/src/server/models/raccoltacataloghi.js @@ -75,7 +75,11 @@ RaccoltaCataloghiSchema.statics.findAllIdApp = async function (idapp) { const RaccoltaCataloghi = this; try { - let arrrec = await RaccoltaCataloghi.find({ idapp }).sort({ title: 1 }).populate('lista_cataloghi').lean(); + let arrrec = await RaccoltaCataloghi.find({ idapp }).sort({ title: 1 }) + .populate({ + path: 'lista_cataloghi', + select: '-lista_prodotti', + }).lean(); return arrrec; } catch (err) { diff --git a/src/server/models/t_web_statiprodotto.js b/src/server/models/t_web_statiprodotto.js index 1e2bba5..74870de 100755 --- a/src/server/models/t_web_statiprodotto.js +++ b/src/server/models/t_web_statiprodotto.js @@ -44,7 +44,16 @@ module.exports.findAllIdApp = async function () { }, { $sort: { IdStatoProdotto: 1 } // opzionale, per ordinare il risultato + }, + { + $project: { + _id: 1, + IdStatoProdotto: 1, + Descrizione: 1 + // rimuovi DataOra e aggiungi altri campi se servono + } } + ]; const rec = await T_WEB_StatiProdotto.aggregate(myquery); diff --git a/src/server/models/t_web_tipiformato.js b/src/server/models/t_web_tipiformato.js index 69d7be2..e7a1cd8 100755 --- a/src/server/models/t_web_tipiformato.js +++ b/src/server/models/t_web_tipiformato.js @@ -44,7 +44,14 @@ module.exports.findAllIdApp = async function () { }, { $sort: { IdTipoFormato: 1 } // opzionale, per ordinare il risultato - } + }, + { + $project: { + _id: 0, + IdTipoFormato: 1, + Descrizione: 1, + } + }, ]; const rec = await T_WEB_TipiFormato.aggregate(myquery); diff --git a/src/server/models/t_web_tipologie.js b/src/server/models/t_web_tipologie.js index db01960..b85c3df 100755 --- a/src/server/models/t_web_tipologie.js +++ b/src/server/models/t_web_tipologie.js @@ -44,7 +44,15 @@ module.exports.findAllIdApp = async function () { }, { $sort: { IdTipologia: 1 } // opzionale, per ordinare il risultato - } + }, + { + $project: { + _id: 0, + IdTipologia: 1, + Descrizione: 1 + } + }, + ]; const rec = await T_WEB_Tipologie.aggregate(myquery); diff --git a/src/server/router/catalogs_router.js b/src/server/router/catalogs_router.js new file mode 100755 index 0000000..14fd3c5 --- /dev/null +++ b/src/server/router/catalogs_router.js @@ -0,0 +1,49 @@ +const express = require('express'); +const router = express.Router(); + +const tools = require('../tools/general'); + +var server_constants = require('../tools/server_constants'); + +var { Project } = require('../models/project'); + +const { User } = require('../models/user'); + +var { authenticate, auth_default } = require('../middleware/authenticate'); + +const _ = require('lodash'); + +const { Catalog } = require('../models/catalog'); + +//GET /catalogs +router.post('/', auth_default, async function (req, res, next) { + const idapp = req.body.idapp; + const userId = req.body.userId; + + let ismanager = await tools.isManagerByReq(req); + + let catalogs = await Catalog.findAllIdApp(idapp, '', undefined, ismanager); + let orders = null; + + if (catalogs) return res.send({ code: server_constants.RIS_CODE_OK, catalogs, orders }); + else return res.status(400).send({ code: server_constants.RIS_CODE_OK, catalogs, orders }); +}); + +router.get('/id/:id', async function (req, res) { + const id = req.params.id; + + try { + var catalog = await Catalog.getCatalogById(id); + + if (catalog) { + return res.send({ code: server_constants.RIS_CODE_OK, catalog: catalog }); + } else { + return res.send({ code: server_constants.RIS_CODE_OK, catalog: null }); + } + } catch (e) { + console.error('Error fetching catalog by ID:', e); + return res.status(400).send({ code: server_constants.RIS_CODE_ERR, msg: e.message }); + } +}); + +module.exports = router; diff --git a/src/server/server.js b/src/server/server.js index 256a6de..a1af47f 100755 --- a/src/server/server.js +++ b/src/server/server.js @@ -128,6 +128,7 @@ connectToDatabase(connectionUrl, options) const site_router = require('./router/site_router'); const admin_router = require('./router/admin_router'); const products_router = require('./router/products_router'); + const catalogs_router = require('./router/catalogs_router'); const cart_router = require('./router/cart_router'); const orders_router = require('./router/orders_router'); const city_router = require('./router/city_router'); @@ -204,7 +205,6 @@ connectToDatabase(connectionUrl, options) // }); }); } - if (process.env.NODE_ENV === 'production') { console.log('*** PRODUCTION! '); } @@ -238,6 +238,7 @@ connectToDatabase(connectionUrl, options) app.use('/site', site_router); app.use('/admin', admin_router); app.use('/products', products_router); + app.use('/catalogs', catalogs_router); app.use('/cart', cart_router); app.use('/orders', orders_router); app.use('/city', city_router);