- ottimizzato il caricamento del sito

- ottimizzato il caricamento del catalogo.
This commit is contained in:
Surya Paolo
2025-05-15 18:22:43 +02:00
parent 768d299881
commit 3521a88395
9 changed files with 190 additions and 90 deletions

View File

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

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

View File

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

View File

@@ -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) {

View File

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

View File

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

View File

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

View File

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

View File

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