- Esporta Lista Carrello (Totale)

- Sconto Applicato
This commit is contained in:
Surya Paolo
2025-06-09 09:48:40 +02:00
parent f88f433003
commit d1d4b73da0
7 changed files with 646 additions and 567 deletions

View File

@@ -30,6 +30,9 @@ const CartSchema = new Schema({
note: { note: {
type: String, type: String,
}, },
codice_sconto: {
type: String,
},
note_ordine_gas: { note_ordine_gas: {
type: String, type: String,
}, },
@@ -116,6 +119,7 @@ module.exports.updateCartByUserId = async function (userId, newCart) {
} else { } else {
// Se il carrello non esiste, crea un nuovo documento // Se il carrello non esiste, crea un nuovo documento
const createdCart = new Cart(newCart); const createdCart = new Cart(newCart);
await createdCart.init();
const savedCart = await createdCart.save(); const savedCart = await createdCart.save();
return savedCart; // Restituisce il carrello creato return savedCart; // Restituisce il carrello creato
} }
@@ -133,6 +137,7 @@ module.exports.updateCartByCartId = async function (cartId, newCart) {
const totalPrice = newCart.totalPrice; const totalPrice = newCart.totalPrice;
const totalPriceCalc = newCart.totalPriceCalc; const totalPriceCalc = newCart.totalPriceCalc;
const note = newCart.note; const note = newCart.note;
const codice_sconto = newCart.codice_sconto;
const note_ordine_gas = newCart.note_ordine_gas; const note_ordine_gas = newCart.note_ordine_gas;
const modify_at = new Date(); const modify_at = new Date();
@@ -144,6 +149,7 @@ module.exports.updateCartByCartId = async function (cartId, newCart) {
totalPriceCalc, totalPriceCalc,
totalQty, totalQty,
note, note,
codice_sconto,
note_ordine_gas, note_ordine_gas,
modify_at: new Date(), modify_at: new Date(),
}, },

View File

@@ -1,19 +1,20 @@
const mongoose = require('mongoose').set('debug', false);
const mongoose = require('mongoose').set('debug', false)
const Schema = mongoose.Schema; const Schema = mongoose.Schema;
const shared_consts = require('../tools/shared_nodejs'); const shared_consts = require('../tools/shared_nodejs');
const { ObjectId } = require('mongodb'); const { ObjectId } = require('mongodb');
const Scontistica = require('../models/scontistica');
mongoose.Promise = global.Promise; mongoose.Promise = global.Promise;
mongoose.level = "F"; mongoose.level = 'F';
const fs = require('fs'); // 👈 Usa il modulo promises const fs = require('fs'); // 👈 Usa il modulo promises
// Resolving error Unknown modifier: $pushAll // Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => { mongoose.plugin((schema) => {
schema.options.usePushEach = true schema.options.usePushEach = true;
}); });
const orderSchema = new Schema({ const orderSchema = new Schema({
@@ -22,7 +23,8 @@ const orderSchema = new Schema({
}, },
userId: { type: Schema.Types.ObjectId, ref: 'User' }, userId: { type: Schema.Types.ObjectId, ref: 'User' },
status: { status: {
type: Number, index: true type: Number,
index: true,
}, },
idProduct: { type: Schema.Types.ObjectId, ref: 'Product', index: true }, idProduct: { type: Schema.Types.ObjectId, ref: 'Product', index: true },
idProducer: { type: Schema.Types.ObjectId, ref: 'Producer' }, idProducer: { type: Schema.Types.ObjectId, ref: 'Producer' },
@@ -35,13 +37,13 @@ const orderSchema = new Schema({
default: 0, default: 0,
}, },
after_price: { after_price: {
type: String type: String,
}, },
color: { color: {
type: String type: String,
}, },
size: { size: {
type: String type: String,
}, },
quantity: { quantity: {
type: Number, type: Number,
@@ -62,83 +64,89 @@ const orderSchema = new Schema({
type: Number, type: Number,
default: 0, default: 0,
}, },
confermato: { // e quindi è stato tolto dal magazzino (aggiornando il campo stockQty) confermato: {
// e quindi è stato tolto dal magazzino (aggiornando il campo stockQty)
type: Boolean, type: Boolean,
default: false, default: false,
}, },
date_confermato: { date_confermato: {
type: Date type: Date,
}, },
pagato: { pagato: {
type: Boolean, type: Boolean,
default: false, default: false,
}, },
date_pagato: { date_pagato: {
type: Date type: Date,
}, },
consegnato: { consegnato: {
type: Boolean, type: Boolean,
default: false, default: false,
}, },
date_consegnato: { date_consegnato: {
type: Date type: Date,
}, },
spedito: { spedito: {
type: Boolean, type: Boolean,
default: false, default: false,
}, },
date_spedito: { date_spedito: {
type: Date type: Date,
}, },
ricevuto: { ricevuto: {
type: Boolean, type: Boolean,
default: false, default: false,
}, },
date_ricevuto: { date_ricevuto: {
type: Date type: Date,
}, },
weight: { weight: {
type: Number type: Number,
}, },
unit: { unit: {
type: Number type: Number,
}, },
stars: { stars: {
type: Number type: Number,
}, },
date_created: { date_created: {
type: Date type: Date,
}, },
date_checkout: { date_checkout: {
type: Date type: Date,
}, },
date_payment: { date_payment: {
type: Date type: Date,
}, },
date_shipping: { date_shipping: {
type: Date type: Date,
}, },
date_delivered: { date_delivered: {
type: Date type: Date,
}, },
note: { note: {
type: String type: String,
},
codice_sconto: {
type: String,
}, },
modify_at: { modify_at: {
type: Date, type: Date,
index: true index: true,
}, },
}); });
var Order = module.exports = mongoose.model('Order', orderSchema); var Order = (module.exports = mongoose.model('Order', orderSchema));
module.exports.createIndexes()
.then(() => { })
.catch((err) => { throw err; });
module.exports
.createIndexes()
.then(() => {})
.catch((err) => {
throw err;
});
module.exports.getFieldsForSearch = function () { module.exports.getFieldsForSearch = function () {
return [] return [];
}; };
module.exports.executeQueryTable = function (idapp, params) { module.exports.executeQueryTable = function (idapp, params) {
@@ -149,7 +157,6 @@ module.exports.executeQueryTable = function (idapp, params) {
}; };
module.exports.findAllIdApp = async function (idapp) { module.exports.findAllIdApp = async function (idapp) {
const query = [ const query = [
{ $match: { idapp } }, { $match: { idapp } },
{ {
@@ -157,16 +164,16 @@ module.exports.findAllIdApp = async function (idapp) {
from: 'products', from: 'products',
localField: 'idProduct', localField: 'idProduct',
foreignField: '_id', foreignField: '_id',
as: 'product' as: 'product',
} },
}, },
{ {
$lookup: { $lookup: {
from: 'productinfos', from: 'productinfos',
localField: 'product.idProduct', localField: 'product.idProduct',
foreignField: '_id', foreignField: '_id',
as: 'product.productInfo' as: 'product.productInfo',
} },
}, },
{ {
$unwind: { $unwind: {
@@ -179,24 +186,24 @@ module.exports.findAllIdApp = async function (idapp) {
from: 'producers', from: 'producers',
localField: 'product.idProducer', localField: 'product.idProducer',
foreignField: '_id', foreignField: '_id',
as: 'producer' as: 'producer',
} },
}, },
{ {
$lookup: { $lookup: {
from: 'providers', from: 'providers',
localField: 'product.idProvider', localField: 'product.idProvider',
foreignField: '_id', foreignField: '_id',
as: 'provider' as: 'provider',
} },
}, },
{ {
$lookup: { $lookup: {
from: 'gasordines', from: 'gasordines',
localField: 'idGasordine', localField: 'idGasordine',
foreignField: '_id', foreignField: '_id',
as: 'gasordine' as: 'gasordine',
} },
}, },
{ {
$unwind: { $unwind: {
@@ -206,19 +213,16 @@ module.exports.findAllIdApp = async function (idapp) {
}, },
{ {
$match: { $match: {
$or: [ $or: [{ gasordine: { $exists: false } }, { 'gasordine.active': true }],
{ 'gasordine': { $exists: false } }, },
{ 'gasordine.active': true }
]
}
}, },
{ {
$lookup: { $lookup: {
from: 'scontisticas', from: 'scontisticas',
localField: 'product.idScontisticas', localField: 'product.idScontisticas',
foreignField: '_id', foreignField: '_id',
as: 'scontistica' as: 'scontistica',
} },
}, },
{ {
$unwind: { $unwind: {
@@ -238,144 +242,160 @@ module.exports.findAllIdApp = async function (idapp) {
preserveNullAndEmptyArrays: true, preserveNullAndEmptyArrays: true,
}, },
}, },
]; ];
return await Order.aggregate(query) return await Order.aggregate(query);
}; };
module.exports.getAllOrders = function (query, sort, callback) { module.exports.getAllOrders = function (query, sort, callback) {
Order.find(query, null, sort, callback) Order.find(query, null, sort, callback);
} };
module.exports.getOrderByUserId = function (userId, sort, callback) { module.exports.getOrderByUserId = function (userId, sort, callback) {
Order.find({ userId }, null, sort, callback) Order.find({ userId }, null, sort, callback);
} };
module.exports.getOrderByID = function (id, callback) { module.exports.getOrderByID = function (id, callback) {
Order.findById(id, callback); Order.findById(id, callback);
} };
module.exports.createOrder = async function (order) { module.exports.createOrder = async function (order) {
try { try {
if (order.idGasordine === '') { if (order.idGasordine === '') {
order.idGasordine = undefined; order.idGasordine = undefined;
} }
Order.updateTotals(order); await Order.updateTotals(order);
return await Order.create(order) return await Order.create(order).then((ris) => {
.then((ris) => { if (!!ris) return ris._id;
if (!!ris) return null;
return ris._id; });
return null;
});
} catch (e) { } catch (e) {
console.error('err', e); console.error('err', e);
} }
} };
module.exports.updateStatusOrders = async function (arrOrders, status) { module.exports.updateStatusOrders = async function (arrOrders, status) {
for (const order of arrOrders) { for (const order of arrOrders) {
let ret = await Order.updateOne({ _id: order.order._id }, { $set: { status } }); let ret = await Order.updateOne({ _id: order.order._id }, { $set: { status } });
} }
};
}
module.exports.updateStatusOrdersElements = async function (arrOrders, myelements) { module.exports.updateStatusOrdersElements = async function (arrOrders, myelements) {
for (const order of arrOrders) { for (const order of arrOrders) {
const ret = await Order.findOneAndUpdate({ _id: order.order._id }, { $set: myelements }); const ret = await Order.findOneAndUpdate({ _id: order.order._id }, { $set: myelements });
} }
};
}
module.exports.updateOrderByParams = async function (idOrder, paramstoupdate) { module.exports.updateOrderByParams = async function (idOrder, paramstoupdate) {
const ris = await Order.findOneAndUpdate({ _id: idOrder }, { $set: paramstoupdate }); const ris = await Order.findOneAndUpdate({ _id: idOrder }, { $set: paramstoupdate });
let myorder = await Order.findOne({ _id: idOrder }).lean(); let myorder = await Order.findOne({ _id: idOrder }).lean();
if (paramstoupdate && !paramstoupdate.hasOwnProperty('TotalPriceProduct')) { if (paramstoupdate && !paramstoupdate.hasOwnProperty('TotalPriceProduct')) {
this.updateTotals(myorder); await this.updateTotals(myorder);
await Order.findOneAndUpdate({ _id: idOrder }, { $set: myorder }); await Order.findOneAndUpdate({ _id: idOrder }, { $set: myorder });
} }
return myorder; return myorder;
};
function initOrderTotals(order) {
order.TotalPriceProduct = 0;
order.TotalPriceProductCalc = 0;
order.modify_at = new Date();
} }
module.exports.updateTotals = function (order) { function getNonCumulativeDiscounts(discounts) {
return discounts.filter((rec) => !rec.cumulativo);
}
try { function applyNonCumulativeDiscounts(order, discounts) {
if (!order) { let qtadascontare = order.quantity + order.quantitypreordered;
return; let qtanonscontata = 0;
let sconti_da_applicare = [];
while (qtadascontare > 0) {
let scontoapplicato = null;
for (const sconto of getNonCumulativeDiscounts(discounts)) {
if (qtadascontare >= sconto.qta) {
scontoapplicato = { ...sconto, qtadascontare: sconto.qta };
}
} }
if (scontoapplicato && scontoapplicato.qtadascontare > 0) {
let mypricecalc = 0; sconti_da_applicare.push(scontoapplicato);
order.TotalPriceProduct = 0; qtadascontare -= scontoapplicato.qtadascontare;
order.TotalPriceProductCalc = 0;
order.modify_at = new Date();
// Calcolo Sconto
let sconti_da_applicare = [];
if (order.scontisticas) {
let qtadascontare = order.quantity + order.quantitypreordered
let qtanonscontata = 0
while (qtadascontare > 0) {
let scontoapplicato = null
for (const sconto of order.scontisticas.filter((rec) => !rec.cumulativo)) {
if (qtadascontare >= sconto.qta) {
scontoapplicato = sconto
scontoapplicato.qtadascontare = sconto.qta
}
}
if (scontoapplicato && scontoapplicato.qtadascontare > 0) {
sconti_da_applicare.push(scontoapplicato)
qtadascontare -= scontoapplicato.qtadascontare
} else {
qtanonscontata = qtadascontare
qtadascontare = 0
}
}
/*for (const sconto of order.scontisticas.filter((rec) => rec.cumulativo)) {
if ((sconto.qta % order.quantity) === 0) {
sconti_da_applicare.push(sconto)
}
}*/
if (sconti_da_applicare.length > 0) {
for (const sconto of sconti_da_applicare) {
if (sconto.perc_sconto > 0) {
mypricecalc += (sconto.qtadascontare * order.price) * (1 - (sconto.perc_sconto / 100))
} else {
mypricecalc += sconto.price
}
}
}
if (qtanonscontata > 0) {
mypricecalc += order.price * qtanonscontata;
}
} else { } else {
mypricecalc = (order.price * order.quantity) + (order.price * order.quantitypreordered); qtanonscontata = qtadascontare;
qtadascontare = 0;
}
}
return { sconti_da_applicare, qtanonscontata };
}
function calculateDiscountedPrice(order, sconti_da_applicare, qtanonscontata) {
let total = 0;
for (const sconto of sconti_da_applicare) {
if (sconto.perc_sconto > 0) {
total += sconto.qtadascontare * order.price * (1 - sconto.perc_sconto / 100);
} else {
total += sconto.price;
}
}
if (qtanonscontata > 0) {
total += order.price * qtanonscontata;
}
return total;
}
function calculateFullPrice(order) {
return order.price * order.quantity + order.price * order.quantitypreordered;
}
module.exports.updateTotals = async function (order) {
try {
if (!order) return;
initOrderTotals(order);
let total = 0;
let scontoapplicato = false;
let recscontisticheTrovate = [];
if (order?.codice_sconto) {
recscontisticheTrovate = await Scontistica.find({
idapp: order.idapp,
code: order?.codice_sconto?.toUpperCase(),
applica: shared_consts.SCONTI_APPLICA.A_TUTTI,
}).lean();
} }
order.TotalPriceProductCalc += mypricecalc; // Se ha inserito una scontistica che esiste...
order.TotalPriceProduct += mypricecalc; if (recscontisticheTrovate && recscontisticheTrovate.length > 0) {
const { sconti_da_applicare, qtanonscontata } = applyNonCumulativeDiscounts(order, recscontisticheTrovate);
total = calculateDiscountedPrice(order, sconti_da_applicare, qtanonscontata);
} else if (order.scontisticas && order.scontisticas.length > 0) {
const { sconti_da_applicare, qtanonscontata } = applyNonCumulativeDiscounts(order, order.scontisticas);
total = calculateDiscountedPrice(order, sconti_da_applicare, qtanonscontata);
} else {
total = calculateFullPrice(order);
}
order.TotalPriceProductCalc += total;
order.TotalPriceProduct += total;
order.TotalPriceProductstr = parseFloat(order.TotalPriceProduct.toFixed(2)); order.TotalPriceProductstr = parseFloat(order.TotalPriceProduct.toFixed(2));
return order; return order;
} catch (e) { } catch (e) {
console.error('Err:', e); console.error('Err:', e);
} }
} };
module.exports.getTotalOrderById = async function (id) { module.exports.getTotalOrderById = async function (id) {
const query = [ const query = [
@@ -385,8 +405,8 @@ module.exports.getTotalOrderById = async function (id) {
from: 'products', from: 'products',
localField: 'idProduct', localField: 'idProduct',
foreignField: '_id', foreignField: '_id',
as: 'product' as: 'product',
} },
}, },
{ {
$unwind: { $unwind: {
@@ -399,8 +419,8 @@ module.exports.getTotalOrderById = async function (id) {
from: 'productinfos', from: 'productinfos',
localField: 'product.idProductInfo', localField: 'product.idProductInfo',
foreignField: '_id', foreignField: '_id',
as: 'product.productInfo' as: 'product.productInfo',
} },
}, },
{ {
$unwind: { $unwind: {
@@ -413,8 +433,8 @@ module.exports.getTotalOrderById = async function (id) {
from: 'producers', from: 'producers',
localField: 'product.idProducer', localField: 'product.idProducer',
foreignField: '_id', foreignField: '_id',
as: 'producer' as: 'producer',
} },
}, },
{ {
$unwind: { $unwind: {
@@ -427,8 +447,8 @@ module.exports.getTotalOrderById = async function (id) {
from: 'storehouses', from: 'storehouses',
localField: 'idStorehouse', localField: 'idStorehouse',
foreignField: '_id', foreignField: '_id',
as: 'storehouse' as: 'storehouse',
} },
}, },
{ {
$unwind: { $unwind: {
@@ -441,8 +461,8 @@ module.exports.getTotalOrderById = async function (id) {
from: 'providers', from: 'providers',
localField: 'product.idProvider', localField: 'product.idProvider',
foreignField: '_id', foreignField: '_id',
as: 'provider' as: 'provider',
} },
}, },
{ {
$unwind: { $unwind: {
@@ -455,8 +475,8 @@ module.exports.getTotalOrderById = async function (id) {
from: 'gasordines', from: 'gasordines',
localField: 'idGasordine', localField: 'idGasordine',
foreignField: '_id', foreignField: '_id',
as: 'gasordine' as: 'gasordine',
} },
}, },
{ {
$unwind: { $unwind: {
@@ -466,19 +486,16 @@ module.exports.getTotalOrderById = async function (id) {
}, },
{ {
$match: { $match: {
$or: [ $or: [{ gasordine: { $exists: false } }, { 'gasordine.active': true }],
{ 'gasordine': { $exists: false } }, },
{ 'gasordine.active': true }
]
}
}, },
{ {
$lookup: { $lookup: {
from: 'scontisticas', from: 'scontisticas',
localField: 'product.idScontisticas', localField: 'product.idScontisticas',
foreignField: '_id', foreignField: '_id',
as: 'scontisticas' as: 'scontisticas',
} },
}, },
{ {
$lookup: { $lookup: {
@@ -493,32 +510,34 @@ module.exports.getTotalOrderById = async function (id) {
{ {
$or: [ $or: [
{ {
$eq: ['$status', shared_consts.OrderStatus.CHECKOUT_SENT] $eq: ['$status', shared_consts.OrderStatus.CHECKOUT_SENT],
}, },
{ {
$and: [{ $lt: ['$status', shared_consts.OrderStatus.CHECKOUT_SENT] }, $and: [
{ { $lt: ['$status', shared_consts.OrderStatus.CHECKOUT_SENT] },
$gt: [ {
'$modify_at', $gt: [
{ $subtract: [new Date(), 60 * 60 * 1000] } // 1 hour in milliseconds 60 * 60 '$modify_at',
] { $subtract: [new Date(), 60 * 60 * 1000] }, // 1 hour in milliseconds 60 * 60
}] ],
} },
] ],
} },
] ],
} },
],
},
}, },
}, },
{ {
$group: { $group: {
_id: null, _id: null,
totalQty: { $sum: '$quantity' }, totalQty: { $sum: '$quantity' },
} },
} },
], ],
as: 'productOrders' as: 'productOrders',
} },
}, },
{ {
$lookup: { $lookup: {
@@ -533,32 +552,34 @@ module.exports.getTotalOrderById = async function (id) {
{ {
$or: [ $or: [
{ {
$eq: ['$status', shared_consts.OrderStatus.CHECKOUT_SENT] $eq: ['$status', shared_consts.OrderStatus.CHECKOUT_SENT],
}, },
{ {
$and: [{ $lt: ['$status', shared_consts.OrderStatus.CHECKOUT_SENT] }, $and: [
{ { $lt: ['$status', shared_consts.OrderStatus.CHECKOUT_SENT] },
$gt: [ {
'$modify_at', $gt: [
{ $subtract: [new Date(), 60 * 60 * 1000] } // 1 hour in milliseconds 60 * 60 '$modify_at',
] { $subtract: [new Date(), 60 * 60 * 1000] }, // 1 hour in milliseconds 60 * 60
}] ],
} },
] ],
} },
] ],
} },
} ],
},
},
}, },
{ {
$group: { $group: {
_id: null, _id: null,
totalQtyPreordered: { $sum: '$quantitypreordered' } totalQtyPreordered: { $sum: '$quantitypreordered' },
} },
} },
], ],
as: 'productPreOrders' as: 'productPreOrders',
} },
}, },
{ {
$addFields: { $addFields: {
@@ -568,11 +589,11 @@ module.exports.getTotalOrderById = async function (id) {
$cond: { $cond: {
if: { $isArray: '$productOrders' }, if: { $isArray: '$productOrders' },
then: { $arrayElemAt: ['$productOrders.totalQty', 0] }, then: { $arrayElemAt: ['$productOrders.totalQty', 0] },
else: 0 else: 0,
} },
}, },
0 0,
] ],
}, },
'product.QuantitaPrenotateInAttesa': { 'product.QuantitaPrenotateInAttesa': {
$ifNull: [ $ifNull: [
@@ -580,36 +601,35 @@ module.exports.getTotalOrderById = async function (id) {
$cond: { $cond: {
if: { $isArray: '$productPreOrders' }, if: { $isArray: '$productPreOrders' },
then: { $arrayElemAt: ['$productPreOrders.totalQtyPreordered', 0] }, then: { $arrayElemAt: ['$productPreOrders.totalQtyPreordered', 0] },
else: 0 else: 0,
} },
}, },
0 0,
] ],
}, },
}, },
}, },
{ {
$addFields: { $addFields: {
'product.quantityAvailable': { 'product.quantityAvailable': {
$subtract: ["$product.stockQty", "$product.QuantitaOrdinateInAttesa"], $subtract: ['$product.stockQty', '$product.QuantitaOrdinateInAttesa'],
}, },
'product.bookableAvailableQty': { 'product.bookableAvailableQty': {
$subtract: ["$product.maxbookableGASQty", "$product.QuantitaPrenotateInAttesa"], $subtract: ['$product.maxbookableGASQty', '$product.QuantitaPrenotateInAttesa'],
} },
} },
}, },
{ {
$unset: 'productOrders' $unset: 'productOrders',
}, },
{ {
$unset: 'productPreOrders' $unset: 'productPreOrders',
}, },
]; ];
const ris = await Order.aggregate(query); const ris = await Order.aggregate(query);
return ris; return ris;
} };
module.exports.RemoveDeletedOrdersInOrderscart = async function () { module.exports.RemoveDeletedOrdersInOrderscart = async function () {
try { try {
@@ -620,11 +640,11 @@ module.exports.RemoveDeletedOrdersInOrderscart = async function () {
for (const rec of arrorders) { for (const rec of arrorders) {
let recordercart = await OrdersCart.getOrdersCartById(rec._id); let recordercart = await OrdersCart.getOrdersCartById(rec._id);
let arrord = [] let arrord = [];
let cambiare = false; let cambiare = false;
for (const recOrd of recordercart.items) { for (const recOrd of recordercart.items) {
if (recOrd.order) { if (recOrd.order) {
arrord.push(recOrd) arrord.push(recOrd);
} else { } else {
cambiare = true; cambiare = true;
} }
@@ -647,18 +667,14 @@ module.exports.RemoveDeletedOrdersInOrderscart = async function () {
await Order.findOneAndDelete({ _id: ord._id }); await Order.findOneAndDelete({ _id: ord._id });
} }
}) })
.catch(err => console.error(err)); .catch((err) => console.error(err));
} }
} catch (e) { } catch (e) {
console.error('Err', e); console.error('Err', e);
} }
}; };
module.exports.GeneraCSVOrdineProdotti = async function () { module.exports.GeneraCSVOrdineProdotti = async function () {
const myidGasordine = '65c2a8cc379ee4f57e865ee7'; const myidGasordine = '65c2a8cc379ee4f57e865ee7';
const myquery = [ const myquery = [
@@ -668,8 +684,8 @@ module.exports.GeneraCSVOrdineProdotti = async function () {
from: 'products', from: 'products',
localField: 'idProduct', localField: 'idProduct',
foreignField: '_id', foreignField: '_id',
as: 'product' as: 'product',
} },
}, },
{ {
$unwind: { $unwind: {
@@ -682,8 +698,8 @@ module.exports.GeneraCSVOrdineProdotti = async function () {
from: 'productinfos', from: 'productinfos',
localField: 'product.idProductInfo', localField: 'product.idProductInfo',
foreignField: '_id', foreignField: '_id',
as: 'productInfo' as: 'productInfo',
} },
}, },
{ {
$unwind: { $unwind: {
@@ -695,8 +711,8 @@ module.exports.GeneraCSVOrdineProdotti = async function () {
from: 'gasordines', from: 'gasordines',
localField: 'idGasordine', localField: 'idGasordine',
foreignField: '_id', foreignField: '_id',
as: 'gasordine' as: 'gasordine',
} },
}, },
{ {
$unwind: { $unwind: {
@@ -707,67 +723,57 @@ module.exports.GeneraCSVOrdineProdotti = async function () {
{ {
$match: { $match: {
$or: [ $or: [
{ 'gasordine.active': true }, // Include documents where gasordines.active is true { 'gasordine.active': true }, // Include documents where gasordines.active is true
{ 'gasordine': { $exists: false } } // Include documents where gasordines array doesn't exist { gasordine: { $exists: false } }, // Include documents where gasordines array doesn't exist
] ],
} },
}, },
{ {
$match: { $match: {
$or: [ $or: [{ quantity: { $gt: 0 } }, { quantitypreordered: { $gt: 0 } }],
{ quantity: { $gt: 0 }, }, },
{ quantitypreordered: { $gt: 0 }, }
]
}
}, },
{ {
$group: { $group: {
_id: "$product._id", _id: '$product._id',
name: { $first: "$productInfo.name" }, name: { $first: '$productInfo.name' },
weight: { $first: "$productInfo.weight" }, weight: { $first: '$productInfo.weight' },
price_acquistato: { $first: "$product.price_acquistato" }, price_acquistato: { $first: '$product.price_acquistato' },
totalQuantity: { $sum: { $add: ["$quantity", "$quantitypreordered"] } }, totalQuantity: { $sum: { $add: ['$quantity', '$quantitypreordered'] } },
totalPrice_acquistato: { $sum: { $multiply: ["$product.price_acquistato", { $add: ["$quantity", "$quantitypreordered"] }] } }, totalPrice_acquistato: {
count: { $sum: 1 } $sum: { $multiply: ['$product.price_acquistato', { $add: ['$quantity', '$quantitypreordered'] }] },
} },
count: { $sum: 1 },
},
}, },
{ {
$sort: { $sort: {
name: 1 // Sort in ascending order based on the "date_created" field name: 1, // Sort in ascending order based on the "date_created" field
}, },
} },
]; ];
let myorderscart = await Order.aggregate(myquery); let myorderscart = await Order.aggregate(myquery);
console.log(myorderscart) console.log(myorderscart);
return generateCSV(myorderscart, 'outout.csv'); return generateCSV(myorderscart, 'outout.csv');
};
}
function generateCSV(data, outputPath) { function generateCSV(data, outputPath) {
const headers = ['Num', 'Nome', 'Peso', 'Prezzo', 'Quantita', 'Totale', 'Ordini']; const headers = ['Num', 'Nome', 'Peso', 'Prezzo', 'Quantita', 'Totale', 'Ordini'];
const rows = data.map(item => { const rows = data.map((item) => {
const formattedPrice = item.price_acquistato.toString().replace(/\./g, ','); // Converti "." in "," const formattedPrice = item.price_acquistato.toString().replace(/\./g, ','); // Converti "." in ","
const total = item.totalPrice_acquistato.toString().replace(/\./g, ','); // Converti "." in "," const total = item.totalPrice_acquistato.toString().replace(/\./g, ','); // Converti "." in ","
return [ return [0, `"${item.name}"`, item.weight, formattedPrice, item.totalQuantity, total, item.count];
0,
`"${item.name}"`,
item.weight,
formattedPrice,
item.totalQuantity,
total,
item.count
];
}); });
rows.unshift(headers); rows.unshift(headers);
const csvData = rows.map(row => row.join('|')); const csvData = rows.map((row) => row.join('|'));
fs.writeFile(outputPath, csvData.join('\n'), (err) => { fs.writeFile(outputPath, csvData.join('\n'), (err) => {
if (err) { if (err) {
@@ -778,8 +784,6 @@ function generateCSV(data, outputPath) {
}); });
} }
// const Order = mongoose.model('Order', OrderSchema); // const Order = mongoose.model('Order', OrderSchema);
// module.exports = { Order }; // module.exports = { Order };

View File

@@ -91,6 +91,9 @@ const OrdersCartSchema = new Schema({
note: { note: {
type: String type: String
}, },
codice_sconto: {
type: String
},
note_per_gestore: { note_per_gestore: {
type: String type: String
}, },
@@ -573,6 +576,7 @@ module.exports.updateOrdersCartById = async function(id, newOrdersCart, callback
numorder: newOrdersCart.numorder, numorder: newOrdersCart.numorder,
numord_pers: newOrdersCart.numord_pers, numord_pers: newOrdersCart.numord_pers,
note: newOrdersCart.note, note: newOrdersCart.note,
codice_sconto: newOrdersCart.codice_sconto,
modify_at: new Date(), modify_at: new Date(),
} }
}, },
@@ -1076,9 +1080,9 @@ module.exports.updateOrdersCartTotals = async function (idOrdersCart, update) {
let orderscart = await OrdersCart.getOrdersCartById(idOrdersCart); let orderscart = await OrdersCart.getOrdersCartById(idOrdersCart);
if (orderscart) { if (orderscart) {
let newOrdersCart = CartClass.constructByCart(orderscart); let newOrdersCart = await CartClass.constructByCart(orderscart);
newOrdersCart.updatecarttotals(false); await newOrdersCart.updatecarttotals(false);
await newOrdersCart.updateExtraOrder(); await newOrdersCart.updateExtraOrder();
if (update) { if (update) {
@@ -1088,6 +1092,7 @@ module.exports.updateOrdersCartTotals = async function (idOrdersCart, update) {
totalPriceCalc: newOrdersCart.totalPriceCalc, totalPriceCalc: newOrdersCart.totalPriceCalc,
totalQty: newOrdersCart.totalQty, totalQty: newOrdersCart.totalQty,
note: newOrdersCart.note, note: newOrdersCart.note,
codice_sconto: newOrdersCart.codice_sconto,
modify_at: new Date(), modify_at: new Date(),
}, },
} }

View File

@@ -31,6 +31,9 @@ const scontisticaSchema = new Schema({
price: { price: {
type: Number, type: Number,
}, },
applica: {
type: Number,
},
comulativo: { comulativo: {
type: Boolean, type: Boolean,
default: false, default: false,

View File

@@ -1,5 +1,5 @@
const shared_consts = require('../tools/shared_nodejs'); const shared_consts = require('../tools/shared_nodejs');
const cartModel = require('../models/cart') const cartModel = require('../models/cart');
const { ObjectId } = require('mongodb'); const { ObjectId } = require('mongodb');
@@ -7,6 +7,8 @@ const Gasordine = require('../models/gasordine');
const Order = require('../models/order'); const Order = require('../models/order');
const Scontistica = require('../models/scontistica');
class Cart { class Cart {
constructor(order, arrorders) { constructor(order, arrorders) {
this.modify_at = new Date(); this.modify_at = new Date();
@@ -16,26 +18,50 @@ class Cart {
this.initializeFromOrder(order); this.initializeFromOrder(order);
} else if (!!arrorders) { } else if (!!arrorders) {
for (const ord of arrorders) { for (const ord of arrorders) {
this.items.push(ord) this.items.push(ord);
} }
} }
this.updatecarttotals(false); }
async updatecarttotals(updateCalcPrice = true) {
try {
this.totalQty = 0;
this.totalPrice = 0;
this.totalPriceCalc = 0;
for (const key in this.items) {
const item = this.items[key];
const order = item.order || item;
await this.updateOrderTotals(order, updateCalcPrice);
}
this.totalPrice = parseFloat(this.totalPrice.toFixed(2));
this.totalPriceCalc = parseFloat(this.totalPriceCalc.toFixed(2));
} catch (e) {
console.error("Errore durante l'aggiornamento del carrello:", e);
}
}
async init() {
await this.updatecarttotals(false);
} }
initializeFromOrder(order) { initializeFromOrder(order) {
this.idapp = order.idapp || 0; this.idapp = order.idapp || 0;
this.userId = order.userId || ""; this.userId = order.userId || '';
this.items[order._id] = order; this.items[order._id] = order;
} }
static constructByCart(cart) { static async constructByCart(cart) {
try { try {
const mynewcart = new Cart(null); const mynewcart = new Cart(null);
await mynewcart.init();
mynewcart.idapp = cart.idapp || 0; mynewcart.idapp = cart.idapp || 0;
mynewcart.items = cart.items; mynewcart.items = cart.items;
mynewcart.department = cart.department; mynewcart.department = cart.department;
mynewcart.userId = cart.userId || ""; mynewcart.userId = cart.userId || '';
mynewcart.modify_at = new Date(); mynewcart.modify_at = new Date();
mynewcart.note_ordine_gas = ''; mynewcart.note_ordine_gas = '';
mynewcart.codice_sconto = cart.codice_sconto;
return mynewcart; return mynewcart;
} catch (e) { } catch (e) {
@@ -46,14 +72,14 @@ class Cart {
isAvailableByOrder(order) { isAvailableByOrder(order) {
if (order && order.product) { if (order && order.product) {
return (order.product.quantityAvailable > 0) return order.product.quantityAvailable > 0;
} }
return false; return false;
} }
isInPreorderByOrder(order) { isInPreorderByOrder(order) {
if (order && order.product) { if (order && order.product) {
return (order.product.bookableAvailableQty > 0) return order.product.bookableAvailableQty > 0;
} }
return false; return false;
} }
@@ -61,48 +87,40 @@ class Cart {
isSameStorehouse(itemorder) { isSameStorehouse(itemorder) {
try { try {
if (this.items.length > 0) { if (this.items.length > 0) {
const mystorehouse = this.items[0].order.idStorehouse const mystorehouse = this.items[0].order.idStorehouse;
return (mystorehouse ? mystorehouse._id.toString() === itemorder.idStorehouse : true); return mystorehouse ? mystorehouse._id.toString() === itemorder.idStorehouse : true;
} else { } else {
return true; return true;
} }
} catch (e) { } catch (e) {
return false; return false;
} }
} }
async addqty(itemorder) { async addqty(itemorder) {
const myitem = this.items.find((rec) => rec.order._id.toString() === itemorder._id);
const myitem = this.items.find((rec) => rec.order._id.toString() === itemorder._id)
if (!!myitem) { if (!!myitem) {
let stepmin = myitem.order?.product?.minStepQty || 1; let stepmin = myitem.order?.product?.minStepQty || 1;
let step = stepmin; let step = stepmin;
if (this.isAvailableByOrder(myitem.order)) { if (this.isAvailableByOrder(myitem.order)) {
if (myitem.order.quantity === 0) if (myitem.order.quantity === 0) step = myitem.order.product.minBuyQty ?? stepmin;
step = myitem.order.product.minBuyQty ?? stepmin else if (myitem.order.quantity >= 10) step = stepmin < 2 ? 2 : stepmin;
else if (myitem.order.quantity >= 10) else if (myitem.order.quantity >= 20) step = stepmin < 5 ? 5 : stepmin;
step = stepmin < 2 ? 2 : stepmin
else if (myitem.order.quantity >= 20)
step = stepmin < 5 ? 5 : stepmin
myitem.order.quantity += step; myitem.order.quantity += step;
} else { } else {
if (myitem.order.quantitypreordered === 0) if (myitem.order.quantitypreordered === 0) step = myitem.order.product.minBuyQty ?? stepmin;
step = myitem.order.product.minBuyQty ?? stepmin else if (myitem.order.quantitypreordered >= 10) step = stepmin < 2 ? 2 : stepmin;
else if (myitem.order.quantitypreordered >= 10) else if (myitem.order.quantitypreordered >= 20) step = stepmin < 5 ? 5 : stepmin;
step = stepmin < 2 ? 2 : stepmin
else if (myitem.order.quantitypreordered >= 20)
step = stepmin < 5 ? 5 : stepmin
myitem.order.quantitypreordered += step; myitem.order.quantitypreordered += step;
} }
myitem.order.modify_at = new Date(); myitem.order.modify_at = new Date();
myitem.order = Order.updateTotals(myitem.order); myitem.order = await Order.updateTotals(myitem.order);
this.updatecarttotals(false); await this.updatecarttotals(false);
await this.updateExtraOrder(); await this.updateExtraOrder();
await Order.findOneAndUpdate({ _id: myitem.order._id }, { $set: myitem.order }, { new: false }); await Order.findOneAndUpdate({ _id: myitem.order._id }, { $set: myitem.order }, { new: false });
return myitem.order; return myitem.order;
@@ -110,27 +128,33 @@ class Cart {
} }
qtaNextSub(myorder, myproduct) { qtaNextSub(myorder, myproduct) {
let step = myproduct.minStepQty try {
let minqta = myproduct.minBuyQty let step = myproduct.minStepQty || 1;
if (myproduct.quantityAvailable > 0) { let minqta = myproduct.minBuyQty || 1;
if (myorder.quantity === minqta) if (myproduct.quantityAvailable > 0) {
step = minqta if (myorder.quantity === minqta) {
else { step = minqta;
if ((myorder.quantity - step) < 0) } else {
step = myorder.quantity - step if (myorder.quantity - step < 0) {
step = myorder.quantity - step;
}
}
} else {
if (myorder.quantitypreordered === minqta) {
step = minqta;
}
step = myorder.quantity - stepΩ;
} }
} else { return step;
if (myorder.quantitypreordered === minqta) } catch (e) {
step = minqta console.error('Error in qtaNextSub: ', e);
return 0; // default step value in case of error
} }
return step
} }
async subqty(itemorder) { async subqty(itemorder) {
try { try {
const myitem = this.items.find((rec) => rec.order._id.toString() === itemorder._id) const myitem = this.items.find((rec) => rec.order._id.toString() === itemorder._id);
if (!!myitem) { if (!!myitem) {
let step = this.qtaNextSub(myitem.order, myitem.order.product); let step = this.qtaNextSub(myitem.order, myitem.order.product);
if (myitem.order.quantitypreordered - step >= 0) { if (myitem.order.quantitypreordered - step >= 0) {
@@ -140,8 +164,8 @@ class Cart {
myitem.order.quantity -= step; myitem.order.quantity -= step;
} }
} }
myitem.order = Order.updateTotals(myitem.order); myitem.order = await Order.updateTotals(myitem.order);
this.updatecarttotals(false); await this.updatecarttotals(false);
await this.updateExtraOrder(); await this.updateExtraOrder();
await Order.findOneAndUpdate({ _id: myitem.order._id }, { $set: myitem.order }, { new: false }); await Order.findOneAndUpdate({ _id: myitem.order._id }, { $set: myitem.order }, { new: false });
@@ -152,7 +176,6 @@ class Cart {
} }
} }
async addItem(itemorder) { async addItem(itemorder) {
// this.items.push(itemorder); // this.items.push(itemorder);
@@ -160,7 +183,7 @@ class Cart {
this.items[ind] = {}; this.items[ind] = {};
this.items[ind].order = itemorder; this.items[ind].order = itemorder;
this.items[ind].order = Order.updateTotals(this.items[ind].order); this.items[ind].order = Order.updateTotals(this.items[ind].order);
this.updatecarttotals(false); await this.updatecarttotals(false);
await this.updateExtraOrder(); await this.updateExtraOrder();
return ind; return ind;
@@ -168,8 +191,8 @@ class Cart {
async removeItem(orderId) { async removeItem(orderId) {
// this.items.push(itemorder); // this.items.push(itemorder);
this.items = this.items.filter(item => item.order._id.toString() !== orderId.toString()); this.items = this.items.filter((item) => item.order._id.toString() !== orderId.toString());
this.updatecarttotals(false); await this.updatecarttotals(false);
await this.updateExtraOrder(); await this.updateExtraOrder();
} }
@@ -184,108 +207,98 @@ class Cart {
userId: this.userId, userId: this.userId,
department: this.department, department: this.department,
note: this.note, note: this.note,
codice_sconto: this.codice_sconto,
note_ordine_gas: this.note_ordine_gas, note_ordine_gas: this.note_ordine_gas,
modify_at: this.modify_at modify_at: this.modify_at,
}) });
return newCart return newCart;
} catch (e) { } catch (e) {
console.error('Err', e); console.error('Err', e);
} }
return null; return null;
} }
updatecarttotals(updatecalcprice) { async updateOrderTotals(order, updateCalcPrice) {
try { order.TotalPriceProductCalc = 0;
this.totalQty = 0; if (updateCalcPrice) {
this.totalPrice = 0; order.TotalPriceProduct = 0;
this.totalPriceCalc = 0;
for (const rec in this.items) {
let mypricecalc = 0;
let order = this.items[rec].order;
if (!order) {
order = this.items[rec];
}
order.TotalPriceProductCalc = 0;
if (updatecalcprice) {
order.TotalPriceProduct = 0;
}
this.totalQty += order.quantity + order.quantitypreordered;
// Calcolo Sconto
let sconti_da_applicare = [];
if (order.scontisticas) {
let qtadascontare = order.quantity + order.quantitypreordered
let qtanonscontata = 0
while (qtadascontare > 0) {
let scontoapplicato = null
for (const sconto of order.scontisticas.filter((rec) => !rec.cumulativo)) {
if (qtadascontare >= sconto.qta) {
scontoapplicato = sconto
scontoapplicato.qtadascontare = sconto.qta
}
}
if (scontoapplicato && scontoapplicato.qtadascontare > 0) {
sconti_da_applicare.push(scontoapplicato)
qtadascontare -= scontoapplicato.qtadascontare
} else {
qtanonscontata = qtadascontare
qtadascontare = 0
}
}
/*for (const sconto of order.scontisticas.filter((rec) => rec.cumulativo)) {
if ((sconto.qta % order.quantity) === 0) {
sconti_da_applicare.push(sconto)
}
}*/
if (sconti_da_applicare.length > 0) {
for (const sconto of sconti_da_applicare) {
if (sconto.perc_sconto > 0) {
mypricecalc += (sconto.qtadascontare * order.price) * (1 - (sconto.perc_sconto / 100))
} else {
mypricecalc += sconto.price
}
}
}
if (qtanonscontata > 0) {
mypricecalc += order.price * qtanonscontata;
}
} else {
mypricecalc = (order.price * order.quantity) + (order.price * order.quantitypreordered);
}
// Aggiorna Totali
order.TotalPriceProductCalc += mypricecalc;
if (updatecalcprice) {
order.TotalPriceProduct += mypricecalc;
order.TotalPriceProductstr = parseFloat(order.TotalPriceProduct.toFixed(2));
}
// Qui lo calcolo sempre, anche se lo cambio manualmente
this.totalPriceCalc += mypricecalc;
this.totalPrice += order.TotalPriceProduct;
}
this.totalPrice = parseFloat(this.totalPrice.toFixed(2))
this.totalPriceCalc = parseFloat(this.totalPriceCalc.toFixed(2))
} catch (e) {
console.error('Err: ', e);
} }
const qty = order.quantity + order.quantitypreordered;
this.totalQty += qty;
let recscontisticheTrovate = await Scontistica.find({
idapp: order.idapp,
code: this.codice_sconto?.toUpperCase(),
applica: shared_consts.SCONTI_APPLICA.A_TUTTI,
}).lean();
const scontiDaUsare = recscontisticheTrovate?.length ? recscontisticheTrovate : order.scontisticas || [];
const priceCalc = this.calcolaPrezzoScontato(order, qty, scontiDaUsare);
order.TotalPriceProductCalc += priceCalc;
if (updateCalcPrice) {
order.TotalPriceProduct += priceCalc;
order.TotalPriceProductstr = parseFloat(order.TotalPriceProduct.toFixed(2));
}
this.totalPriceCalc += priceCalc;
this.totalPrice += order.TotalPriceProduct;
}
calcolaPrezzoScontato(order, qtyTotale, sconti = []) {
if (!sconti || sconti.length === 0) {
return order.price * qtyTotale;
}
let scontiApplicati = [];
let qtaRimanente = qtyTotale;
let qtaNonScontata = 0;
// Applica sconti non cumulativi
while (qtaRimanente > 0) {
let scontoScelto = null;
for (const sconto of sconti.filter((s) => !s.cumulativo)) {
if (qtaRimanente >= s.qta) {
scontoScelto = { ...sconto, qtadascontare: s.qta };
break; // prendi il primo valido (puoi migliorare scegliendo il più vantaggioso)
}
}
if (scontoScelto) {
scontiApplicati.push(scontoScelto);
qtaRimanente -= scontoScelto.qtadascontare;
} else {
qtaNonScontata = qtaRimanente;
qtaRimanente = 0;
}
}
let prezzoTotale = 0;
for (const sconto of scontiApplicati) {
if (sconto.perc_sconto > 0) {
prezzoTotale += sconto.qtadascontare * order.price * (1 - sconto.perc_sconto / 100);
} else if (sconto.price > 0) {
prezzoTotale += sconto.price;
}
}
if (qtaNonScontata > 0) {
prezzoTotale += qtaNonScontata * order.price;
}
return prezzoTotale;
} }
async updateExtraOrder() { async updateExtraOrder() {
try { try {
let arrGas = []; let arrGas = [];
const precnoteordgas = this.note_ordine_gas const precnoteordgas = this.note_ordine_gas;
this.note_ordine_gas = ''; this.note_ordine_gas = '';
for (const rec in this.items) { for (const rec in this.items) {
let order = this.items[rec].order; let order = this.items[rec].order;
if (!order) { if (!order) {
order = this.items[rec]; order = this.items[rec];
@@ -296,8 +309,7 @@ class Cart {
if (recGas) { if (recGas) {
if (recGas.note_ordine_gas) { if (recGas.note_ordine_gas) {
if (!arrGas.includes(recGas._id.toString())) { if (!arrGas.includes(recGas._id.toString())) {
if (this.note_ordine_gas) if (this.note_ordine_gas) this.note_ordine_gas += '<br>';
this.note_ordine_gas += '<br>'
this.note_ordine_gas += '<strong>' + recGas.name + '</strong>' + ':<br>' + recGas.note_ordine_gas; this.note_ordine_gas += '<strong>' + recGas.name + '</strong>' + ':<br>' + recGas.note_ordine_gas;
arrGas.push(recGas._id.toString()); arrGas.push(recGas._id.toString());
@@ -306,7 +318,6 @@ class Cart {
} }
} }
} }
} catch (e) { } catch (e) {
console.error('Err:', e); console.error('Err:', e);
} }
@@ -315,10 +326,10 @@ class Cart {
generateArray() { generateArray() {
let arr = []; let arr = [];
for (let id in this.items) { for (let id in this.items) {
arr.push(this.items[id]) arr.push(this.items[id]);
} }
return arr; return arr;
} }
} }
module.exports = Cart module.exports = Cart;

View File

@@ -10,6 +10,8 @@ var server_constants = require('../tools/server_constants');
var { Project } = require('../models/project'); var { Project } = require('../models/project');
const Scontistica = require('../models/scontistica');
var { authenticate, auth_default } = require('../middleware/authenticate'); var { authenticate, auth_default } = require('../middleware/authenticate');
const _ = require('lodash'); const _ = require('lodash');
@@ -28,26 +30,46 @@ const paypal_config = require('../configs/paypal-config')
const paypal = require('paypal-rest-sdk') const paypal = require('paypal-rest-sdk')
*/ */
const CartClass = require('../modules/Cart') const CartClass = require('../modules/Cart');
const Cart = require('../models/cart'); const Cart = require('../models/cart');
const OrdersCart = require('../models/orderscart'); const OrdersCart = require('../models/orderscart');
//GET cart //GET cart
router.get('/:userId', authenticate, async function (req, res, next) { router.get('/:userId', authenticate, async function (req, res, next) {
let userId = req.params.userId let userId = req.params.userId;
let idapp = req.user.idapp let idapp = req.user.idapp;
return await Cart.getCartByUserId(userId, idapp) return await Cart.getCartByUserId(userId, idapp)
.then((cart) => { .then((cart) => {
if (cart) if (cart) return res.send({ code: server_constants.RIS_CODE_OK, cart });
return res.send({ code: server_constants.RIS_CODE_OK, cart }); else return res.send({ code: server_constants.RIS_CODE_OK, cart: null });
else })
return res.send({ code: server_constants.RIS_CODE_OK, cart: null }); .catch((err) => {
}).catch((err) => {
console.error('Err', err); console.error('Err', err);
return res.send({ code: server_constants.RIS_CODE_ERR, cart: null }); return res.send({ code: server_constants.RIS_CODE_ERR, cart: null });
}); });
});
}) async function aggiornaCarrello(mycartpar, userId, idapp) {
try {
let mycart = mycartpar;
if (!mycart) mycart = await Cart.getCartByUserId(userId, idapp);
if (!mycart) {
return null;
}
let newCart = await CartClass.constructByCart(mycart);
// order = await Product.updateProductInOrder(order);
await newCart.updatecarttotals(true);
await newCart.updateExtraOrder();
return newCart;
} catch (e) {
console.error('Err AggiornaCarrello', e);
return null;
}
}
//POST cart //POST cart
router.post('/:userId', authenticate, async function (req, res, next) { router.post('/:userId', authenticate, async function (req, res, next) {
@@ -60,7 +82,6 @@ router.post('/:userId', authenticate, async function (req, res, next) {
try { try {
let mycart = await Cart.getCartByUserId(userId, idapp); let mycart = await Cart.getCartByUserId(userId, idapp);
if (!order) { if (!order) {
return res.send({ code: server_constants.RIS_CODE_OK, cart: null }); return res.send({ code: server_constants.RIS_CODE_OK, cart: null });
} }
@@ -78,15 +99,14 @@ router.post('/:userId', authenticate, async function (req, res, next) {
// no cart save empty cart to database then return response // no cart save empty cart to database then return response
let nuovo = false; let nuovo = false;
if (!mycart) { if (!mycart) {
let oldCart = new CartClass(order) let oldCart = new CartClass(order);
cart = await Cart.createCart(oldCart.generateModel()); cart = await Cart.createCart(oldCart.generateModel());
mycart = await Cart.getCartByUserId(userId, idapp); mycart = await Cart.getCartByUserId(userId, idapp);
nuovo = true; nuovo = true;
} }
let newCart = await CartClass.constructByCart(mycart);
let newCart = CartClass.constructByCart(mycart);
// order = await Product.updateProductInOrder(order); // order = await Product.updateProductInOrder(order);
if (!nuovo) { if (!nuovo) {
// Controlla se sto inserendo un prodotto con 2 Negozi, non permetterlo ! // Controlla se sto inserendo un prodotto con 2 Negozi, non permetterlo !
@@ -101,35 +121,35 @@ router.post('/:userId', authenticate, async function (req, res, next) {
myord = arrord ? arrord[0] : null; myord = arrord ? arrord[0] : null;
} }
} else { } else {
return res.send({ code: server_constants.RIS_CODE_ERR, cart: null, myord: null, msgerr: 'Non è possibile acquistare nello stesso ordine, su negozi differenti!' }); return res.send({
code: server_constants.RIS_CODE_ERR,
cart: null,
myord: null,
msgerr: 'Non è possibile acquistare nello stesso ordine, su negozi differenti!',
});
} }
} else { } else {
newCart.updatecarttotals(true); await newCart.updatecarttotals(true);
await newCart.updateExtraOrder(); await newCart.updateExtraOrder();
const arrord = await Order.getTotalOrderById(order._id); const arrord = await Order.getTotalOrderById(order._id);
myord = arrord ? arrord[0] : null; myord = arrord ? arrord[0] : null;
} }
cart = await Cart.updateCartByCartId(mycart._id, newCart.generateModel()); cart = await Cart.updateCartByCartId(mycart._id, newCart.generateModel());
if (cart) { if (cart) {
const carttot = await Cart.getCartByUserId(userId, idapp); const carttot = await Cart.getCartByUserId(userId, idapp);
if (order.idProduct) if (order.idProduct) product = await Product.getProductById(order.idProduct);
product = await Product.getProductById(order.idProduct); else if (order.product) product = await Product.getProductById(order.product._id);
else if (order.product)
product = await Product.getProductById(order.product._id);
return res.send({ code: server_constants.RIS_CODE_OK, cart: carttot, myord, product }); return res.send({ code: server_constants.RIS_CODE_OK, cart: carttot, myord, product });
} else { } else {
console.error('Err:', err); console.error('Err:', err);
return res.send({ code: server_constants.RIS_CODE_ERR, cart: null, myord: null }); return res.send({ code: server_constants.RIS_CODE_ERR, cart: null, myord: null });
} }
} catch (e) { } catch (e) {
console.error('Err:', e); console.error('Err:', e);
return res.send({ code: server_constants.RIS_CODE_ERR, cart: 0 }); return res.send({ code: server_constants.RIS_CODE_ERR, cart: 0 });
} }
});
})
router.delete('/:userId', authenticate, async function (req, res) { router.delete('/:userId', authenticate, async function (req, res) {
console.log('DELETE Item'); console.log('DELETE Item');
@@ -140,17 +160,16 @@ router.delete('/:userId', authenticate, async function (req, res) {
const mycart = await Cart.getCartByUserId(userId, idapp); const mycart = await Cart.getCartByUserId(userId, idapp);
const ord = await Order.findOne({ _id: orderId }); const ord = await Order.findOne({ _id: orderId });
let idProduct = '' let idProduct = '';
let product = null; let product = null;
if (ord) if (ord) idProduct = ord.idProduct;
idProduct = ord.idProduct;
// Rimuovere l'Ordine // Rimuovere l'Ordine
const recremoved = await Order.deleteOne({ _id: orderId }); const recremoved = await Order.deleteOne({ _id: orderId });
if (recremoved) { if (recremoved) {
// Rimuovere l'id sul Carrello // Rimuovere l'id sul Carrello
let newCart = CartClass.constructByCart(mycart); let newCart = await CartClass.constructByCart(mycart);
await newCart.removeItem(orderId); await newCart.removeItem(orderId);
let carttot = null; let carttot = null;
const cart = await Cart.updateCartByCartId(mycart._id, newCart.generateModel()); const cart = await Cart.updateCartByCartId(mycart._id, newCart.generateModel());
@@ -161,29 +180,27 @@ router.delete('/:userId', authenticate, async function (req, res) {
product = await Product.getProductById(idProduct); product = await Product.getProductById(idProduct);
} }
console.log('carttot', carttot) console.log('carttot', carttot);
return res.send({ code: server_constants.RIS_CODE_OK, cart: carttot, product }); return res.send({ code: server_constants.RIS_CODE_OK, cart: carttot, product });
} }
return res.send({ code: server_constants.RIS_CODE_ERR, cart: null }); return res.send({ code: server_constants.RIS_CODE_ERR, cart: null });
}); });
//PUT cart //PUT cart
router.put('/:userId', authenticate, async function (req, res, next) { router.put('/:userId', authenticate, async function (req, res, next) {
let userId = req.params.userId let userId = req.params.userId;
let requestProduct = req.body let requestProduct = req.body;
let { productId, color, size } = requestProduct.product let { productId, color, size } = requestProduct.product;
try { try {
try { try {
const cart = await Cart.getCartByUserId(userId); const cart = await Cart.getCartByUserId(userId);
try { try {
const myprod = await Product.getProductByID(productId); const myprod = await Product.getProductByID(productId);
let newCart = oldCart.add(myprod, productId, { color, size }) let newCart = oldCart.add(myprod, productId, { color, size });
//exist cart in databse //exist cart in databse
if (cart.length > 0) { if (cart.length > 0) {
@@ -193,7 +210,7 @@ router.put('/:userId', authenticate, async function (req, res, next) {
totalQty: newCart.totalQty, totalQty: newCart.totalQty,
totalPrice: newCart.totalPrice, totalPrice: newCart.totalPrice,
totalPriceCalc: newCart.totalPriceCalc, totalPriceCalc: newCart.totalPriceCalc,
userId: userId userId: userId,
}); });
res.json(result); res.json(result);
} catch (err) { } catch (err) {
@@ -206,16 +223,15 @@ router.put('/:userId', authenticate, async function (req, res, next) {
totalQty: newCart.totalQty, totalQty: newCart.totalQty,
totalPrice: newCart.totalPrice, totalPrice: newCart.totalPrice,
totalPriceCalc: newCart.totalPriceCalc, totalPriceCalc: newCart.totalPriceCalc,
userId: userId userId: userId,
} };
try { try {
const resultCart = await Cart.createCart(newCartobj); const resultCart = await Cart.createCart(newCartobj);
} catch (err) { } catch (err) {
return next(err) return next(err);
} }
res.status(201).json(resultCart); res.status(201).json(resultCart);
} }
} catch (err) { } catch (err) {
return next(err); return next(err);
} }
@@ -223,32 +239,132 @@ router.put('/:userId', authenticate, async function (req, res, next) {
const product = await Product.getProductById(productId); const product = await Product.getProductById(productId);
return res.send({ code: server_constants.RIS_CODE_OK, product }); return res.send({ code: server_constants.RIS_CODE_OK, product });
} catch (err) { } catch (err) {
return next(err) return next(err);
} }
let oldCart = new CartClass(c || {}) let oldCart = new CartClass(c || {});
} catch (e) { } catch (e) {
return res.send({ code: server_constants.RIS_CODE_ERR, status: 0 }); return res.send({ code: server_constants.RIS_CODE_ERR, status: 0 });
} }
});
}) router.post('/:userId/app_sc', authenticate, async function (req, res, next) {
//POST cart
router.post('/:userId/createorderscart', authenticate, async function (req, res, next) {
let idapp = req.body.idapp; let idapp = req.body.idapp;
let cart_id = req.body.cart_id; let cart_id = req.body.cart_id;
let userId = req.params.userId; let userId = req.params.userId;
let status = req.body.status; let codice_sconto = req.body.code;
let note = req.body.note;
let options = req.body.options; let options = req.body.options;
let mycart = null;
let valido = false;
let errmsg = '';
try { try {
let mycart = await Cart.findOne({ _id: cart_id }).lean(); let mycart = await Cart.findOne({ _id: cart_id }).lean();
if (codice_sconto === 'RIMUOVI') {
mycart = await Cart.findOneAndUpdate({ _id: cart_id }, { $set: { codice_sconto: '' } }, { new: true }).lean();
return res.send({ mycart, valido, msg: 'Codice Sconto rimosso', rimuovi: true });
}
// attendi 3 secondi prima di poter inviare una nuova richiesta
await tools.attendiNSecondi(1);
if (codice_sconto) {
const condSconto = { $regex: new RegExp(`^${codice_sconto}$`, 'i') };
recscontisticheTrovate = await Scontistica.find({
idapp: idapp,
code: condSconto,
applica: shared_consts.SCONTI_APPLICA.A_TUTTI,
}).lean();
if (recscontisticheTrovate && recscontisticheTrovate.length > 0) {
if (mycart.codice_sconto !== codice_sconto) {
mycart.codice_sconto = codice_sconto;
await Cart.updateOne({ _id: cart_id }, { $set: { codice_sconto: codice_sconto } });
}
valido = true;
mycart = await aggiornaCarrello(mycart, userId, idapp);
} else {
errmsg = `Codice sconto "${codice_sconto}" non valido oppure scaduto`;
}
}
return res.send({ mycart, valido, errmsg, recsconto: recscontisticheTrovate });
} catch (e) {
console.error('Err Applica Sconto', e);
return res.send({ valido: false, mycart: null, errmsg: e.message });
}
});
// Recupera il carrello
async function getCartById(cart_id) {
const cart = await Cart.findOne({ _id: cart_id }).lean();
return cart;
}
// Crea o aggiorna un ordine partendo dal cart
async function createOrUpdateOrderFromCart({ idapp, cart, userId, status, note }) {
let numorder = await OrdersCart.getLastNumOrder(idapp);
let numord_pers = await OrdersCart.getLastNumOrdPers(userId, idapp);
let myorderCart = await OrdersCart.getRecCartByUserId(userId, idapp, numorder);
if (!myorderCart) {
numorder++;
numord_pers++;
myorderCart = new OrdersCart({
idapp,
items: cart.items,
totalQty: cart.totalQty,
totalPrice: cart.totalPrice,
totalPriceCalc: cart.totalPriceCalc,
note_ordine_gas: cart.note_ordine_gas,
userId,
status,
note,
codice_sconto: cart.codice_sconto,
numorder,
numord_pers,
created_at: new Date(),
modify_at: new Date(),
});
}
return myorderCart;
}
// Gestisce l'invio ordine (checkout)
async function handleCheckout({ myorderCart, mycart, userId, idapp, req, options, userDest }) {
try {
const ris = await OrdersCart.updateOrdersCartById(-1, myorderCart);
await Order.updateStatusOrders(mycart.items, shared_consts.OrderStatus.CHECKOUT_SENT);
await Cart.deleteCartByCartId(mycart._id);
const orders = await OrdersCart.getOrdersCartByUserId(userId, idapp, myorderCart.numorder);
if (orders?.[0]) {
await OrdersCart.updateCmd(orders[0], shared_consts.OrderStatus.CHECKOUT_SENT, true, req, options);
await sendemail.sendEmail_OrderProduct(userDest.lang, idapp, orders[0], userDest);
const updatedOrder = await OrdersCart.findById(myorderCart._id).lean();
return { status: ris.status, orders, recOrderCart: updatedOrder };
}
} catch (err) {
console.error('Errore durante il checkout:', err);
throw err;
}
}
//POST cart
router.post('/:userId/createorderscart', authenticate, async function (req, res) {
const { idapp, cart_id, status, note, options } = req.body;
const userId = req.params.userId;
try {
const mycart = await getCartById(cart_id);
if (!mycart) { if (!mycart) {
return res.send({ return res.send({
code: server_constants.RIS_CODE_OK, code: server_constants.RIS_CODE_OK,
@@ -257,93 +373,43 @@ router.post('/:userId/createorderscart', authenticate, async function (req, res,
}); });
} }
let numorder = await OrdersCart.getLastNumOrder(idapp); let myorderCart = await createOrUpdateOrderFromCart({ idapp, cart: mycart, userId, status, note });
let numord_pers = await OrdersCart.getLastNumOrdPers(userId, idapp); let statusOrderCart = myorderCart.status;
// Esiste l'ordine ?
let myorderCart = await OrdersCart.getRecCartByUserId(userId, idapp, numorder);
if (!myorderCart) {
// crea il nuovo numero d'ordine
numorder++;
numord_pers++;
// SE non esiste allora lo creo !
myorderCart = new OrdersCart({
idapp,
items: mycart.items,
totalQty: mycart.totalQty,
totalPrice: mycart.totalPrice,
totalPriceCalc: mycart.totalPriceCalc,
note_ordine_gas: mycart.note_ordine_gas,
userId,
status,
note,
numorder,
numord_pers,
created_at: new Date(),
modify_at: new Date(),
})
}
statusOrderCart = myorderCart.status;
const idordercart = myorderCart._id;
const userDest = await User.findById(userId).lean(); const userDest = await User.findById(userId).lean();
if (!!mycart) { if (status === shared_consts.OrderStatus.CHECKOUT_SENT) {
if (status === shared_consts.OrderStatus.CHECKOUT_SENT) { try {
const checkoutResult = await handleCheckout({
myorderCart,
mycart,
userId,
idapp,
req,
options,
userDest,
});
try { return res.send({
const ris = await OrdersCart.updateOrdersCartById(-1, myorderCart); code: server_constants.RIS_CODE_OK,
// Gestisci il risultato qui status: checkoutResult.status,
await Order.updateStatusOrders(mycart.items, status); orders: checkoutResult.orders,
recOrderCart: checkoutResult.recOrderCart,
const myris = ris; });
// Cancella il Cart appena salvato in OrdersCart } catch (err) {
return res.send({ code: server_constants.RIS_CODE_ERR, status: 0 });
return Cart.deleteCartByCartId(mycart._id)
.then((ris) => {
return OrdersCart.getOrdersCartByUserId(userId, idapp, numorder)
.then(async (orders) => {
if (!!orders) {
if (orders[0]) {
await OrdersCart.updateCmd(orders[0], status, true, req, options);
// Invia la email dell'Ordine
sendemail.sendEmail_OrderProduct(userDest.lang, idapp, orders[0], userDest)
.then(async (ris) => {
myorderCart = await OrdersCart.findById(idordercart).lean();
return res.send({
code: server_constants.RIS_CODE_OK,
status: myris.status,
orders: orders,
recOrderCart: myorderCart
});
});
}
}
});
})
} catch (err) {
console.error("Errore durante l'aggiornamento dell'ordine:", err);
return res.send({ code: server_constants.RIS_CODE_ERR, status: 0 });
}
} }
} }
return res.send({ return res.send({
code: server_constants.RIS_CODE_OK, code: server_constants.RIS_CODE_OK,
status: statusOrderCart, status: statusOrderCart,
recOrderCart: myorderCart recOrderCart: myorderCart,
}); });
} catch (e) { } catch (e) {
console.error('Err', e); console.error('Errore generale:', e);
return res.send({ code: server_constants.RIS_CODE_ERR, status: 0, recOrderCart: null }); return res.send({ code: server_constants.RIS_CODE_ERR, status: 0, recOrderCart: null });
} }
}); });
//POST cart //POST cart
@@ -356,22 +422,19 @@ router.post('/:userId/ordercartstatus', authenticate, async function (req, res,
const { User } = require('../models/user'); const { User } = require('../models/user');
let myOrdersCart = await OrdersCart.findOne({ idapp, _id: order_id }).lean(); let myOrdersCart = await OrdersCart.findOne({ idapp, _id: order_id }).lean();
if ((userId !== String(req.user._id)) && !User.isManager(req.user.perm)) { if (userId !== String(req.user._id) && !User.isManager(req.user.perm)) {
// I'm trying to write something not mine! // I'm trying to write something not mine!
return res.status(404).send({ code: server_constants.RIS_CODE_TODO_CREATING_NOTMYUSER }); return res.status(404).send({ code: server_constants.RIS_CODE_TODO_CREATING_NOTMYUSER });
} }
try { try {
if (!!myOrdersCart) { if (!!myOrdersCart) {
let fields_to_update = { status }; let fields_to_update = { status };
await OrdersCart.findOneAndUpdate({ _id: order_id }, { $set: fields_to_update } await OrdersCart.findOneAndUpdate({ _id: order_id }, { $set: fields_to_update }, { new: false }).then(
, { new: false }) async (ris) => {
.then(async (ris) => {
const userDest = await User.findById(myOrdersCart.userId).lean(); const userDest = await User.findById(myOrdersCart.userId).lean();
if (ris) { if (ris) {
@@ -390,15 +453,14 @@ router.post('/:userId/ordercartstatus', authenticate, async function (req, res,
} }
if (ordertype !== '') { if (ordertype !== '') {
sendemail.sendEmail_Order(userDest.lang, idapp, myOrdersCart, userDest, ordertype, status) sendemail
.then((ris) => { .sendEmail_Order(userDest.lang, idapp, myOrdersCart, userDest, ordertype, status)
.then((ris) => {});
})
} }
} }
} }
}
}) );
let orderscart = null; let orderscart = null;
@@ -410,14 +472,11 @@ router.post('/:userId/ordercartstatus', authenticate, async function (req, res,
} }
return res.send({ code: server_constants.RIS_CODE_OK, status, orders: orderscart }); return res.send({ code: server_constants.RIS_CODE_OK, status, orders: orderscart });
} }
} catch (e) { } catch (e) {
console.error('err', e); console.error('err', e);
return res.send({ code: server_constants.RIS_CODE_ERR, status: 0 }); return res.send({ code: server_constants.RIS_CODE_ERR, status: 0 });
} }
}); });
//POST cart //POST cart
@@ -428,24 +487,22 @@ router.post('/:userId/gestord', authenticate, async function (req, res, next) {
const { User } = require('../models/user'); const { User } = require('../models/user');
try { try {
let queryord = [];
let queryord = [] let filtroOrdini = [];
let filtroOrdini = []
if (idGasordine) { if (idGasordine) {
const gasordine = { const gasordine = {
$match: { $match: {
idGasordine: { idGasordine: {
$type: "objectId", // Checks if the field is of type ObjectId $type: 'objectId', // Checks if the field is of type ObjectId
$eq: new ObjectId(idGasordine) // Compares the value to a specific ObjectId $eq: new ObjectId(idGasordine), // Compares the value to a specific ObjectId
} },
} },
} };
queryord.push(gasordine) queryord.push(gasordine);
} }
const query = [ const query = [
{ {
$lookup: { $lookup: {
@@ -506,15 +563,15 @@ router.post('/:userId/gestord', authenticate, async function (req, res, next) {
}, },
{ {
$lookup: { $lookup: {
from: "orderscarts", from: 'orderscarts',
localField: "_id", localField: '_id',
foreignField: "items.order", foreignField: 'items.order',
as: "matchingOrders", as: 'matchingOrders',
}, },
}, },
{ {
$match: { $match: {
"matchingOrders": { matchingOrders: {
$ne: [], $ne: [],
}, },
}, },
@@ -539,10 +596,7 @@ router.post('/:userId/gestord', authenticate, async function (req, res, next) {
}, },
totalQuantity: { totalQuantity: {
$sum: { $sum: {
$add: [ $add: ['$quantity', '$quantitypreordered'],
'$quantity',
'$quantitypreordered',
],
}, },
}, },
totalPrice_acquistato: { totalPrice_acquistato: {
@@ -550,10 +604,7 @@ router.post('/:userId/gestord', authenticate, async function (req, res, next) {
$multiply: [ $multiply: [
'$product.price_acquistato', '$product.price_acquistato',
{ {
$add: [ $add: ['$quantity', '$quantitypreordered'],
'$quantity',
'$quantitypreordered',
],
}, },
], ],
}, },
@@ -563,10 +614,7 @@ router.post('/:userId/gestord', authenticate, async function (req, res, next) {
$multiply: [ $multiply: [
'$product.price', '$product.price',
{ {
$add: [ $add: ['$quantity', '$quantitypreordered'],
'$quantity',
'$quantitypreordered',
],
}, },
], ],
}, },
@@ -580,25 +628,22 @@ router.post('/:userId/gestord', authenticate, async function (req, res, next) {
$sort: { $sort: {
name: 1, name: 1,
}, },
} },
] ];
queryord = [...queryord, ...query] queryord = [...queryord, ...query];
filtroOrdini = queryord; filtroOrdini = queryord;
const arrout = await Order.aggregate(filtroOrdini); const arrout = await Order.aggregate(filtroOrdini);
for (const rec of arrout) { for (const rec of arrout) {
} }
return res.send({ code: server_constants.RIS_CODE_OK, arrout }); return res.send({ code: server_constants.RIS_CODE_OK, arrout });
} catch (e) { } catch (e) {
console.error('Err', e); console.error('Err', e);
} }
}); });
module.exports = router; module.exports = router;

View File

@@ -1224,6 +1224,11 @@ module.exports = {
// Download, DVD, Epub, Mobi, Nuovo, PDF, Streaming, Usato // Download, DVD, Epub, Mobi, Nuovo, PDF, Streaming, Usato
PUNTI_PER_POLLICE: 96 PUNTI_PER_POLLICE: 96,
SCONTI_APPLICA: {
NESSUNO: 0,
A_TUTTI: 1,
}
}; };