From 24f2b46cc800ee056fc2b9b5a93e96dd13d92d41 Mon Sep 17 00:00:00 2001 From: Surya Paolo Date: Tue, 13 Feb 2024 18:13:26 +0100 Subject: [PATCH] aggiornamento Ordini GAS filtri --- .env.development | 6 +- outout.csv | 47 ++++ src/server/models/order.js | 124 +++++++++- src/server/models/orderscart.js | 387 +++++++++++++++++++++++------- src/server/router/cart_router.js | 187 ++++++++++++++- src/server/router/users_router.js | 2 + 6 files changed, 663 insertions(+), 90 deletions(-) create mode 100644 outout.csv diff --git a/.env.development b/.env.development index 3136acd..61bd7e9 100644 --- a/.env.development +++ b/.env.development @@ -1,11 +1,11 @@ -DATABASE=test_FreePlanet +DATABASE=test_PiuCheBuono UDB=paofreeplanet PDB=mypassword@1A SEND_EMAIL=0 SEND_EMAIL_ORDERS=1 PORT=3000 -appTelegram_TEST=["1","13"] -appTelegram=["1","13"] +appTelegram_TEST=["1","17"] +appTelegram=["1","17"] DOMAIN=mongodb://localhost:27017/ AUTH_MONGODB=true MONGODB_USER=admin diff --git a/outout.csv b/outout.csv new file mode 100644 index 0000000..9a2d305 --- /dev/null +++ b/outout.csv @@ -0,0 +1,47 @@ +Num|Nome|Peso|Prezzo|Quantita|Totale|Ordini +0|"Acqua distillata di rose di Damasco"|100|8|2|16|1 +0|"Artemisia in foglie"|20|1,5|7|10,5|3 +0|"Cannella"|100|3|4|12|3 +0|"Carruba macinata"|250|3|2|6|2 +0|"Cous cous 5 stelle (grano duro, mais, orzo, lenticchie ed avena)"|500|3,5|1|3,5|1 +0|"Cous cous d'avena"|500|3|3|9|2 +0|"Cous cous d'orzo"|500|3|1|3|1 +0|"Cous cous di grano duro (Akka)"|500|3,25|1|3,25|1 +0|"Cous cous di lenticchie"|500|3,5|4|14|3 +0|"Cous cous di miglio"|500|3|4|12|4 +0|"Couscous 5 cereali 1kg"|1|5,5|1|5,5|1 +0|"Couscous di grano duro 500g"|500|2,5|1|2,5|1 +0|"Curcuma"|100|3|5|15|4 +0|"Datteri boufeggous extra 1kg"|1|11|1|11|1 +0|"Datteri boufeggous extra 500g"|500|6,5|3|19,5|3 +0|"Datteri boustahammi 1kg"|1|5|11|55|6 +0|"Datteri boustahammi 500g"|500|3|3|9|3 +0|"Datteri bouzagagh 1kg"|1|5,5|2|11|2 +0|"Datteri bouzagagh 500g"|500|3,5|7|24,5|6 +0|"Farina di segale grigliata 1kg"|1|3,5|1|3,5|1 +0|"Fichi secchi bianchi 250g"|250|5|1|5|1 +0|"Fichi secchi bianchi 500g"|500|9|1|9|1 +0|"Fieno greco"|500|3,5|2|7|1 +0|"Ghassoul (pezzetti di argilla saponifera) per capelli"|100|4|2|8|2 +0|"Henné"|250|3|2|6|2 +0|"Henné (per tatuaggi e capelli)"|200|3,5|1|3,5|1 +0|"Henné (per tatuaggi e capelli)"|150|2,5|1|2,5|1 +0|"Menta Maachi (autoctona) in foglie"|20|1,5|1|1,5|1 +0|"Olio alle rose di Damasco"|60|9|2|18|2 +0|"Olio di argan cosmetico 30ml"|30|8|3|24|2 +0|"Olio di mandorle dolci"|30|5,5|1|5,5|1 +0|"Olio di nigella (cumino nero)"|30|5,5|1|5,5|1 +0|"Olio di sesamo"|30|5,5|1|5,5|1 +0|"Olive nere"|125|2|1|2|1 +0|"Olive nere alle piante aromatiche 1kg"|1|9|1|9|1 +0|"Olive nere alle piante aromatiche 500g"|500|5|1|5|1 +0|"Olive verdi alle piante aromatiche 1kg"|1|9|1|9|1 +0|"Olive verdi alle spezie 500g"|500|5|1|5|1 +0|"Paprika dolce senza olio"|100|3|2|6|2 +0|"Prugne secche"|250|3|2|6|2 +0|"Rose secche di Damasco"|50|2,5|2|5|2 +0|"Sapone a base di olio di argan"|80|4|3|12|3 +0|"Scrub Naama (rosa, in polvere)"|100|5|2|10|2 +0|"Sottopentola medio"|296|2,5|1|2,5|1 +0|"Verbena citronella in foglie"|20|1,5|1|1,5|1 +0|"Zenzero"|100|3|2|6|2 \ No newline at end of file diff --git a/src/server/models/order.js b/src/server/models/order.js index c0f552d..01f7e5b 100755 --- a/src/server/models/order.js +++ b/src/server/models/order.js @@ -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); diff --git a/src/server/models/orderscart.js b/src/server/models/orderscart.js index 3d1a13f..fd769a0 100755 --- a/src/server/models/orderscart.js +++ b/src/server/models/orderscart.js @@ -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; diff --git a/src/server/router/cart_router.js b/src/server/router/cart_router.js index e79fa02..472d481 100755 --- a/src/server/router/cart_router.js +++ b/src/server/router/cart_router.js @@ -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; diff --git a/src/server/router/users_router.js b/src/server/router/users_router.js index 6fa346e..1f6df16 100755 --- a/src/server/router/users_router.js +++ b/src/server/router/users_router.js @@ -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: [