aggiornamento Ordini GAS filtri

This commit is contained in:
Surya Paolo
2024-02-13 18:13:26 +01:00
parent 26ab024514
commit 24f2b46cc8
6 changed files with 663 additions and 90 deletions

View File

@@ -9,6 +9,7 @@ const { ObjectID } = require('mongodb');
mongoose.Promise = global.Promise;
mongoose.level = "F";
const fs = require('fs');
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
@@ -362,7 +363,7 @@ module.exports.updateTotals = function (order) {
} else {
mypricecalc = (order.price * order.quantity) + (order.price * order.quantitypreordered);
}
order.TotalPriceProductCalc += mypricecalc;
order.TotalPriceProduct += mypricecalc;
order.TotalPriceProductstr = parseFloat(order.TotalPriceProduct.toFixed(2));
@@ -607,6 +608,127 @@ module.exports.getTotalOrderById = async function (id) {
return await Order.aggregate(query);
}
module.exports.GeneraCSVOrdineProdotti = async function () {
const myidGasordine = '65c2a8cc379ee4f57e865ee7';
const myquery = [
{ $match: { idGasordine: ObjectID(myidGasordine) } },
{
$lookup: {
from: 'products',
localField: 'idProduct',
foreignField: '_id',
as: 'product'
}
},
{
$unwind: {
path: '$product',
preserveNullAndEmptyArrays: true,
},
},
{
$lookup: {
from: 'productinfos',
localField: 'product.idProductInfo',
foreignField: '_id',
as: 'productInfo'
}
},
{
$unwind: {
path: '$productInfo',
},
},
{
$lookup: {
from: 'gasordines',
localField: 'idGasordine',
foreignField: '_id',
as: 'gasordine'
}
},
{
$unwind: {
path: '$gasordine',
preserveNullAndEmptyArrays: true,
},
},
{
$match: {
$or: [
{ '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 }, }
]
}
},
{
$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 }
}
},
{
$sort: {
name: 1 // Sort in ascending order based on the "date_created" field
},
}
];
let myorderscart = await Order.aggregate(myquery);
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 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
];
});
rows.unshift(headers);
const csvData = rows.map(row => row.join('|'));
fs.writeFile(outputPath, csvData.join('\n'), (err) => {
if (err) {
console.error('Error writing CSV file:', err);
} else {
console.log('CSV file has been successfully generated:', outputPath);
}
});
}
// const Order = mongoose.model('Order', OrderSchema);

View File

@@ -206,97 +206,303 @@ module.exports.getOrdersCartById = async function (id) {
module.exports.getOrdersCartByQuery = async function (query) {
try {
let myorderscart = await OrdersCart.find(query)
.populate('items.order')
.populate({
path: 'items.order',
populate: {
path: 'idProduct',
model: 'Product',
let myorderscart = await OrdersCart.find(query)
.populate('items.order')
.populate({
path: 'items.order',
populate: {
path: 'idProductInfo',
model: 'ProductInfo'
}
}
})
.populate({
path: 'items.order',
populate: {
path: 'idProducer',
model: 'Producer'
}
})
.populate({
path: 'items.order',
populate: {
path: 'idProvider',
model: 'Provider'
}
})
.populate({
path: 'items.order',
populate: {
path: 'idGasordine',
model: 'Gasordine'
}
})
.populate({
path: 'items.order',
populate: {
path: 'idStorehouse',
model: 'Storehouse'
}
})
.populate({
path: 'items.order',
populate: {
path: 'idScontisticas',
model: 'Scontistica'
}
})
.populate({
path: 'userId',
model: 'User',
select: '_id name surname username profile email lang'
})
.lean();
myorderscart = myorderscart.map(order => {
order.user = order.userId;
order.userId = order.user._id;
order.items = order.items.map(item => {
if (item.order) {
try {
if (item.order.idProduct) {
item.order.idProduct.productInfo = item.order.idProduct.productInfo ? item.order.idProduct.productInfo : { ...item.order.idProduct.idProductInfo };
item.order.idProduct.productInfo.unitstr = tools.getUnitsMeasure(item.order.idProduct.productInfo.unit, true);
item.order.idProduct.idProductInfo = item.order.idProduct.productInfo ? item.order.idProduct.productInfo._id : '';
path: 'idProduct',
model: 'Product',
populate: {
path: 'idProductInfo',
model: 'ProductInfo'
}
item.order.product = { ...item.order.idProduct };
item.order.idProduct = item.order.product ? item.order.product._id : '';
item.order.producer = item.order.idProducer;
item.order.idProducer = item.order.producer ? item.order.producer._id : '';
item.order.storehouse = item.order.idStorehouse;
item.order.idStorehouse = item.order.storehouse ? item.order.storehouse._id : '';
item.order.provider = item.order.idProvider;
item.order.idProvider = item.order.provider ? item.order.provider._id : '';
item.order.gasordine = item.order.idGasordine;
item.order.idGasordine = item.order.gasordine ? item.order.gasordine._id : '';
item.order.scontisticas = item.order.scontisticas;
item.order.idScontisticas = item.order.idScontisticas ? item.order.idScontisticas._id : '';
} catch (e) {
console.error('Err: ', e);
}
})
.populate({
path: 'items.order',
populate: {
path: 'idProducer',
model: 'Producer'
}
})
.populate({
path: 'items.order',
populate: {
path: 'idProvider',
model: 'Provider'
}
})
.populate({
path: 'items.order',
populate: {
path: 'idGasordine',
model: 'Gasordine'
}
})
.populate({
path: 'items.order',
populate: {
path: 'idStorehouse',
model: 'Storehouse'
}
})
.populate({
path: 'items.order',
populate: {
path: 'idScontisticas',
model: 'Scontistica'
}
})
.populate({
path: 'userId',
model: 'User',
select: '_id name surname username profile email lang'
})
.lean();
myorderscart = myorderscart.map(order => {
order.user = order.userId;
order.userId = order.user._id;
order.items = order.items.map(item => {
if (item.order) {
try {
if (item.order.idProduct) {
item.order.idProduct.productInfo = item.order.idProduct.productInfo ? item.order.idProduct.productInfo : { ...item.order.idProduct.idProductInfo };
item.order.idProduct.productInfo.unitstr = tools.getUnitsMeasure(item.order.idProduct.productInfo.unit, true);
item.order.idProduct.idProductInfo = item.order.idProduct.productInfo ? item.order.idProduct.productInfo._id : '';
}
const myid = item.order._id;
// console.log('ID ORD', order.numorder, myid, order.user.name);
item.order.product = { ...item.order.idProduct };
item.order.idProduct = item.order.product ? item.order.product._id : '';
item.order.producer = item.order.idProducer;
item.order.idProducer = item.order.producer ? item.order.producer._id : '';
item.order.storehouse = item.order.idStorehouse;
item.order.idStorehouse = item.order.storehouse ? item.order.storehouse._id : '';
item.order.provider = item.order.idProvider;
item.order.idProvider = item.order.provider ? item.order.provider._id : '';
item.order.gasordine = item.order.idGasordine;
item.order.idGasordine = item.order.gasordine ? item.order.gasordine._id : '';
item.order.scontisticas = item.order.scontisticas;
item.order.idScontisticas = item.order.idScontisticas ? item.order.idScontisticas._id : '';
} catch (e) {
console.error('Err: ', e);
}
}
return item;
});
return order;
});
myorderscart = fixupdated(myorderscart);
/*
let myquery = [
{ $match: query }, // Match documents based on your query
{
$unwind: "$items"
},
{
$lookup: {
from: "orders", // Assuming the referenced collection is named "orders"
localField: "items.order",
foreignField: "_id",
as: "items.order"
}
},
{
$unwind: {
path: "$items.order",
preserveNullAndEmptyArrays: true // Preserve items with no matching orders
}
},
{
$lookup: {
from: "products",
localField: "items.order.idProduct",
foreignField: "_id",
as: "items.order.product"
}
},
{
$unwind: {
path: "$items.order.product",
preserveNullAndEmptyArrays: true // Preserve items with no matching orders
}
},
// Populate 'items.order.idProduct.idProductInfo' with 'ProductInfo'
{
$lookup: {
from: "productinfos",
localField: "items.order.product.idProductInfo",
foreignField: "_id",
as: "items.order.product.productInfo"
}
},
{ $unwind: "$items.order.product.productInfo" }, // Deconstruct the array
// Populate 'items.order.idProducer' with 'Producer'
{
$lookup: {
from: "producers",
localField: "items.order.product.IdProducer",
foreignField: "_id",
as: "items.order.producer"
}
},
{
$unwind: {
path: "$items.order.producer",
preserveNullAndEmptyArrays: true // Preserve items with no matching orders
}
},
// Populate 'items.order.idProvider' with 'Provider'
{
$lookup: {
from: "providers",
localField: "items.order.idProvider",
foreignField: "_id",
as: "items.order.provider"
}
},
{
$unwind: {
path: "$items.order.provider",
preserveNullAndEmptyArrays: true // Preserve items with no matching orders
}
},
// Populate 'items.order.idGasordine' with 'Gasordine'
{
$lookup: {
from: "gasordines",
localField: "items.order.idGasordine",
foreignField: "_id",
as: "items.order.gasordine"
}
},
{
$unwind: {
path: "$items.order.gasordine",
preserveNullAndEmptyArrays: true // Preserve items with no matching orders
}
},
// Populate 'items.order.idStorehouse' with 'Storehouse'
{
$lookup: {
from: "storehouses",
localField: "items.order.idStorehouse",
foreignField: "_id",
as: "items.order.storehouse"
}
},
{
$unwind: {
path: "$items.order.storehouse",
preserveNullAndEmptyArrays: true // Preserve items with no matching orders
}
},
// Populate 'items.order.idScontisticas' with 'Scontistica'
{
$lookup: {
from: "scontisticas",
localField: "items.order.product.idScontisticas",
foreignField: "_id",
as: "items.order.scontisticas"
}
},
{
$unwind: {
path: "$items.order.scontisticas",
preserveNullAndEmptyArrays: true // Preserve items with no matching orders
}
},
// Populate 'userId' with 'User'
{
$lookup: {
from: "users",
localField: "userId",
foreignField: "_id",
as: "user"
}
},
{
$unwind: {
path: "$user",
preserveNullAndEmptyArrays: true // Preserve items with no matching orders
}
},
{
$group: {
_id: "$_id",
}
},
{
$project: {
_id: 1,
'user.name': 1,
'user.surname': 1,
'user.username': 1,
'user.profile': 1,
'user.email': 1,
'user.lang': 1,
'totalQty': 1,
'totalQtyPreordered': 1,
'totalPrice': 1,
"totalPriceCalc": 1,
"confermato": 1,
"pagato": 1,
"spedito": 1,
"consegnato": 1,
"preparato": 1,
"ricevuto": 1,
"deleted": 1,
"idapp": 1,
"items": 1,
"userId": 1,
"status": 1,
"note": 1,
"numorder": 1,
"numord_pers": 1,
"created_at": 1,
"modify_at": 1,
}
}
return item;
});
return order;
});
];
myorderscart = fixupdated(myorderscart);
// Project to select specific fields from 'User'
/*{
$project: {
"_id": 1,
"name": "$userId.name",
"surname": "$userId.surname",
"username": "$userId.username",
"profile": "$userId.profile",
"email": "$userId.email",
"lang": "$userId.lang",
"items": 1 // Include other fields as needed
}
}
let myorderscart = await OrdersCart.aggregate(myquery);
*/
return myorderscart;
// Optionally use toArray() to convert cursor to array
return myorderscart;
} catch (e) {
console.error('err', e);
return [];
}
}
module.exports.getOrdersCartByUserId = async function (uid, idapp, numorder, filterStatus) {
@@ -887,6 +1093,19 @@ module.exports.updateOrdersCartTotals = async function (idOrdersCart, update) {
}
)
}
/*
for (const order of orderscart.items) {
await Order.findOneAndUpdate({ _id: order.order._id }, {
$set: {
price: order.order.price,
quantity: order.order.quantity,
quantitypreordered: order.order.quantitypreordered,
TotalPriceProduct: order.order.TotalPriceProduct,
}
})
}*/
orderscart = await OrdersCart.getOrdersCartById(idOrdersCart);
return orderscart;

View File

@@ -19,6 +19,8 @@ const Order = require('../models/order');
const Variant = require('../models/variant');
const { User } = require('../models/user');
const {ObjectID} = require('mongodb');
/*const Department = require('../models/Department')
const Category = require('../models/Category')
const TypedError = require('../modules/ErrorHandler')
@@ -83,7 +85,7 @@ router.post('/:userId', authenticate, async function (req, res, next) {
nuovo = true;
}
let newCart = CartClass.constructByCart(mycart);
// order = await Product.updateProductInOrder(order);
if (!nuovo) {
@@ -397,7 +399,7 @@ router.post('/:userId/ordercartstatus', authenticate, async function (req, res,
}
})
let orderscart = null;
if (User.isManager(user.perm)) {
@@ -418,4 +420,185 @@ router.post('/:userId/ordercartstatus', authenticate, async function (req, res,
});
//POST cart
router.post('/:userId/gestord', authenticate, async function (req, res, next) {
let idapp = req.body.idapp;
const user = req.user;
let idGasordine = req.body.idGasordine;
const { User } = require('../models/user');
try {
let queryord = []
let filtroOrdini = []
if (idGasordine) {
const gasordine = {
$match: {
idGasordine: {
$type: "objectId", // Checks if the field is of type ObjectId
$eq: ObjectID(idGasordine) // Compares the value to a specific ObjectId
}
}
}
queryord.push(gasordine)
}
const query = [
{
$lookup: {
from: 'products',
localField: 'idProduct',
foreignField: '_id',
as: 'product',
},
},
{
$unwind: {
path: '$product',
preserveNullAndEmptyArrays: true,
},
},
{
$lookup: {
from: 'productinfos',
localField: 'product.idProductInfo',
foreignField: '_id',
as: 'productInfo',
},
},
{
$unwind: {
path: '$productInfo',
},
},
{
$lookup: {
from: 'gasordines',
localField: 'idGasordine',
foreignField: '_id',
as: 'gasordine',
},
},
{
$unwind: {
path: '$gasordine',
preserveNullAndEmptyArrays: true,
},
},
{
$match: {
$or: [
{
'gasordine.active': true,
},
{
gasordine: {
$exists: false,
},
},
],
},
},
{
$match: {
$or: [
{
quantity: {
$gt: 0,
},
},
{
quantitypreordered: {
$gt: 0,
},
},
],
},
},
{
$group: {
_id: '$product._id',
name: {
$first: '$productInfo.name',
},
weight: {
$first: '$productInfo.weight',
},
unit: {
$first: '$productInfo.unit',
},
price_acquistato: {
$first: '$product.price_acquistato',
},
price: {
$first: '$product.price',
},
totalQuantity: {
$sum: {
$add: [
'$quantity',
'$quantitypreordered',
],
},
},
totalPrice_acquistato: {
$sum: {
$multiply: [
'$product.price_acquistato',
{
$add: [
'$quantity',
'$quantitypreordered',
],
},
],
},
},
totalPrice: {
$sum: {
$multiply: [
'$product.price',
{
$add: [
'$quantity',
'$quantitypreordered',
],
},
],
},
},
count: {
$sum: 1,
},
},
},
{
$sort: {
name: 1,
},
}
]
queryord = [...queryord, ...query]
filtroOrdini = queryord;
const arrout = await Order.aggregate(filtroOrdini);
for (const rec of arrout) {
}
return res.send({ code: server_constants.RIS_CODE_OK, arrout });
} catch (e) {
console.error('Err', e);
}
});
module.exports = router;

View File

@@ -1245,6 +1245,8 @@ async function eseguiDbOp(idapp, mydata, locale, req, res) {
} else if (mydata.dbop === 'updateReactionsCounts') {
await Reaction.updateReactionsCounts();
} else if (mydata.dbop === 'GeneraCSVOrdineProdotti') {
await Order.GeneraCSVOrdineProdotti();
} else if (mydata.dbop === 'AbilitaNewsletterALL') {
await User.updateMany({
$or: [