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