From 05ec2838826d025a36783a4ea58ae8eac2d52ff5 Mon Sep 17 00:00:00 2001 From: Surya Paolo Date: Fri, 15 Dec 2023 00:57:14 +0100 Subject: [PATCH 1/8] import dati prodotti + fornitore + produttore --- emails/ecommerce/order_confirmed/it/html.pug | 10 +- src/server/models/order.js | 19 +++ src/server/models/orderscart.js | 16 ++- src/server/models/product.js | 119 ++++++++++++++++--- src/server/models/provider.js | 64 ++++++++++ src/server/router/admin_router.js | 21 +++- src/server/router/index_router.js | 4 + src/server/tools/globalTables.js | 3 + 8 files changed, 223 insertions(+), 33 deletions(-) create mode 100755 src/server/models/provider.js diff --git a/emails/ecommerce/order_confirmed/it/html.pug b/emails/ecommerce/order_confirmed/it/html.pug index 9a4c742..089d136 100755 --- a/emails/ecommerce/order_confirmed/it/html.pug +++ b/emails/ecommerce/order_confirmed/it/html.pug @@ -40,11 +40,11 @@ html - var index = 0 each product in orders.items - - var descr = product.order.product.name - - var img = product.order.product.img - - var price = product.order.price - - var after_price = product.order.after_price - - var qty = product.order.quantity + - var descr = product.name + - var img = product.img + - var price = product.price + - var after_price = product.after_price + - var qty = product.quantity - index = index + 1 table(cellpadding="0", cellspacing="0", width="100%", summary="", border="0", align="center") diff --git a/src/server/models/order.js b/src/server/models/order.js index cd59553..b5104de 100755 --- a/src/server/models/order.js +++ b/src/server/models/order.js @@ -25,6 +25,7 @@ const orderSchema = new Schema({ idProduct: { type: Schema.Types.ObjectId, ref: 'Product' }, idProducer: { type: Schema.Types.ObjectId, ref: 'Producer' }, idStorehouse: { type: Schema.Types.ObjectId, ref: 'StoreHouse' }, + idProvider: { type: Schema.Types.ObjectId, ref: 'Provider' }, price: { type: Number }, @@ -148,8 +149,17 @@ module.exports.findAllIdApp = async function (idapp) { as: 'producer' } }, + { + $lookup: { + from: 'providers', + localField: 'idProvider', + foreignField: '_id', + as: 'provider' + } + }, { $unwind: '$product' }, { $unwind: '$producer' }, + { $unwind: '$provider' }, ]; return await Order.aggregate(query) @@ -223,9 +233,18 @@ module.exports.getTotalOrderById = async function (id) { as: 'storehouse' } }, + { + $lookup: { + from: 'providers', + localField: 'idProvider', + foreignField: '_id', + as: 'provider' + } + }, { $unwind: '$product' }, { $unwind: '$producer' }, { $unwind: '$storehouse' }, + { $unwind: '$provider' }, ]; return await Order.aggregate(query); diff --git a/src/server/models/orderscart.js b/src/server/models/orderscart.js index 485378f..c7ffd86 100755 --- a/src/server/models/orderscart.js +++ b/src/server/models/orderscart.js @@ -7,6 +7,7 @@ const Order = require('../models/order'); var { User } = require('../models/user'); const Storehouse = require('../models/storehouse'); +const Provider = require('../models/provider'); const Product = require('../models/product'); const tools = require('../tools/general'); @@ -189,12 +190,13 @@ module.exports.getOrdersCartByUserId = async function (uid, idapp, numorder) { path: 'idProducer', model: 'Producer' }, - /* transform: function(doc, populated) { - // Rinomina 'idProduct' a 'product' nei risultati della popolazione - populated.producer = populated.idProducer; - delete populated.idProducer; - return populated; - }, */ + }) + .populate({ + path: 'items.order', + populate: { + path: 'idProvider', + model: 'Provider' + }, }) .populate({ path: 'items.order', @@ -219,6 +221,8 @@ module.exports.getOrdersCartByUserId = async function (uid, idapp, numorder) { delete item.order.idProducer; item.order.storehouse = item.order.idStorehouse; delete item.order.idStorehouse; + item.order.provider = item.order.idProvider; + delete item.order.idProvider; return item; }); return order; diff --git a/src/server/models/product.js b/src/server/models/product.js index 29488f2..3fb8e6f 100755 --- a/src/server/models/product.js +++ b/src/server/models/product.js @@ -4,9 +4,13 @@ const Schema = mongoose.Schema; const tools = require('../tools/general'); const Producer = require('../models/producer'); +const Storehouse = require('../models/storehouse'); +const Provider = require('../models/provider'); const shared_consts = require('../tools/shared_nodejs'); +const { ObjectID } = require('mongodb'); + mongoose.Promise = global.Promise; mongoose.level = "F"; @@ -29,8 +33,10 @@ const productSchema = new Schema({ idStorehouses: [ { type: Schema.Types.ObjectId, ref: 'Storehouse' } ], + idProvider: { type: Schema.Types.ObjectId, ref: 'Provider' }, code: { type: String, + unique: true, }, codice_EAN: { type: String, @@ -139,7 +145,13 @@ const productSchema = new Schema({ }, producer_name: { type: String, - } + }, + provider_name: { + type: String, + }, + magazzino_name: { + type: String, + }, }); var Product = module.exports = mongoose.model('Product', productSchema); @@ -175,6 +187,15 @@ module.exports.findAllIdApp = async function (idapp, code) { } }, { $unwind: '$producer' }, + { + $lookup: { + from: 'providers', + localField: 'idProvider', + foreignField: '_id', + as: 'provider' + } + }, + { $unwind: '$provider' }, { $lookup: { from: 'storehouses', @@ -278,27 +299,93 @@ module.exports.createIndexes((err) => { if (err) throw err; }); -module.exports.convertAfterImport = async function () { +module.exports.convertAfterImport = async function (idapp, dataObjects) { - const arrprod = await Product.find({}).lean(); + const arrprod = await Product.find({idapp}).lean(); for (const prod of arrprod) { + let setta = false; + + // Impostazioni Base: + let objtoset = { + idapp, + img: 'upload/products/' + prod.code + '.jpg', + } + if (prod.producer_name) { - // Cerca il produttore - const recproducer = await Producer.findOne({ name: prod.producer_name }).lean(); - - const campodarimuovere = 'producer_name'; + let recproducer = await Producer.findOne({ idapp, name: prod.producer_name }).lean(); + if (!recproducer) { + // Non esiste questo produttore, quindi lo creo ! + recproducer = await Producer.create({ idapp, name: prod.producer_name }, (err, recordCreato) => { + return recordCreato + }) + } if (recproducer) { - await Product.findOneAndUpdate({ _id: prod._id }, { $set: { idProducer: recproducer._id } }) - await Product.findOneAndUpdate({ _id: prod._id }, { $unset: { [campodarimuovere]: 1 } }) + objtoset = { + ...objtoset, + idProducer: recproducer._id, + } + setta = true; } } + + if (prod.magazzino_name) { + // Cerca il produttore + let recstorehouse = await Storehouse.findOne({ idapp, name: prod.magazzino_name }).lean(); + if (!recstorehouse) { + // Non esiste questo produttore, quindi lo creo ! + recstorehouse = await Storehouse.create({ idapp, name: prod.magazzino_name }, (err, recordCreato) => { + return recordCreato + }) + } + + if (recstorehouse) { + objtoset = { + ...objtoset, + idStorehouses: [recstorehouse._id], + } + setta = true; + } + } + + if (prod.provider_name) { + // Cerca il produttore + let recprovider = await Provider.findOne({ idapp, name: prod.provider_name }).lean(); + if (!recprovider) { + // Non esiste questo produttore, quindi lo creo ! + recprovider = await Provider.create({ idapp, name: prod.provider_name }, (err, recordCreato) => { + return recordCreato + }) + } + + if (recprovider) { + objtoset = { + ...objtoset, + idProvider: recprovider._id, + } + setta = true; + } + } + + // Aggiorna il prezzo ? + const aggiornaprezzo = false; + if (aggiornaprezzo) { + // cerca il prodotto + const myprodinput = dataObjects.find((rec) => rec._id === prod._id) + if (myprodinput) { + objtoset = { + ...objtoset, + price: myprodinput.price, + } + } + } + + if (setta) { + await Product.findOneAndUpdate({ _id: prod._id }, { $set: objtoset }) + + // const campodarimuovere = 'producer_name'; + // await Product.findOneAndUpdate({ _id: prod._id }, { $unset: { [campodarimuovere]: 1 } }) + } } -} - - -// const Product = mongoose.model('Product', ProductSchema); - -// module.exports = { Product }; -// PROVA +} \ No newline at end of file diff --git a/src/server/models/provider.js b/src/server/models/provider.js new file mode 100755 index 0000000..b04367f --- /dev/null +++ b/src/server/models/provider.js @@ -0,0 +1,64 @@ +mongoose = require('mongoose').set('debug', false) +const Schema = mongoose.Schema; + +const tools = require('../tools/general'); + +mongoose.Promise = global.Promise; +mongoose.level = "F"; + + +// Resolving error Unknown modifier: $pushAll +mongoose.plugin(schema => { + schema.options.usePushEach = true +}); + +const providerSchema = new Schema({ + idapp: { + type: String, + }, + name: { + type: String, + }, + description: { + type: String, + }, + referent: { + type: String, + }, + address: { + type: String, + }, + city: { + type: String, + }, + region: { + type: String, + }, + img: { + type: String, + }, + website: { + type: String, + }, +}); + +var Provider = module.exports = mongoose.model('Provider', providerSchema); + +module.exports.getFieldsForSearch = function () { + return [{ field: 'name', type: tools.FieldType.string }] +}; + +module.exports.executeQueryTable = function (idapp, params) { + params.fieldsearch = this.getFieldsForSearch(); + return tools.executeQueryTable(this, idapp, params); +}; + +module.exports.findAllIdApp = async function (idapp) { + const myfind = { idapp }; + + return await Provider.find(myfind); +}; + +module.exports.createIndexes((err) => { + if (err) throw err; +}); diff --git a/src/server/router/admin_router.js b/src/server/router/admin_router.js index f96146c..deb4500 100755 --- a/src/server/router/admin_router.js +++ b/src/server/router/admin_router.js @@ -35,6 +35,7 @@ router.post('/updateval', authenticate, async (req, res) => { router.post('/import', authenticate, async (req, res) => { const cmd = req.body.cmd; + const idapp = req.body.idapp; const data = req.body.data; try { @@ -49,15 +50,23 @@ router.post('/import', authenticate, async (req, res) => { let dataObjects = JSON.parse(`[${data}]`); - return await Product.insertMany(dataObjects).then((ris) => { + // L'opzione ordered: false gestisce gli errori senza interrompere l'inserimento + return await Product.insertMany(dataObjects, { ordered: false }) + .then((ris) => { - Product.convertAfterImport().then((ris) => { - return res.status(200).send(true); + Product.convertAfterImport(idapp, dataObjects).then((ris) => { + return res.status(200).send(true); + }); + + + }) + .catch((errors) => { + console.error(errors); + Product.convertAfterImport(idapp).then((ris) => { + return res.status(200).send(true); + }); }); - - }); - } } catch (e) { console.error('e', e); diff --git a/src/server/router/index_router.js b/src/server/router/index_router.js index b398a93..85db907 100755 --- a/src/server/router/index_router.js +++ b/src/server/router/index_router.js @@ -65,6 +65,7 @@ const Producer = require('../models/producer'); const Cart = require('../models/cart'); const OrdersCart = require('../models/orderscart'); const Storehouse = require('../models/storehouse'); +const Provider = require('../models/provider'); const Department = require('../models/department'); const { Category } = require('../models/category'); const Group = require('../models/group'); @@ -1431,6 +1432,7 @@ function load(req, res, version) { let resps = User.getusersRespList(idapp); let workers = User.getusersWorkersList(idapp); let storehouses = Storehouse.findAllIdApp(idapp); + let providers = Provider.findAllIdApp(idapp); let departments = Department.findAllIdApp(idapp); let categories = Category.findAllIdApp(idapp); @@ -1517,6 +1519,7 @@ function load(req, res, version) { listcircuits, // 37 myelems, // 38 categories, // 39 + providers, ]).then((arrdata) => { // console.table(arrdata); let myuser = req.user; @@ -1599,6 +1602,7 @@ function load(req, res, version) { listcircuits: arrdata[37], myelems: arrdata[38], categories: arrdata[39], + providers: arrdata[40], }); const prova = 1; diff --git a/src/server/tools/globalTables.js b/src/server/tools/globalTables.js index 9613577..ee9ffc6 100755 --- a/src/server/tools/globalTables.js +++ b/src/server/tools/globalTables.js @@ -60,6 +60,7 @@ const Producer = require('../models/producer'); const Cart = require('../models/cart'); const OrdersCart = require('../models/orderscart'); const Storehouse = require('../models/storehouse'); +const Provider = require('../models/provider'); const Department = require('../models/department'); const { Category } = require('../models/category'); const ShareWithUs = require('../models/sharewithus'); @@ -104,6 +105,8 @@ module.exports = { mytable = Product; else if (tablename === 'storehouses') mytable = Storehouse; + else if (tablename === 'providers') + mytable = Provider; else if (tablename === 'departments') mytable = Department; else if (tablename === 'categorys') From 4d9eccd1ae0ed2a38bfa6f0cc86672b47881096c Mon Sep 17 00:00:00 2001 From: Surya Paolo Date: Fri, 15 Dec 2023 21:50:21 +0100 Subject: [PATCH 2/8] Corretto Ordini e visualizzazione dei Totali --- .env.development | 2 + .env.prod.pcb | 1 + .env.test.pcb | 1 + src/server/models/movement.js | 1 - src/server/models/order.js | 25 +-- src/server/models/orderscart.js | 264 ++++++++++----------------- src/server/models/product.js | 188 +++++++++++-------- src/server/router/cart_router.js | 62 +++++-- src/server/router/products_router.js | 5 +- src/server/sendemail.js | 91 +++++---- 10 files changed, 326 insertions(+), 314 deletions(-) diff --git a/.env.development b/.env.development index b06ac29..0e58657 100644 --- a/.env.development +++ b/.env.development @@ -2,6 +2,7 @@ DATABASE=test_PiuCheBuono UDB=paofreeplanet PDB=mypassword@1A SEND_EMAIL=0 +SEND_EMAIL_ORDERS=0 PORT=3000 appTelegram_TEST=["1","13"] appTelegram=["1","13"] @@ -15,6 +16,7 @@ PORT_APP1=8080 SIGNCODE=SU2134hncaskjdbo231oihJSDNHEI$1@AB HTTPS_LOCALHOST=true DEBUG=0 +DEBUG=0 TESTING_ON=1 LOCALE=1 DELAY_SENDEMAIL=2000 diff --git a/.env.prod.pcb b/.env.prod.pcb index 733621b..ff304d6 100644 --- a/.env.prod.pcb +++ b/.env.prod.pcb @@ -2,6 +2,7 @@ DATABASE=PiuCheBuono UDB=paofreeplanet PDB=suerteFreePlanet@1A SEND_EMAIL=1 +SEND_EMAIL_ORDERS=1 PORT=3000 appTelegram_TEST=["17"] appTelegram=["17"] diff --git a/.env.test.pcb b/.env.test.pcb index 5d4fd39..51cb569 100644 --- a/.env.test.pcb +++ b/.env.test.pcb @@ -2,6 +2,7 @@ DATABASE=test_PiuCheBuono UDB=paofreeplanet PDB=suerteFreePlanet@1A SEND_EMAIL=1 +SEND_EMAIL_ORDERS=1 PORT=3001 appTelegram_TEST=["17"] appTelegram=["17"] diff --git a/src/server/models/movement.js b/src/server/models/movement.js index 1f60b75..9c672b4 100755 --- a/src/server/models/movement.js +++ b/src/server/models/movement.js @@ -98,7 +98,6 @@ MovementSchema.statics.addMov = async function (idapp, accountFromIdTable, accou let mymov = await Movement.create( { - _id: new ObjectID().toString(), idapp, transactionDate: new Date(), accountFromId: accountFromIdTable._id, diff --git a/src/server/models/order.js b/src/server/models/order.js index b5104de..3cd0f82 100755 --- a/src/server/models/order.js +++ b/src/server/models/order.js @@ -180,30 +180,33 @@ module.exports.getOrderByID = function (id, callback) { } module.exports.createOrder = async function (order) { - const orderModel = new Order(order); - return await orderModel.save(order) - .then((ris) => { - if (!!ris) - return ris._id; - return null; - }); + try { + 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) { const ret = await this.findOneAndUpdate({ _id: order._id }, { $set: status }); } - + } module.exports.updateStatusOrdersElements = async function (arrOrders, myelements) { - + for (const order of arrOrders) { const ret = await this.findOneAndUpdate({ _id: order._id }, { $set: myelements }); } - + } module.exports.getTotalOrderById = async function (id) { diff --git a/src/server/models/orderscart.js b/src/server/models/orderscart.js index c7ffd86..f653b0f 100755 --- a/src/server/models/orderscart.js +++ b/src/server/models/orderscart.js @@ -6,8 +6,8 @@ const shared_consts = require('../tools/shared_nodejs'); const Order = require('../models/order'); var { User } = require('../models/user'); -const Storehouse = require('../models/storehouse'); -const Provider = require('../models/provider'); +const Storehouse = require('../models/storehouse'); +const Provider = require('../models/provider'); const Product = require('../models/product'); const tools = require('../tools/general'); @@ -35,7 +35,7 @@ const OrdersCartSchema = new Schema({ type: Number, Default: 0, }, - evaso: { // e quindi è stato tolto dal magazzino (aggiornando il campo StockQty) + evaso: { // e quindi è stato tolto dal magazzino (aggiornando il campo stockQty) type: Boolean, default: false, }, @@ -141,10 +141,10 @@ module.exports.getStatusCartByUserId = async function (uid, idapp, numorder) { } module.exports.getRecCartByUserId = async function (uid, idapp, numorder) { - let query = { userId: uid, idapp, status: { $gte: shared_consts.OrderStatus.CHECKOUT_SENT } } + let query = { userId: uid, idapp, status: { $lt: shared_consts.OrderStatus.CHECKOUT_SENT } } let myorderscart = null; if (numorder > 0) { - query = { userId: uid, idapp, numorder, status: { $gte: shared_consts.OrderStatus.CHECKOUT_SENT } } + query = { userId: uid, idapp, numorder, status: { $lt: shared_consts.OrderStatus.CHECKOUT_SENT } } } myorderscart = await OrdersCart.findOne(query).lean(); @@ -160,171 +160,91 @@ module.exports.getOrdersCartById = async function (id) { } module.exports.getOrdersCartByUserId = async function (uid, idapp, numorder) { - let query = { idapp, status: { $gte: shared_consts.OrderStatus.CHECKOUT_SENT }, deleted: false } - let myorderscart = null; - if (numorder > 0) { - query.numorder = numorder; - } + try { + let query = { idapp, status: { $gte: shared_consts.OrderStatus.CHECKOUT_SENT }, deleted: false } + let myorderscart = null; + if (numorder > 0) { + query.numorder = numorder; + } - if (uid !== 'ALL') { - query.userId = uid; - } + if (uid !== 'ALL') { + query.userId = uid; + } - myorderscart = await OrdersCart.find(query).populate('items.order') - .populate({ - path: 'items.order', - populate: { - path: 'idProduct', - model: 'Product' - }, - /*transform: function(doc, populated) { - // Rinomina 'idProduct' a 'product' nei risultati della popolazione - populated.product = populated.idProduct; - delete populated.idProduct; - return populated; - },*/ - }) - .populate({ - path: 'items.order', - populate: { - path: 'idProducer', - model: 'Producer' - }, - }) - .populate({ - path: 'items.order', - populate: { - path: 'idProvider', - model: 'Provider' - }, - }) - .populate({ - path: 'items.order', - populate: { - path: 'idStorehouse', - model: 'Storehouse' - }, - /*transform: function(doc, populated) { - // Rinomina 'idProduct' a 'product' nei risultati della popolazione - populated.storehouse = populated.idStorehouse; - delete populated.idStorehouse; - return populated; - },*/ - }) - .populate('userId').lean(); + /*transform: function(doc, populated) { + // Rinomina 'idProduct' a 'product' nei risultati della popolazione + populated.product = populated.idProduct; + delete populated.idProduct; + return populated; + },*/ + + myorderscart = await OrdersCart.find(query) + .populate('items.order') + .populate({ + path: 'items.order', + populate: { + path: 'idProduct', + model: 'Product' + }, + }) + .populate({ + path: 'items.order', + populate: { + path: 'idProducer', + model: 'Producer' + }, + }) + .populate({ + path: 'items.order', + populate: { + path: 'idProvider', + model: 'Provider' + }, + }) + .populate({ + path: 'items.order', + populate: { + path: 'idStorehouse', + model: 'Storehouse' + }, + }) + .populate({ + path: 'userId', + model: 'User', + select: '_id name surname username profile', // Specify the fields you want to retrieve + }) + .lean(); myorderscart = myorderscart.map(order => { + order.user = order.userId + order.userId = order.user._id order.items = order.items.map(item => { - item.order.product = item.order.idProduct; - delete item.order.idProduct; - item.order.producer = item.order.idProducer; - delete item.order.idProducer; - item.order.storehouse = item.order.idStorehouse; - delete item.order.idStorehouse; - item.order.provider = item.order.idProvider; - delete item.order.idProvider; + if (item.order) { + try { + item.order.product = item.order.idProduct; + item.order.idProduct = item.order.product._id; + item.order.producer = item.order.idProducer; + item.order.idProducer = item.order.producer._id; + item.order.storehouse = item.order.idStorehouse; + item.order.idStorehouse = item.order.storehouse._id; + item.order.provider = item.order.idProvider; + item.order.idProvider = item.order.provider._id; + } catch (e) { + console.error('Err: ', e); + } + } return item; }); return order; }); - /*for (let ind = 0; ind < myorderscart.length; ind++) { - for (const idkey in myorderscart[ind].items) { - try { - let idorder = myorderscart[ind].items[idkey]._id.toString(); - const myorder = myorderscart[ind].items[idkey].order; - if (!!myorder) { - idorder = myorderscart[ind].items[idkey].order._id.toString(); - } - // myorderscart[ind].nameSurname = await User.getNameSurnameById(idapp, myorderscart[ind].userId); - // const myord = await Order.getTotalOrderById(idorder); - // if (myord.length > 0) { - // myorderscart[ind].items[idkey].order = myord[0]; - // } - } catch (e) { - console.log('err', e); - } - } - }*/ - - /* if (!!mycart) { - for (const idkey in mycart.items) { - try { - idorder = mycart.items[idkey]._id.toString(); - const myorder = mycart.items[idkey].order; - if (!!myorder) { - idorder = mycart.items[idkey].order._id.toString(); - } - const myord = await Order.getTotalOrderById(idorder); - if (myord.length > 0) { - mycart.items[idkey]._doc.order = myord[0]; - } - } catch (e) { - console.log('err', e); - } - } - return mycart; - }*/ - return myorderscart + return myorderscart + } catch (e) { + console.error('Err:', e); + } // return null; } -module.exports.getOrdersCartByDepartmentId = async function (depId, idapp) { - let query = { - idapp, status: { $gte: shared_consts.OrderStatus.CHECKOUT_SENT }, - deleted: false, - } - const myorderscart = await OrdersCart.find(query).lean(); - - for (let ind = 0; ind < myorderscart.length; ind++) { - for (const idkey in myorderscart[ind].items) { - try { - let idorder = myorderscart[ind].items[idkey]._id.toString(); - const myorder = myorderscart[ind].items[idkey].order; - if (!!myorder) { - idorder = myorderscart[ind].items[idkey].order._id.toString(); - } - myorderscart[ind].nameSurname = await User.getNameSurnameById(idapp, myorderscart[ind].userId); - const myord = await Order.getTotalOrderById(idorder); - if (myord.length > 0) { - myorderscart[ind].items[idkey].order = myord[0]; - } - } catch (e) { - console.log('err', e); - } - } - } - - return myorderscart - // return null; -} - -module.exports.getOrderById = async function (Id, idapp) { - let query = { _id: Id, idapp, status: { $gte: shared_consts.OrderStatus.CHECKOUT_SENT } } - const myorderscart = await OrdersCart.find(query).lean(); - - for (let ind = 0; ind < myorderscart.length; ind++) { - for (const idkey in myorderscart[ind].items) { - try { - let idorder = myorderscart[ind].items[idkey]._id.toString(); - const myorder = myorderscart[ind].items[idkey].order; - if (!!myorder) { - idorder = myorderscart[ind].items[idkey].order._id.toString(); - } - myorderscart[ind].nameSurname = await User.getNameSurnameById(idapp, myorderscart[ind].userId); - const myord = await Order.getTotalOrderById(idorder); - if (myord.length > 0) { - myorderscart[ind].items[idkey].order = myord[0]; - } - } catch (e) { - console.log('err', e); - } - } - } - - return myorderscart - // return null; -} module.exports.updateOrdersCartById = function (id, newOrdersCart, callback) { let query = { @@ -362,23 +282,30 @@ module.exports.updateOrdersCartById = function (id, newOrdersCart, callback) { module.exports.setFieldInOrdersById = async function (objtoset, myOrderCart) { - const ris = await OrdersCart.findOneAndUpdate( - { _id: myOrderCart._id }, - { - $set: objtoset - }, - { new: false } - ) + try { + let ris2 = null; + // Imposta su tutti i singoli prodotti ordinati (Order) + for (const recitem of myOrderCart.items) { + ris2 = await Order.findOneAndUpdate( + { _id: recitem.order._id }, + { + $set: objtoset + }, + { new: false } + ) + // console.log('ris', ris2); + } - // Imposta su tutti i singoli prodotti ordinati (Order) - for (const order of myOrderCart.items) { - await Order.findOneAndUpdate( - { _id: order._id }, + const ris = await OrdersCart.findOneAndUpdate( + { _id: myOrderCart._id }, { $set: objtoset }, { new: false } ) + + } catch (e) { + console.log('Err', e); } } @@ -463,7 +390,6 @@ module.exports.updateStockQtaDalMagazzino = async function (idorderscart) { if (myorderscart) { for (const idkey in myorderscart.items) { - let idorder = myorderscart.items[idkey]._id; let order = myorderscart.items[idkey].order; if (!order.evaso) { diff --git a/src/server/models/product.js b/src/server/models/product.js index 3fb8e6f..64b22df 100755 --- a/src/server/models/product.js +++ b/src/server/models/product.js @@ -4,8 +4,8 @@ const Schema = mongoose.Schema; const tools = require('../tools/general'); const Producer = require('../models/producer'); -const Storehouse = require('../models/storehouse'); -const Provider = require('../models/provider'); +const Storehouse = require('../models/storehouse'); +const Provider = require('../models/provider'); const shared_consts = require('../tools/shared_nodejs'); @@ -92,10 +92,6 @@ const productSchema = new Schema({ type: Number, default: 0, }, - quantityAvailable: { - type: Number, - default: 0, - }, quantityLow: { //Soglia disponibilità bassa type: Number, default: 0, @@ -167,88 +163,124 @@ module.exports.executeQueryTable = function (idapp, params) { return tools.executeQueryTable(this, idapp, params); }; -module.exports.findAllIdApp = async function (idapp, code) { - let myfind = { idapp, active: true }; +module.exports.getProductByCode = function (idapp, code) { + return Product.findAllIdApp(idapp, code); +} - if (code) { - myfind = { ...myfind, code } - } +module.exports.getProductById = async function (id) { + const arrris = await Product.findAllIdApp('', '', id); + return arrris && arrris.length > 0 ? arrris[0] : null +} - // return await Product.find(myfind); +module.exports.findAllIdApp = async function (idapp, code, id) { + let myfind = {}; + let myqueryadd = {}; + let query = []; - const query = [ - { $match: myfind }, - { - $lookup: { - from: 'producers', - localField: 'idProducer', - foreignField: '_id', - as: 'producer' + try { + + if (idapp) + myfind = { idapp, active: true }; + + if (code) { + myfind = { ...myfind, code } + } + if (id) { + myqueryadd = { + $addFields: { + myId1: { + $toObjectId: id, + }, + }, } - }, - { $unwind: '$producer' }, - { - $lookup: { - from: 'providers', - localField: 'idProvider', - foreignField: '_id', - as: 'provider' + myfind = { + $expr: { + $eq: ["$_id", "$myId1"], + }, } - }, - { $unwind: '$provider' }, - { - $lookup: { - from: 'storehouses', - localField: 'idStorehouses', - foreignField: '_id', - as: 'storehouses' - } - }, - { - $lookup: { - from: 'orders', - let: { productId: '$_id' }, - pipeline: [ - { - $match: { - $expr: { - $and: [ - { $eq: ['$idProduct', '$$productId'] }, - { $lt: ['$status', shared_consts.OrderStatus.ORDER_CONFIRMED] } - ] + + query.push(myqueryadd); + } + + // return await Product.find(myfind); + + query.push( + { $match: myfind }, + { + $lookup: { + from: 'producers', + localField: 'idProducer', + foreignField: '_id', + as: 'producer' + } + }, + { $unwind: '$producer' }, + { + $lookup: { + from: 'providers', + localField: 'idProvider', + foreignField: '_id', + as: 'provider' + } + }, + { $unwind: '$provider' }, + { + $lookup: { + from: 'storehouses', + localField: 'idStorehouses', + foreignField: '_id', + as: 'storehouses' + } + }, + { + $lookup: { + from: 'orders', + let: { productId: '$_id' }, + pipeline: [ + { + $match: { + $expr: { + $and: [ + { $eq: ['$idProduct', '$$productId'] }, + { $lt: ['$status', shared_consts.OrderStatus.ORDER_CONFIRMED] } + ] + } + } + }, + { + $group: { + _id: null, + totalQty: { $sum: '$quantity' } } } - }, - { - $group: { - _id: null, - totalQty: { $sum: '$quantity' } + ], + as: 'productOrders' + } + }, + { + $addFields: { + QuantitaOrdinateInAttesa: { + $cond: { + if: { $isArray: '$productOrders' }, + then: { $arrayElemAt: ['$productOrders.totalQty', 0] }, + else: 0 } } - ], - as: 'productOrders' - } - }, - { - $addFields: { - QuantitaOrdinateInAttesa: { - $cond: { - if: { $isArray: '$productOrders' }, - then: { $arrayElemAt: ['$productOrders.totalQty', 0] }, - else: 0 - } } - } - }, - { - $unset: 'productOrders' - }, + }, + { + $unset: 'productOrders' + }, - ]; + ); - let ris = await Product.aggregate(query) + let ris = await Product.aggregate(query) - return ris; + return ris; + + } catch (e) { + console.error('E', e); + } }; @@ -269,10 +301,6 @@ module.exports.getProductByTitle = function (query, sort, callback) { Product.find(query, null, sort, callback) } -module.exports.getProductByCode = function (idapp, code) { - return Product.findOne({ idapp, code }) -} - module.exports.filterProductByDepartment = function (department, callback) { let regexp = new RegExp(`^${department}$`, 'i') var query = { department: { $regex: regexp } }; @@ -301,7 +329,7 @@ module.exports.createIndexes((err) => { module.exports.convertAfterImport = async function (idapp, dataObjects) { - const arrprod = await Product.find({idapp}).lean(); + const arrprod = await Product.find({ idapp }).lean(); for (const prod of arrprod) { let setta = false; diff --git a/src/server/router/cart_router.js b/src/server/router/cart_router.js index 673b4e1..51a63b3 100755 --- a/src/server/router/cart_router.js +++ b/src/server/router/cart_router.js @@ -55,20 +55,27 @@ router.post('/:userId', authenticate, async function (req, res, next) { let order = req.body.order; try { - const mycart = await Cart.getCartByUserId(userId, idapp); + let mycart = await Cart.getCartByUserId(userId, idapp); // const myorder = Order.getOrderByID(order._id); if (!addqty && !subqty) order._id = await Order.createOrder(order); let cart = null; + let product = null; // no cart save empty cart to database then return response let myqty = 0; + let nuovo = false; if (!mycart) { let oldCart = new CartClass(order) cart = await Cart.createCart(oldCart.generateModel()); - } else { - let newCart = CartClass.constructByCart(mycart); + + mycart = await Cart.getCartByUserId(userId, idapp); + nuovo = true; + } + + let newCart = CartClass.constructByCart(mycart); + if (!nuovo) { if (addqty) { myqty = await newCart.addqty(order); } else if (subqty) { @@ -76,11 +83,19 @@ router.post('/:userId', authenticate, async function (req, res, next) { } else { const ind = newCart.addItem(order); } - cart = await Cart.updateCartByCartId(mycart._id, newCart.generateModel()); + } else { + await newCart.updatetotals(); } + cart = await Cart.updateCartByCartId(mycart._id, newCart.generateModel()); + + if (cart) { const carttot = await Cart.getCartByUserId(userId, idapp); - return res.send({ code: server_constants.RIS_CODE_OK, cart: carttot, qty: myqty }); + if (order.idProduct) + product = await Product.getProductById(order.idProduct); + else if (order.product) + product = await Product.getProductById(order.product._id); + return res.send({ code: server_constants.RIS_CODE_OK, cart: carttot, qty: myqty, product }); } else { return res.send({ code: server_constants.RIS_CODE_ERR, cart: null }); } @@ -112,6 +127,12 @@ router.delete('/:userId', authenticate, async function (req, res) { const mycart = await Cart.getCartByUserId(userId, idapp); + const ord = await Order.findOne({ _id: orderId }); + let idProduct = '' + let product = null; + if (ord) + idProduct = ord.idProduct; + // Rimuovere l'Ordine const recremoved = await Order.deleteOne({ _id: orderId }); if (recremoved) { @@ -124,8 +145,12 @@ router.delete('/:userId', authenticate, async function (req, res) { carttot = await Cart.getCartByUserId(userId, idapp); + if (idProduct) { + product = await Product.getProductById(idProduct); + } + console.log('carttot', carttot) - return res.send({ code: server_constants.RIS_CODE_OK, cart: carttot }); + return res.send({ code: server_constants.RIS_CODE_OK, cart: carttot, product }); } return res.send({ code: server_constants.RIS_CODE_ERR, cart: null }); @@ -140,17 +165,17 @@ router.put('/:userId', authenticate, async function (req, res, next) { try { - await Cart.getCartByUserId(userId, function (err, c) { + await Cart.getCartByUserId(userId, async function (err, c) { if (err) return next(err) - let oldCart = new CartClass(c[0] || {}) + let oldCart = new CartClass(c || {}) - Product.getProductByID(productId, function (err, p) { + await Product.getProductByID(productId, async function (err, p) { if (err) return next(err) let newCart = oldCart.add(p, productId, { color, size }) //exist cart in databse if (c.length > 0) { - Cart.updateCartByUserId( + await Cart.updateCartByUserId( userId, { items: newCart.items, @@ -164,13 +189,13 @@ router.put('/:userId', authenticate, async function (req, res, next) { }) } else { //no cart in database - newCart = new Cart({ + let newCartobj = { items: newCart.items, totalQty: newCart.totalQty, totalPrice: newCart.totalPrice, userId: userId - }) - Cart.createCart(newCart, function (err, resultCart) { + } + await Cart.createCart(newCartobj, function (err, resultCart) { if (err) return next(err) res.status(201).json(resultCart) }) @@ -178,7 +203,9 @@ router.put('/:userId', authenticate, async function (req, res, next) { }) }) - return res.send({ code: server_constants.RIS_CODE_OK }); + const product = await Product.getProductById(productId); + + return res.send({ code: server_constants.RIS_CODE_OK, product }); } catch (e) { return res.send({ code: server_constants.RIS_CODE_ERR, status: 0 }); } @@ -192,6 +219,7 @@ router.post('/:userId/createorderscart', authenticate, async function (req, res, let userId = req.params.userId; const user = req.user; let status = req.body.status; + let note = req.body.note; try { const mycart = await Cart.findOne({ _id: cart_id }); @@ -213,7 +241,7 @@ router.post('/:userId/createorderscart', authenticate, async function (req, res, totalPrice: mycart.totalPrice, userId, status, - note: mycart.note, + note, numorder, created_at: new Date(), modify_at: new Date(), @@ -221,6 +249,8 @@ router.post('/:userId/createorderscart', authenticate, async function (req, res, } statusOrderCart = myorderCart.status; + const idordercart = myorderCart._id; + if (!!mycart) { if (status === shared_consts.OrderStatus.CHECKOUT_SENT) { @@ -246,7 +276,7 @@ router.post('/:userId/createorderscart', authenticate, async function (req, res, // Invia la email dell'Ordine sendemail.sendEmail_OrderProduct(user.lang, idapp, orders[0], user) .then(async (ris) => { - myorderCart = await OrdersCart.getRecCartByUserId(userId, idapp, numorder); + myorderCart = await OrdersCart.findById(idordercart).lean(); return res.send({ code: server_constants.RIS_CODE_OK, status: myris.status, diff --git a/src/server/router/products_router.js b/src/server/router/products_router.js index 658f793..8a9bb77 100755 --- a/src/server/router/products_router.js +++ b/src/server/router/products_router.js @@ -12,6 +12,7 @@ var { authenticate, auth_default } = require('../middleware/authenticate'); const _ = require('lodash'); const Product = require('../models/product'); +const OrdersCart = require('../models/orderscart'); const Variant = require('../models/variant'); /*const Department = require('../models/Department') @@ -27,11 +28,13 @@ const Cart = require('../models/cart'); //GET /products router.post('/', auth_default, async function (req, res, next) { const idapp = req.body.idapp; + let userId = req.body.userId; var products = await Product.findAllIdApp(idapp, ""); + var orders = await OrdersCart.getOrdersCartByUserId(userId, idapp, 0); if (products) - res.send({ code: server_constants.RIS_CODE_OK, products }); + res.send({ code: server_constants.RIS_CODE_OK, products, orders }); else res.status(400).send(e); diff --git a/src/server/sendemail.js b/src/server/sendemail.js index 185fb25..ef72463 100755 --- a/src/server/sendemail.js +++ b/src/server/sendemail.js @@ -742,57 +742,76 @@ module.exports = { sendEmail_OrderProduct: async function (lang, idapp, orders, user) { - const msginizio = 'Ordine n: ' + orders.numorder + ' ' + user.name + ' ' + user.surname; - console.log(msginizio); + try { + const msginizio = 'Ordine n: ' + orders.numorder + ' ' + user.name + ' ' + user.surname; + console.log(msginizio); - await telegrambot.sendMsgTelegramToTheManagers(idapp, msginizio); + if (process.env.SEND_EMAIL_ORDERS === '1') { - let mylocalsconf = { - idapp, - locale: lang, - nomeapp: tools.getNomeAppByIdApp(idapp), - orders, - baseurl: tools.getHostByIdApp(idapp), - dataemail: await this.getdataemail(idapp), - ordernumber: orders.numorder, - user, - }; + await telegrambot.sendMsgTelegramToTheManagers(idapp, msginizio); - mylocalsconf = this.setParamsForTemplate(user, mylocalsconf); + let mylocalsconf = { + idapp, + locale: lang, + nomeapp: tools.getNomeAppByIdApp(idapp), + orders, + baseurl: tools.getHostByIdApp(idapp), + dataemail: await this.getdataemail(idapp), + ordernumber: orders.numorder, + user, + }; - this.sendEmail_base_e_manager(idapp, 'ecommerce/makeorder/' + lang, mylocalsconf.emailto, mylocalsconf, - mylocalsconf.dataemail.email_reply); + mylocalsconf = this.setParamsForTemplate(user, mylocalsconf); + + this.sendEmail_base_e_manager(idapp, 'ecommerce/makeorder/' + lang, mylocalsconf.emailto, mylocalsconf, + mylocalsconf.dataemail.email_reply); + } else { + console.log('Invio Email non eseguito perchè sei in TEST !'); + } + } catch (e) { + console.error('Err:', e); + } }, sendEmail_Order: async function (lang, idapp, orders, user, ordertype, status) { - const msginizio = 'INIZIO - sendEmail_Order ' + ordertype + ': ' + tools.getNomeAppByIdApp(idapp); - console.log(msginizio); + try { + const msginizio = 'INIZIO - sendEmail_Order ' + ordertype + ': ' + tools.getNomeAppByIdApp(idapp); + console.log(msginizio); - await telegrambot.sendMsgTelegramToTheManagers(idapp, msginizio); + if (process.env.SEND_EMAIL_ORDERS === '1') { - let mylocalsconf = { - idapp, - locale: lang, - nomeapp: tools.getNomeAppByIdApp(idapp), - orders, - baseurl: tools.getHostByIdApp(idapp), - dataemail: await this.getdataemail(idapp), - ordernumber: orders.numorder, - user, - }; + await telegrambot.sendMsgTelegramToTheManagers(idapp, msginizio); - mylocalsconf = this.setParamsForTemplate(user, mylocalsconf); + let mylocalsconf = { + idapp, + locale: lang, + nomeapp: tools.getNomeAppByIdApp(idapp), + orders, + baseurl: tools.getHostByIdApp(idapp), + dataemail: await this.getdataemail(idapp), + ordernumber: orders.numorder, + user, + }; - if ((status !== shared_consts.OrderStatus.CANCELED) && (status !== shared_consts.OrderStatus.COMPLETED)) { - const esito = this.sendEmail_base('ecommerce/' + ordertype + '/' + lang, mylocalsconf.emailto, mylocalsconf, - mylocalsconf.dataemail.email_reply); + mylocalsconf = this.setParamsForTemplate(user, mylocalsconf); - this.sendEmail_base('ecommerce/' + ordertype + '/' + lang, tools.getAdminEmailByIdApp(idapp), mylocalsconf, ''); + if ((status !== shared_consts.OrderStatus.CANCELED) && (status !== shared_consts.OrderStatus.COMPLETED)) { + const esito = this.sendEmail_base('ecommerce/' + ordertype + '/' + lang, mylocalsconf.emailto, mylocalsconf, + mylocalsconf.dataemail.email_reply); - if (tools.isManagAndAdminDifferent(idapp)) { - this.sendEmail_base('ecommerce/' + ordertype + '/' + lang, tools.getManagerEmailByIdApp(idapp), mylocalsconf, ''); + this.sendEmail_base('ecommerce/' + ordertype + '/' + lang, tools.getAdminEmailByIdApp(idapp), mylocalsconf, ''); + + if (tools.isManagAndAdminDifferent(idapp)) { + this.sendEmail_base('ecommerce/' + ordertype + '/' + lang, tools.getManagerEmailByIdApp(idapp), mylocalsconf, ''); + } + } + } else { + console.log('Invio Email non eseguito perchè sei in TEST !'); } + + } catch (e) { + console.error('Err:', e); } }, From 1ca72118f11c22022a7ff2d6037295a55e340db2 Mon Sep 17 00:00:00 2001 From: Surya Paolo Date: Fri, 15 Dec 2023 23:36:43 +0100 Subject: [PATCH 3/8] lista ordini aggiornata --- src/server/models/orderscart.js | 18 +++++++++++++++++- src/server/models/site.js | 3 +++ src/server/models/user.js | 10 ++++++++++ src/server/router/cart_router.js | 5 ++++- src/server/router/products_router.js | 12 ++++++++++-- 5 files changed, 44 insertions(+), 4 deletions(-) diff --git a/src/server/models/orderscart.js b/src/server/models/orderscart.js index f653b0f..023d8d7 100755 --- a/src/server/models/orderscart.js +++ b/src/server/models/orderscart.js @@ -19,6 +19,7 @@ const OrdersCartSchema = new Schema({ type: String }, numorder: { type: Number }, + numord_pers: { type: Number }, userId: { type: Schema.Types.ObjectId, ref: 'User' }, totalQty: { type: Number, default: 0 }, totalPrice: { type: Number, default: 0 }, @@ -110,7 +111,21 @@ module.exports.getFieldsForSearch = function () { }; -module.exports.getLastNumOrder = async function (uid, idapp) { +module.exports.getLastNumOrder = async function (idapp) { + let query = { idapp, deleted: false } + let numorder = 100; + let numorderrec = await OrdersCart.find(query).sort({ numorder: -1 }).limit(1); + + if (numorderrec && numorderrec.length > 0) + numorder = numorderrec[0].numorder; + else + numorder = 100; + + return numorder; + +}; + +module.exports.getLastNumOrdPers = async function (uid, idapp) { let query = { userId: uid, idapp, deleted: false } let numorder = 1; let numorderrec = await OrdersCart.find(query).sort({ numorder: -1 }).limit(1); @@ -266,6 +281,7 @@ module.exports.updateOrdersCartById = function (id, newOrdersCart, callback) { userId: userId, status: newOrdersCart.status, numorder: newOrdersCart.numorder, + numord_pers: newOrdersCart.numord_pers, note: newOrdersCart.note, modify_at: new Date(), } diff --git a/src/server/models/site.js b/src/server/models/site.js index 4be0b69..da043f6 100755 --- a/src/server/models/site.js +++ b/src/server/models/site.js @@ -176,6 +176,9 @@ const SiteSchema = new Schema({ info2: { type: String, default: '' }, cell: { type: String, default: '' }, }, + ecomm: { + enablePreOrders: { type: Boolean, default: false }, + } }); var Site = module.exports = mongoose.model('Site', SiteSchema); diff --git a/src/server/models/user.js b/src/server/models/user.js index 87fb04a..bd376b8 100755 --- a/src/server/models/user.js +++ b/src/server/models/user.js @@ -625,6 +625,16 @@ UserSchema.statics.isManager = function (perm) { } }; +UserSchema.statics.isManagerById = async function (id) { + try { + const ris = await User.findOne({ _id: id }, { perm: 1 }).lean(); + return ((ris.perm & shared_consts.Permissions.Manager) === + shared_consts.Permissions.Manager); + } catch (e) { + return false; + } +}; + UserSchema.statics.isEditor = function (perm) { try { return ((perm & shared_consts.Permissions.Editor) === diff --git a/src/server/router/cart_router.js b/src/server/router/cart_router.js index 51a63b3..bf9d903 100755 --- a/src/server/router/cart_router.js +++ b/src/server/router/cart_router.js @@ -224,7 +224,8 @@ router.post('/:userId/createorderscart', authenticate, async function (req, res, try { const mycart = await Cart.findOne({ _id: cart_id }); - let numorder = await OrdersCart.getLastNumOrder(userId, idapp); + let numorder = await OrdersCart.getLastNumOrder(idapp); + let numord_pers = await OrdersCart.getLastNumOrdPers(userId, idapp); // Esiste l'ordine ? let myorderCart = await OrdersCart.getRecCartByUserId(userId, idapp, numorder); @@ -232,6 +233,7 @@ router.post('/:userId/createorderscart', authenticate, async function (req, res, // crea il nuovo numero d'ordine numorder++; + numord_pers++; // SE non esiste allora lo creo ! myorderCart = new OrdersCart({ @@ -243,6 +245,7 @@ router.post('/:userId/createorderscart', authenticate, async function (req, res, status, note, numorder, + numord_pers, created_at: new Date(), modify_at: new Date(), }) diff --git a/src/server/router/products_router.js b/src/server/router/products_router.js index 8a9bb77..fcfd9f2 100755 --- a/src/server/router/products_router.js +++ b/src/server/router/products_router.js @@ -7,6 +7,8 @@ var server_constants = require('../tools/server_constants'); var { Project } = require('../models/project'); +const { User } = require('../models/user'); + var { authenticate, auth_default } = require('../middleware/authenticate'); const _ = require('lodash'); @@ -30,8 +32,14 @@ router.post('/', auth_default, async function (req, res, next) { const idapp = req.body.idapp; let userId = req.body.userId; - var products = await Product.findAllIdApp(idapp, ""); - var orders = await OrdersCart.getOrdersCartByUserId(userId, idapp, 0); + let products = await Product.findAllIdApp(idapp, ""); + let orders = null; + if (await User.isManagerById(userId)) { + // Prende Tutti gli Ordini ! + orders = await OrdersCart.getOrdersCartByUserId('ALL', idapp, 0); + } else { + orders = await OrdersCart.getOrdersCartByUserId(userId, idapp, 0); + } if (products) res.send({ code: server_constants.RIS_CODE_OK, products, orders }); From ab3a31d4fb64341c23a06ec20c413c8f974de136 Mon Sep 17 00:00:00 2001 From: Surya Paolo Date: Sat, 16 Dec 2023 00:51:03 +0100 Subject: [PATCH 4/8] Scontistica- Parte 1 --- src/server/models/order.js | 28 ++++++++++++++ src/server/models/product.js | 32 +++++++++++++++- src/server/models/scontistica.js | 59 ++++++++++++++++++++++++++++++ src/server/router/index_router.js | 4 ++ src/server/telegram/telegrambot.js | 4 +- src/server/tools/general.js | 1 + src/server/tools/globalTables.js | 3 ++ 7 files changed, 127 insertions(+), 4 deletions(-) create mode 100755 src/server/models/scontistica.js diff --git a/src/server/models/order.js b/src/server/models/order.js index 3cd0f82..b4d9c75 100755 --- a/src/server/models/order.js +++ b/src/server/models/order.js @@ -157,6 +157,20 @@ module.exports.findAllIdApp = async function (idapp) { as: 'provider' } }, + { + $lookup: { + from: 'scontisticas', + localField: 'idScontisticas', + foreignField: '_id', + as: 'scontistica' + } + }, + { + $unwind: { + path: '$scontistica', + preserveNullAndEmptyArrays: true, + }, + }, { $unwind: '$product' }, { $unwind: '$producer' }, { $unwind: '$provider' }, @@ -244,6 +258,20 @@ module.exports.getTotalOrderById = async function (id) { as: 'provider' } }, + { + $lookup: { + from: 'scontisticas', + localField: 'idScontisticas', + foreignField: '_id', + as: 'scontistica' + } + }, + { + $unwind: { + path: '$scontistica', + preserveNullAndEmptyArrays: true, + }, + }, { $unwind: '$product' }, { $unwind: '$producer' }, { $unwind: '$storehouse' }, diff --git a/src/server/models/product.js b/src/server/models/product.js index 64b22df..ccf7aca 100755 --- a/src/server/models/product.js +++ b/src/server/models/product.js @@ -6,6 +6,7 @@ const tools = require('../tools/general'); const Producer = require('../models/producer'); const Storehouse = require('../models/storehouse'); const Provider = require('../models/provider'); +const Scontistica = require('../models/scontistica'); const shared_consts = require('../tools/shared_nodejs'); @@ -33,6 +34,9 @@ const productSchema = new Schema({ idStorehouses: [ { type: Schema.Types.ObjectId, ref: 'Storehouse' } ], + idScontisticas: [ + { type: Schema.Types.ObjectId, ref: 'Scontistica' } + ], idProvider: { type: Schema.Types.ObjectId, ref: 'Provider' }, code: { type: String, @@ -214,7 +218,12 @@ module.exports.findAllIdApp = async function (idapp, code, id) { as: 'producer' } }, - { $unwind: '$producer' }, + { + $unwind: { + path: '$producer', + preserveNullAndEmptyArrays: true, + }, + }, { $lookup: { from: 'providers', @@ -223,7 +232,26 @@ module.exports.findAllIdApp = async function (idapp, code, id) { as: 'provider' } }, - { $unwind: '$provider' }, + { + $unwind: { + path: '$provider', + preserveNullAndEmptyArrays: true, + }, + }, + { + $lookup: { + from: 'scontisticas', + localField: 'idScontisticas', + foreignField: '_id', + as: 'scontistica' + } + }, + { + $unwind: { + path: '$scontistica', + preserveNullAndEmptyArrays: true, + }, + }, { $lookup: { from: 'storehouses', diff --git a/src/server/models/scontistica.js b/src/server/models/scontistica.js new file mode 100755 index 0000000..2a3a74a --- /dev/null +++ b/src/server/models/scontistica.js @@ -0,0 +1,59 @@ +mongoose = require('mongoose').set('debug', false) +const Schema = mongoose.Schema; + +const tools = require('../tools/general'); + +mongoose.Promise = global.Promise; +mongoose.level = "F"; + + +// Resolving error Unknown modifier: $pushAll +mongoose.plugin(schema => { + schema.options.usePushEach = true +}); + +const scontisticaSchema = new Schema({ + idapp: { + type: String, + }, + code: { + type: String, + }, + description: { + type: String, + }, + qta: { + type: Number, + }, + perc_sconto: { + type: Number, + }, + price: { + type: Number, + }, + comulativo: { + type: Boolean, + default: false, + }, +}); + +var Scontistica = module.exports = mongoose.model('Scontistica', scontisticaSchema); + +module.exports.getFieldsForSearch = function () { + return [{ field: 'name', type: tools.FieldType.string }] +}; + +module.exports.executeQueryTable = function (idapp, params) { + params.fieldsearch = this.getFieldsForSearch(); + return tools.executeQueryTable(this, idapp, params); +}; + +module.exports.findAllIdApp = async function (idapp) { + const myfind = { idapp }; + + return await Scontistica.find(myfind); +}; + +module.exports.createIndexes((err) => { + if (err) throw err; +}); diff --git a/src/server/router/index_router.js b/src/server/router/index_router.js index 85db907..f8fd6ce 100755 --- a/src/server/router/index_router.js +++ b/src/server/router/index_router.js @@ -66,6 +66,7 @@ const Cart = require('../models/cart'); const OrdersCart = require('../models/orderscart'); const Storehouse = require('../models/storehouse'); const Provider = require('../models/provider'); +const Scontistica = require('../models/scontistica'); const Department = require('../models/department'); const { Category } = require('../models/category'); const Group = require('../models/group'); @@ -1433,6 +1434,7 @@ function load(req, res, version) { let workers = User.getusersWorkersList(idapp); let storehouses = Storehouse.findAllIdApp(idapp); let providers = Provider.findAllIdApp(idapp); + let scontistica = Scontistica.findAllIdApp(idapp); let departments = Department.findAllIdApp(idapp); let categories = Category.findAllIdApp(idapp); @@ -1520,6 +1522,7 @@ function load(req, res, version) { myelems, // 38 categories, // 39 providers, + scontistica, ]).then((arrdata) => { // console.table(arrdata); let myuser = req.user; @@ -1603,6 +1606,7 @@ function load(req, res, version) { myelems: arrdata[38], categories: arrdata[39], providers: arrdata[40], + scontistica: arrdata[41], }); const prova = 1; diff --git a/src/server/telegram/telegrambot.js b/src/server/telegram/telegrambot.js index cf48f94..2b2ecf3 100755 --- a/src/server/telegram/telegrambot.js +++ b/src/server/telegram/telegrambot.js @@ -3,8 +3,8 @@ const tools = require('../tools/general'); const appTelegram = [tools.FREEPLANET, tools.RISO]; const appTelegram_TEST = [tools.FREEPLANET, tools.RISO]; -const appTelegram_DEVELOP = [tools.RISO]; -//const appTelegram_DEVELOP = [tools.FIOREDELLAVITA]; +//const appTelegram_DEVELOP = [tools.RISO]; +const appTelegram_DEVELOP = [tools.PIUCHEBUONO]; const appTelegramFinti = ['2', tools.CNM]; const appTelegramDest = [tools.FREEPLANET, tools.FREEPLANET]; diff --git a/src/server/tools/general.js b/src/server/tools/general.js index 30668cf..51897ef 100755 --- a/src/server/tools/general.js +++ b/src/server/tools/general.js @@ -416,6 +416,7 @@ module.exports = { CNM: '10', RISO: '13', FIOREDELLAVITA: '15', + PIUCHEBUONO: '17', HELP_CHAT: '', TYPECONF_ZOOM: 'zoom', diff --git a/src/server/tools/globalTables.js b/src/server/tools/globalTables.js index ee9ffc6..98674f1 100755 --- a/src/server/tools/globalTables.js +++ b/src/server/tools/globalTables.js @@ -61,6 +61,7 @@ const Cart = require('../models/cart'); const OrdersCart = require('../models/orderscart'); const Storehouse = require('../models/storehouse'); const Provider = require('../models/provider'); +const Scontistica = require('../models/scontistica'); const Department = require('../models/department'); const { Category } = require('../models/category'); const ShareWithUs = require('../models/sharewithus'); @@ -107,6 +108,8 @@ module.exports = { mytable = Storehouse; else if (tablename === 'providers') mytable = Provider; + else if (tablename === 'scontisticas') + mytable = Scontistica; else if (tablename === 'departments') mytable = Department; else if (tablename === 'categorys') From 4290895a97ac0ff788618a836e99a3b3c8e7e20a Mon Sep 17 00:00:00 2001 From: Surya Paolo Date: Sat, 16 Dec 2023 18:40:17 +0100 Subject: [PATCH 5/8] aggiornamento scontistica, corretto errori --- ecosystem.config.js | 9 ++++-- package.json | 2 +- src/server/models/order.js | 45 ++++++++++++++++++++------ src/server/models/orderscart.js | 17 +++++++--- src/server/models/product.js | 29 ++++++++--------- src/server/models/scontistica.js | 5 ++- src/server/models/site.js | 3 +- src/server/models/user.js | 3 +- src/server/modules/Cart.js | 54 +++++++++++++++++++++++++++++-- src/server/router/index_router.js | 6 ++-- src/server/router/users_router.js | 3 +- 11 files changed, 132 insertions(+), 44 deletions(-) diff --git a/ecosystem.config.js b/ecosystem.config.js index 44c2279..93e084d 100755 --- a/ecosystem.config.js +++ b/ecosystem.config.js @@ -4,7 +4,10 @@ module.exports = { name: "FreePlanetServerSide", script: "./src/server/server.js", ignore_watch : ["node_modules"], + interpreter: "/root/.nvm/versions/node/v16.19.0/bin/node", watch: false, + //autorestart: true, + instances: 1, env: { "PORT": 3000, "NODE_ENV": "development", @@ -17,9 +20,9 @@ module.exports = { "PORT": 3000, "NODE_ENV": "production", }, - log_file: "combined.outerr.log", - error_file: "err.log", - out_file: "out.log", + log_file: "logs/combined.outerr.log", + error_file: "logs/err.log", + out_file: "logs/out.log", merge_logs: true, log_date_format: "YYYY-MM-DD HH:mm:ss.SSSS Z" } diff --git a/package.json b/package.json index 3e1220f..a681b9e 100755 --- a/package.json +++ b/package.json @@ -14,7 +14,7 @@ "test-watch": "nodemon --exec 'npm test'" }, "engines": { - "node": "^18.17.0" + "node": "^18.19.0" }, "author": "Paolo Arena", "license": "MIT", diff --git a/src/server/models/order.js b/src/server/models/order.js index b4d9c75..4d59673 100755 --- a/src/server/models/order.js +++ b/src/server/models/order.js @@ -25,6 +25,7 @@ const orderSchema = new Schema({ idProduct: { type: Schema.Types.ObjectId, ref: 'Product' }, idProducer: { type: Schema.Types.ObjectId, ref: 'Producer' }, idStorehouse: { type: Schema.Types.ObjectId, ref: 'StoreHouse' }, + idScontisticas: [{ type: Schema.Types.ObjectId, ref: 'Scontistica' }], idProvider: { type: Schema.Types.ObjectId, ref: 'Provider' }, price: { type: Number @@ -167,13 +168,23 @@ module.exports.findAllIdApp = async function (idapp) { }, { $unwind: { - path: '$scontistica', + path: '$product', preserveNullAndEmptyArrays: true, }, }, - { $unwind: '$product' }, - { $unwind: '$producer' }, - { $unwind: '$provider' }, + { + $unwind: { + path: '$producer', + preserveNullAndEmptyArrays: true, + }, + }, + { + $unwind: { + path: '$provider', + preserveNullAndEmptyArrays: true, + }, + } + ]; return await Order.aggregate(query) @@ -263,19 +274,33 @@ module.exports.getTotalOrderById = async function (id) { from: 'scontisticas', localField: 'idScontisticas', foreignField: '_id', - as: 'scontistica' + as: 'scontisticas' } }, { $unwind: { - path: '$scontistica', + path: '$product', preserveNullAndEmptyArrays: true, }, }, - { $unwind: '$product' }, - { $unwind: '$producer' }, - { $unwind: '$storehouse' }, - { $unwind: '$provider' }, + { + $unwind: { + path: '$producer', + preserveNullAndEmptyArrays: true, + }, + }, + { + $unwind: { + path: '$storehouse', + preserveNullAndEmptyArrays: true, + }, + }, + { + $unwind: { + path: '$provider', + preserveNullAndEmptyArrays: true, + }, + } ]; return await Order.aggregate(query); diff --git a/src/server/models/orderscart.js b/src/server/models/orderscart.js index 023d8d7..d3e062f 100755 --- a/src/server/models/orderscart.js +++ b/src/server/models/orderscart.js @@ -223,6 +223,13 @@ module.exports.getOrdersCartByUserId = async function (uid, idapp, numorder) { model: 'Storehouse' }, }) + .populate({ + path: 'items.order', + populate: { + path: 'idScontisticas', + model: 'Scontistica' + }, + }) .populate({ path: 'userId', model: 'User', @@ -237,13 +244,15 @@ module.exports.getOrdersCartByUserId = async function (uid, idapp, numorder) { if (item.order) { try { item.order.product = item.order.idProduct; - item.order.idProduct = item.order.product._id; + item.order.idProduct = item.order.product ? item.order.product._id : ''; item.order.producer = item.order.idProducer; - item.order.idProducer = item.order.producer._id; + item.order.idProducer = item.order.producer ? item.order.producer._id : ''; item.order.storehouse = item.order.idStorehouse; - item.order.idStorehouse = item.order.storehouse._id; + item.order.idStorehouse = item.order.storehouse ? item.order.storehouse._id : ''; item.order.provider = item.order.idProvider; - item.order.idProvider = item.order.provider._id; + item.order.idProvider = item.order.provider ? item.order.provider._id : ''; + item.order.scontisticas = item.order.scontisticas; + item.order.idScontisticas = item.order.idScontisticas ? item.order.idScontisticas._id : ''; } catch (e) { console.error('Err: ', e); } diff --git a/src/server/models/product.js b/src/server/models/product.js index ccf7aca..2a1bd7d 100755 --- a/src/server/models/product.js +++ b/src/server/models/product.js @@ -206,6 +206,9 @@ module.exports.findAllIdApp = async function (idapp, code, id) { query.push(myqueryadd); } + // DA TOGLIEREE + // myfind = { ...myfind, code: '4012824406094' }; + // return await Product.find(myfind); query.push( @@ -243,15 +246,9 @@ module.exports.findAllIdApp = async function (idapp, code, id) { from: 'scontisticas', localField: 'idScontisticas', foreignField: '_id', - as: 'scontistica' + as: 'scontisticas' } }, - { - $unwind: { - path: '$scontistica', - preserveNullAndEmptyArrays: true, - }, - }, { $lookup: { from: 'storehouses', @@ -372,9 +369,9 @@ module.exports.convertAfterImport = async function (idapp, dataObjects) { let recproducer = await Producer.findOne({ idapp, name: prod.producer_name }).lean(); if (!recproducer) { // Non esiste questo produttore, quindi lo creo ! - recproducer = await Producer.create({ idapp, name: prod.producer_name }, (err, recordCreato) => { - return recordCreato - }) + recproducer = new Producer({ idapp, name: prod.producer_name }); + ris = await recproducer.save(); + recproducer = await Producer.findOne({ idapp, name: prod.producer_name }).lean(); } if (recproducer) { @@ -391,9 +388,9 @@ module.exports.convertAfterImport = async function (idapp, dataObjects) { let recstorehouse = await Storehouse.findOne({ idapp, name: prod.magazzino_name }).lean(); if (!recstorehouse) { // Non esiste questo produttore, quindi lo creo ! - recstorehouse = await Storehouse.create({ idapp, name: prod.magazzino_name }, (err, recordCreato) => { - return recordCreato - }) + recstorehouse = new Storehouse({ idapp, name: prod.magazzino_name }); + ris = await recstorehouse.save(); + recstorehouse = await Storehouse.findOne({ idapp, name: prod.magazzino_name }).lean(); } if (recstorehouse) { @@ -409,10 +406,10 @@ module.exports.convertAfterImport = async function (idapp, dataObjects) { // Cerca il produttore let recprovider = await Provider.findOne({ idapp, name: prod.provider_name }).lean(); if (!recprovider) { + recprovider = new Provider({ idapp, name: prod.provider_name }); // Non esiste questo produttore, quindi lo creo ! - recprovider = await Provider.create({ idapp, name: prod.provider_name }, (err, recordCreato) => { - return recordCreato - }) + ris = await recprovider.save(); + recprovider = await Provider.findOne({ idapp, name: prod.provider_name }).lean(); } if (recprovider) { diff --git a/src/server/models/scontistica.js b/src/server/models/scontistica.js index 2a3a74a..ec448dc 100755 --- a/src/server/models/scontistica.js +++ b/src/server/models/scontistica.js @@ -40,7 +40,10 @@ const scontisticaSchema = new Schema({ var Scontistica = module.exports = mongoose.model('Scontistica', scontisticaSchema); module.exports.getFieldsForSearch = function () { - return [{ field: 'name', type: tools.FieldType.string }] + return [ + { field: 'code', type: tools.FieldType.string }, + { field: 'description', type: tools.FieldType.string } + ] }; module.exports.executeQueryTable = function (idapp, params) { diff --git a/src/server/models/site.js b/src/server/models/site.js index da043f6..f79314d 100755 --- a/src/server/models/site.js +++ b/src/server/models/site.js @@ -338,7 +338,8 @@ module.exports.createFirstUserAdmin = async function () { const numusers = await User.countDocuments({ idapp: mysite.idapp }); if (numusers === 0) { // Non esistono utenti, quindi creo quello di Admin - const utenteadmin = await User.findOne({ idapp: '13', username: telegrambot.ADMIN_USER_SERVER }).lean() + + const utenteadmin = { idapp: '13', username: telegrambot.ADMIN_USER_SERVER }; const newuser = new User(utenteadmin); newuser._id = new ObjectID(); diff --git a/src/server/models/user.js b/src/server/models/user.js index bd376b8..d1b5f33 100755 --- a/src/server/models/user.js +++ b/src/server/models/user.js @@ -5378,6 +5378,7 @@ UserSchema.statics.addNewSite = async function (idappPass, body) { // cerca un IdApp Libero let idapp = await Site.generateNewSite_IdApp(idappPass, body, true); + if (idapp) { let arrSite = await Site.find({ idapp }).lean(); let numutenti = 0; @@ -5385,7 +5386,7 @@ UserSchema.statics.addNewSite = async function (idappPass, body) { numutenti = await User.countDocuments({ idapp }); }; - if (arrSite && arrSite.length === 1 && numutenti === 0) { + if (arrSite && arrSite.length === 1 && numutenti < 2) { // Nessun Sito Installato e Nessun Utente installato ! let myuser = new User(); myuser._id = new ObjectID(); diff --git a/src/server/modules/Cart.js b/src/server/modules/Cart.js index 2becf20..31677e4 100755 --- a/src/server/modules/Cart.js +++ b/src/server/modules/Cart.js @@ -99,9 +99,59 @@ class Cart { order = this.items[rec]; } this.totalQty += order.quantity; - this.totalPrice += order.price * order.quantity; - } + // Calcolo Sconto + let sconti_da_applicare = []; + let mypricecalc = 0; + if (order.scontisticas) { + + let qtadascontare = order.quantity + 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) + } + }*/ + + mypricecalc = order.price * order.quantity; + + if (sconti_da_applicare.length > 0) { + mypricecalc = 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; + } + this.totalPrice += mypricecalc; + } this.totalPrice = parseFloat(this.totalPrice.toFixed(2)) } catch (e) { console.error('Err: ', e); diff --git a/src/server/router/index_router.js b/src/server/router/index_router.js index f8fd6ce..f501fc6 100755 --- a/src/server/router/index_router.js +++ b/src/server/router/index_router.js @@ -1434,7 +1434,7 @@ function load(req, res, version) { let workers = User.getusersWorkersList(idapp); let storehouses = Storehouse.findAllIdApp(idapp); let providers = Provider.findAllIdApp(idapp); - let scontistica = Scontistica.findAllIdApp(idapp); + let scontisticas = Scontistica.findAllIdApp(idapp); let departments = Department.findAllIdApp(idapp); let categories = Category.findAllIdApp(idapp); @@ -1522,7 +1522,7 @@ function load(req, res, version) { myelems, // 38 categories, // 39 providers, - scontistica, + scontisticas, ]).then((arrdata) => { // console.table(arrdata); let myuser = req.user; @@ -1606,7 +1606,7 @@ function load(req, res, version) { myelems: arrdata[38], categories: arrdata[39], providers: arrdata[40], - scontistica: arrdata[41], + scontisticas: arrdata[41], }); const prova = 1; diff --git a/src/server/router/users_router.js b/src/server/router/users_router.js index b6d39ef..9135f41 100755 --- a/src/server/router/users_router.js +++ b/src/server/router/users_router.js @@ -566,8 +566,7 @@ router.post('/login', (req, res) => { // tools.mylog("CREDENZIALI ! "); if (!user) { await tools.snooze(3000); - const msg = 'Tentativo di Login ERRATO [' + body.username + ' , ' + - body.password + ']\n' + '[IP: ' + tools.getiPAddressUser(req) + + const msg = 'Tentativo di Login ERRATO [' + body.username + ' , ' + ']\n' + '[IP: ' + tools.getiPAddressUser(req) + ']'; tools.mylogshow(msg); await telegrambot.sendMsgTelegramToTheAdmin(user.idapp, msg, true); From c71f4af370401a6a8c45d866324b5684d01d960d Mon Sep 17 00:00:00 2001 From: Surya Paolo Date: Sun, 17 Dec 2023 16:20:44 +0100 Subject: [PATCH 6/8] Abilitazione del BOT --- filelog.txt | 12 +++ src/server/models/bot.js | 141 +++++++++++++++++++++++++++-- src/server/models/orderscart.js | 1 + src/server/models/site.js | 6 ++ src/server/models/user.js | 11 +++ src/server/router/users_router.js | 7 ++ src/server/telegram/telegrambot.js | 30 +++++- src/server/tools/general.js | 26 +++++- 8 files changed, 221 insertions(+), 13 deletions(-) diff --git a/filelog.txt b/filelog.txt index e1a4589..4139363 100644 --- a/filelog.txt +++ b/filelog.txt @@ -93,3 +93,15 @@ Gio 12/10 ORE 15:06: USER [paoloar77]: bottone Ven 13/10 ORE 11:05: USER [SuryaArena]: bottone Ven 13/10 ORE 11:40: USER [SuryaArena]: bottone + +Dom 17/12 ORE 15:38: USER [admin]: prova + +Dom 17/12 ORE 16:18: USER [admin]: vai al sito + +Dom 17/12 ORE 16:19: USER [admin]: vai al sito + +Dom 17/12 ORE 16:19: USER [admin]: il mio profilo + +Dom 17/12 ORE 16:19: USER [admin]: prova + +Dom 17/12 ORE 16:19: USER [admin]: link da condividere diff --git a/src/server/models/bot.js b/src/server/models/bot.js index bb0d430..97f291d 100755 --- a/src/server/models/bot.js +++ b/src/server/models/bot.js @@ -50,11 +50,11 @@ const BotSchema = new Schema({ }, }); -BotSchema.statics.getFieldsForSearch = function() { +BotSchema.statics.getFieldsForSearch = function () { return [{ field: 'label', type: tools.FieldType.string }] }; -BotSchema.statics.executeQueryTable = function(idapp, params) { +BotSchema.statics.executeQueryTable = function (idapp, params) { params.fieldsearch = this.getFieldsForSearch(); return tools.executeQueryTable(this, idapp, params); }; @@ -66,12 +66,141 @@ BotSchema.statics.DuplicateAllRecords = async function (idapporig, idappdest) { }; -BotSchema.statics.findAllIdApp = async function(idapp) { +BotSchema.statics.generateBotMenuRecords = async function (idapp) { + + try { + let arrrec = [ + { + "page": 1, + "index": 1, + "riga": 1, + "active": true, + "label": "Vai al Sito", + "type": 3, + "value": "{host}", + "visibility": 0, + idapp, + "lang": "it", + "main": true + }, + { + "page": 1, + "index": 1, + "riga": 2, + "active": true, + "label": "Il mio Profilo", + "type": 3, + "value": "{host}/my/{username}", + "visibility": 1, + idapp, + "lang": "it", + "main": true + }, + { + "page": 1, + "index": 1, + "riga": 3, + "active": true, + "label": "Link da Condividere", + "type": 2, + "value": "{host}/registrati/{username}", + "visibility": 1, + idapp, + "lang": "it", + "main": true, + }, + { + "page": 1, + "index": 2, + "riga": 1, + "active": true, + "label": "🔮 Help", + "type": 4, + "value": "", + "visibility": 0, + idapp, + "lang": "it", + "main": true, + }, + { + "page": 1, + "index": 1, + "riga": 3, + "active": true, + "label": "💁‍♀️ Admin", + "type": 4, + "value": "", + "visibility": 5, + idapp, + "lang": "it", + "main": true + }, + { + "page": 1, + "index": 2, + "riga": 2, + "active": true, + "label": "Imposta Foto Profilo", + "type": 4, + "value": "🖼 SetPicProfile", + "visibility": 1, + idapp, + "lang": "it", + "main": true + }, + { + "page": 1, + "index": 2, + "riga": 3, + "active": true, + "label": "🛠 Strumenti", + "type": 1, + "value": "2", + "visibility": 1, + idapp, + "lang": "it", + "main": true, + }, + { + "page": 2, + "index": 1, + "riga": 1, + "active": true, + "label": "🔑 Cambio Password", + "type": 4, + "value": "🔑 SetResetPwd", + "visibility": 1, + idapp, + "lang": "it", + }, + { + "page": 2, + "index": 1, + "riga": 2, + "active": true, + "label": "👉🏻 Indietro", + "type": 1, + "value": "1", + "visibility": 1, + idapp, + "lang": "it", + }]; + + const ris = await MyBot.insertMany(arrrec); + + return ris; + + } catch (e) { + console.error('Err:', e); + } + +} +BotSchema.statics.findAllIdApp = async function (idapp) { const Bot = this; - const myfind = {idapp}; + const myfind = { idapp }; - return await Bot.find(myfind).sort({page: 1, lang: 1, riga: 1, index: 1}).lean(); + return await Bot.find(myfind).sort({ page: 1, lang: 1, riga: 1, index: 1 }).lean(); }; const MyBot = mongoose.model('Bot', BotSchema); @@ -80,4 +209,4 @@ MyBot.createIndexes((err) => { if (err) throw err; }); -module.exports = {MyBot}; +module.exports = { MyBot }; diff --git a/src/server/models/orderscart.js b/src/server/models/orderscart.js index d3e062f..3ce5ad0 100755 --- a/src/server/models/orderscart.js +++ b/src/server/models/orderscart.js @@ -262,6 +262,7 @@ module.exports.getOrdersCartByUserId = async function (uid, idapp, numorder) { return order; }); + console.log('*** Num myorderscart ', myorderscart.length); return myorderscart } catch (e) { console.error('Err:', e); diff --git a/src/server/models/site.js b/src/server/models/site.js index f79314d..85b4612 100755 --- a/src/server/models/site.js +++ b/src/server/models/site.js @@ -64,6 +64,12 @@ const SiteSchema = new Schema({ telegram_key_test: { type: String, }, + load_process_telegram: { + type: Boolean, + }, + load_process_telegram_test: { + type: String, + }, teleg_cfg: { type: String, }, diff --git a/src/server/models/user.js b/src/server/models/user.js index d1b5f33..8509448 100755 --- a/src/server/models/user.js +++ b/src/server/models/user.js @@ -30,6 +30,7 @@ const i18n = require('i18n'); const shared_consts = require('../tools/shared_nodejs'); + mongoose.Promise = global.Promise; mongoose.level = 'F'; @@ -5387,6 +5388,8 @@ UserSchema.statics.addNewSite = async function (idappPass, body) { }; if (arrSite && arrSite.length === 1 && numutenti < 2) { + const MyTelegramBot = require('../telegram/telegrambot'); + // Nessun Sito Installato e Nessun Utente installato ! let myuser = new User(); myuser._id = new ObjectID(); @@ -5403,11 +5406,19 @@ UserSchema.statics.addNewSite = async function (idappPass, body) { myuser.perm = '3'; myuser.profile.special_req = true; myuser.profile.nationality = 'IT'; + myuser.profile.manage_telegram = true; + myuser.profile.teleg_id = MyTelegramBot.ADMIN_IDTELEGRAM_SERVER; + myuser.profile.username_telegram = MyTelegramBot.ADMIN_USERNAME_TELEGRAM; myuser.lasttimeonline = new Date(); myuser.date_reg = new Date(); await myuser.save(); + const { MyBot } = require('../models/bot'); + + // Genera il Menu del BOT: + await MyBot.generateBotMenuRecords(idapp); + return { code: server_constants.RIS_CODE_OK, idapp }; } } diff --git a/src/server/router/users_router.js b/src/server/router/users_router.js index 9135f41..e871351 100755 --- a/src/server/router/users_router.js +++ b/src/server/router/users_router.js @@ -17,6 +17,8 @@ const { Settings } = require('../models/settings'); const { SendNotif } = require('../models/sendnotif'); +const { MyBot } = require('../models/bot'); + const tools = require('../tools/general'); const shared_consts = require('../tools/shared_nodejs'); @@ -1409,6 +1411,11 @@ async function eseguiDbOp(idapp, mydata, locale, req, res) { } else if (mydata.dbop === 'updateSaldoAndTransato_AllAccounts') { await Account.updateSaldoAndTransato_AllAccounts(idapp); + } else if (mydata.dbop === 'generateBotMenuRecords') { + + + await MyBot.generateBotMenuRecords(idapp); + } else if (mydata.dbop === 'GenerateVapiKey') { await tools.generateVapiKey(); diff --git a/src/server/telegram/telegrambot.js b/src/server/telegram/telegrambot.js index 2b2ecf3..8753b70 100755 --- a/src/server/telegram/telegrambot.js +++ b/src/server/telegram/telegrambot.js @@ -695,6 +695,7 @@ const ADMIN_IDTELEGRAM_TEST = 5356627050; // 5022837609; //Surya Arena const MyTelegramBot = { ADMIN_IDTELEGRAM_SERVER: '12429864', //Paolo + ADMIN_USERNAME_TELEGRAM: 'surya1977', //Paolo ADMIN_USER_SERVER: 'paoloar77', ADMIN_USER_NAME_SERVER: 'Paolo', @@ -710,7 +711,7 @@ const MyTelegramBot = { } else { return appTelegram; } - + }, getAppTelegramTest: function () { @@ -719,7 +720,7 @@ const MyTelegramBot = { } else { return appTelegram_TEST; } - + }, local_sendMsgTelegramByIdTelegram: async function (idapp, idtelegram, text, @@ -978,7 +979,7 @@ const MyTelegramBot = { if (send_notif && msg_notifpush) { // SEND PUSH NOTIFICATION - await tools.sendNotificationToUser(userId, title, msg_notifpush, openUrl, '', tag, actions); + await tools.sendNotificationToUser(userId, title, msg_notifpush, openUrl, '', tag, actions); } @@ -3435,15 +3436,26 @@ class Telegram { rec.status = Status.NONE; if (!msg.from.username) { + // Non ha l'Username: + + // Chiedi l'username sul Bot: if (tools.getConfSiteOptionEnabledByIdApp(this.idapp, shared_consts.ConfSite.AskUsernameSulBot)) { rec.status = Status.WAITFOR_USERNAME_TELEGRAM; } } else { + // Ha l'Username + + // Chiedi l'invitante ? if (tools.getConfSiteOptionEnabledByIdApp(this.idapp, shared_consts.ConfSite.AskInvitantesulBot)) { rec.status = Status.WAITFOR_USERNAME_INVITANTE; } } + if (rec.status === Status.NONE) { + // Se il Sito non chiede di autenticarsi o l'invitante, allora lo Verifico direttamente ! + rec.status = Status.VERIFIED; + } + this.arrUsers.push(rec); if (tools.getConfSiteOptionEnabledByIdApp(this.idapp, shared_consts.ConfSite.AskInvitantesulBot)) { @@ -4065,11 +4077,16 @@ if (true) { else if (process.env.NODE_ENV === 'test') arrTeleg = MyTelegramBot.getAppTelegramTest(); + const arrTelegFromSite = tools.getArrTelegramFromSite(); + if (arrTelegFromSite.length > 0) { + arrTeleg = arrTelegFromSite; + } + var internetAvailable = require('internet-available'); internetAvailable().then(() => { // .. - console.log('TELEGRAM STARTING.... NODE_ENV:' + process.env.NODE_ENV); + console.log('TELEGRAM STARTING.... ' + process.env.NODE_ENV); for (const idapp of arrTeleg) { @@ -4080,7 +4097,9 @@ if (true) { // console.log('idapp', idapp, 'token', token); if (!!token) { - console.log('*** START BOT ' + nomebot); + console.log('-------------------------------------'); + console.log('*** STARTING BOT ' + nomebot); + console.log('-------------------------------------'); const bot = new TelegramBot(token, { polling: true }); if (url === '0') { @@ -4095,6 +4114,7 @@ if (true) { arrTelegram.push({ idapp, cl: new Telegram(idapp, bot) }); bot.onText(/\/start/, (msg) => { + console.log('*** BOT PARTITO CORRETTAMENTE !!! (Start Cmd)'); const myclTelegram = getclTelegBytoken(bot.token); myclTelegram.start(msg); diff --git a/src/server/tools/general.js b/src/server/tools/general.js index 51897ef..7bcba2c 100755 --- a/src/server/tools/general.js +++ b/src/server/tools/general.js @@ -1804,7 +1804,7 @@ module.exports = { getTelegramBotNameByIdApp: function (idapp) { const myapp = this.MYAPPS.find((item) => item.idapp === idapp); - if (process.env.NODE_ENV === 'test') + if (process.env.NODE_ENV === 'test' || process.env.NODE_ENV === 'development') return (myapp) ? myapp.telegram_bot_name_test : ''; else return (myapp) ? myapp.telegram_bot_name : ''; @@ -1823,12 +1823,30 @@ module.exports = { getTelegramKeyByIdApp: function (idapp) { const myapp = this.MYAPPS.find((item) => item.idapp === idapp); - if (process.env.NODE_ENV === 'test') + if (process.env.NODE_ENV === 'test' || process.env.NODE_ENV === 'development') return (myapp) ? myapp.telegram_key_test : ''; else return (myapp) ? myapp.telegram_key : ''; }, + getArrTelegramFromSite: function () { + const myapp = this.MYAPPS; + let arrteleg = [] + for (const site of myapp) { + if (site.active) { + if (process.env.NODE_ENV === 'test') { + if (myapp.load_process_telegram_test) + arrteleg.push(myapp.idapp) + } else { + if (myapp.load_process_telegram) + arrteleg.push(myapp.idapp) + } + } + } + + return arrteleg; + }, + getLookupPipeLine(params, proj) { let myquery = [ @@ -4025,7 +4043,11 @@ module.exports = { if (!msg) return msg; + if (!!user) { + if (msg.includes('{host}')) { + msg = msg.replace('{host}', this.getHostByIdApp(user.idapp)); + } if (msg.includes('{appname}')) msg = msg.replace('{appname}', this.getNomeAppByIdApp(user.idapp)); msg = msg.replace('{username}', user.username); From 50d610b1b1a70439db58b2bacdf611f6250b49cf Mon Sep 17 00:00:00 2001 From: Surya Paolo Date: Sun, 17 Dec 2023 19:19:04 +0100 Subject: [PATCH 7/8] aggiornamento... --- src/server/models/orderscart.js | 194 ++++++++++++++++++----------- src/server/models/product.js | 4 + src/server/sendemail.js | 14 ++- src/server/telegram/telegrambot.js | 27 ++-- src/server/tools/shared_nodejs.js | 48 +++++++ 5 files changed, 195 insertions(+), 92 deletions(-) diff --git a/src/server/models/orderscart.js b/src/server/models/orderscart.js index 3ce5ad0..bb085a7 100755 --- a/src/server/models/orderscart.js +++ b/src/server/models/orderscart.js @@ -168,9 +168,86 @@ module.exports.getRecCartByUserId = async function (uid, idapp, numorder) { } module.exports.getOrdersCartById = async function (id) { - let query = { _id: id }; - return await OrdersCart.findOne(query); + let query = { _id: ObjectID(id) }; + + const arrris = await OrdersCart.getOrdersCartByQuery(query); + return arrris && arrris.length > 0 ? arrris[0] : null; + +} + +module.exports.getOrdersCartByQuery = async function (query) { + + let myorderscart = await OrdersCart.find(query) + .populate('items.order') + .populate({ + path: 'items.order', + populate: { + path: 'idProduct', + model: 'Product' + }, + }) + .populate({ + path: 'items.order', + populate: { + path: 'idProducer', + model: 'Producer' + }, + }) + .populate({ + path: 'items.order', + populate: { + path: 'idProvider', + model: 'Provider' + }, + }) + .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', // Specify the fields you want to retrieve + }) + .lean(); + + myorderscart = myorderscart.map(order => { + order.user = order.userId + order.userId = order.user._id + order.items = order.items.map(item => { + if (item.order) { + try { + 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.scontisticas = item.order.scontisticas; + item.order.idScontisticas = item.order.idScontisticas ? item.order.idScontisticas._id : ''; + } catch (e) { + console.error('Err: ', e); + } + } + return item; + }); + return order; + }); + + return myorderscart; } module.exports.getOrdersCartByUserId = async function (uid, idapp, numorder) { @@ -186,6 +263,12 @@ module.exports.getOrdersCartByUserId = async function (uid, idapp, numorder) { query.userId = uid; } + myorderscart = await OrdersCart.getOrdersCartByQuery(query); + + if (myorderscart) + console.log('*** Num myorderscart ', myorderscart.length); + + /*transform: function(doc, populated) { // Rinomina 'idProduct' a 'product' nei risultati della popolazione populated.product = populated.idProduct; @@ -193,76 +276,7 @@ module.exports.getOrdersCartByUserId = async function (uid, idapp, numorder) { return populated; },*/ - myorderscart = await OrdersCart.find(query) - .populate('items.order') - .populate({ - path: 'items.order', - populate: { - path: 'idProduct', - model: 'Product' - }, - }) - .populate({ - path: 'items.order', - populate: { - path: 'idProducer', - model: 'Producer' - }, - }) - .populate({ - path: 'items.order', - populate: { - path: 'idProvider', - model: 'Provider' - }, - }) - .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', // Specify the fields you want to retrieve - }) - .lean(); - myorderscart = myorderscart.map(order => { - order.user = order.userId - order.userId = order.user._id - order.items = order.items.map(item => { - if (item.order) { - try { - 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.scontisticas = item.order.scontisticas; - item.order.idScontisticas = item.order.idScontisticas ? item.order.idScontisticas._id : ''; - } catch (e) { - console.error('Err: ', e); - } - } - return item; - }); - return order; - }); - - console.log('*** Num myorderscart ', myorderscart.length); return myorderscart } catch (e) { console.error('Err:', e); @@ -438,7 +452,8 @@ module.exports.updateStockQtaDalMagazzino = async function (idorderscart) { module.exports.updateCmd = async function (ordersCart, status, value) { - let myOrderCart = await OrdersCart.findOne({ _id: ordersCart._id }).populate('items.order').lean(); + let myOrderCart = await OrdersCart.findOne({ _id: ordersCart._id }) + .populate('items.order').lean(); try { if (!!myOrderCart) { @@ -466,7 +481,7 @@ module.exports.updateCmd = async function (ordersCart, status, value) { await OrdersCart.setFieldInOrdersById({ status }, myOrderCart); - myOrderCart = await OrdersCart.findOne({ _id: ordersCart._id }).populate('items.order').lean(); + myOrderCart = await OrdersCart.getOrdersCartById(ordersCart._id) // myOrderCart = await OrdersCart.findOne({ _id: idorderscart }); return myOrderCart; @@ -513,6 +528,39 @@ OrdersCartSchema.pre('save', async function (next) { } }); +module.exports.getmsgorderTelegram = async function (ordersCart) { + try { + const statusstr = shared_consts.getStatusStr(ordersCart.status); + + let msg = '🟢✍️ Ordine n. ' + ordersCart.numorder + + msg += '
Stato: ' + statusstr; + + msg += '
🙎🏻‍♂️ ' + tools.getNomeCognomeEUserNameByUser(ordersCart.user) + if (ordersCart.note) + msg += '
Note: ' + ordersCart.note; + + + msg += '

Lista Prodotti:'; + for (const ord of ordersCart.items) { + msg += '
'; + msg += '✅ [' + ord.order.quantity + '] ' + ord.order.product.name + ' (' + ord.order.price + ' € ' + (ord.order.after_price ? ord.order.after_price : '') + ')'; + } + + msg += '
'; + + msg += '
Totale Prodotti: ' + ordersCart.totalQty; + msg += '
Totale Ordine: ' + ordersCart.totalPrice + ' € 💰'; + + + + return msg; + + } catch (e) { + console.error('Err', e); + } +}; + module.exports.createIndexes((err) => { if (err) throw err; }); diff --git a/src/server/models/product.js b/src/server/models/product.js index 2a1bd7d..7d34ef9 100755 --- a/src/server/models/product.js +++ b/src/server/models/product.js @@ -299,8 +299,12 @@ module.exports.findAllIdApp = async function (idapp, code, id) { ); + // console.log('query=', query); + let ris = await Product.aggregate(query) + // console.table('ris', ris); + return ris; } catch (e) { diff --git a/src/server/sendemail.js b/src/server/sendemail.js index ef72463..5ed4f84 100755 --- a/src/server/sendemail.js +++ b/src/server/sendemail.js @@ -743,12 +743,13 @@ module.exports = { sendEmail_OrderProduct: async function (lang, idapp, orders, user) { try { - const msginizio = 'Ordine n: ' + orders.numorder + ' ' + user.name + ' ' + user.surname; + const msg = await OrdersCart.getmsgorderTelegram(orders); + const msginizio = msg; console.log(msginizio); - if (process.env.SEND_EMAIL_ORDERS === '1') { + await telegrambot.sendMsgTelegramToTheManagers(idapp, msginizio); - await telegrambot.sendMsgTelegramToTheManagers(idapp, msginizio); + if (process.env.SEND_EMAIL_ORDERS === '1') { let mylocalsconf = { idapp, @@ -776,12 +777,13 @@ module.exports = { sendEmail_Order: async function (lang, idapp, orders, user, ordertype, status) { try { - const msginizio = 'INIZIO - sendEmail_Order ' + ordertype + ': ' + tools.getNomeAppByIdApp(idapp); + const msg = await OrdersCart.getmsgorderTelegram(orders); + const msginizio = msg; console.log(msginizio); - if (process.env.SEND_EMAIL_ORDERS === '1') { + await telegrambot.sendMsgTelegramToTheManagers(idapp, msginizio); - await telegrambot.sendMsgTelegramToTheManagers(idapp, msginizio); + if (process.env.SEND_EMAIL_ORDERS === '1') { let mylocalsconf = { idapp, diff --git a/src/server/telegram/telegrambot.js b/src/server/telegram/telegrambot.js index 8753b70..ad8c6f1 100755 --- a/src/server/telegram/telegrambot.js +++ b/src/server/telegram/telegrambot.js @@ -707,10 +707,20 @@ const MyTelegramBot = { getAppTelegram: function () { if (process.env.appTelegram) { - return JSON.parse(process.env.appTelegram); + arrTeleg = JSON.parse(process.env.appTelegram); } else { - return appTelegram; + arrTeleg = appTelegram; } + if (process.env.NODE_ENV === 'development') + arrTeleg = appTelegram_DEVELOP; + else if (process.env.NODE_ENV === 'test') + arrTeleg = MyTelegramBot.getAppTelegramTest(); + + const arrTelegFromSite = tools.getArrTelegramFromSite(); + if (arrTelegFromSite.length > 0) { + arrTeleg = arrTelegFromSite; + } + return arrTeleg; }, @@ -3437,14 +3447,14 @@ class Telegram { if (!msg.from.username) { // Non ha l'Username: - + // Chiedi l'username sul Bot: if (tools.getConfSiteOptionEnabledByIdApp(this.idapp, shared_consts.ConfSite.AskUsernameSulBot)) { rec.status = Status.WAITFOR_USERNAME_TELEGRAM; } } else { // Ha l'Username - + // Chiedi l'invitante ? if (tools.getConfSiteOptionEnabledByIdApp(this.idapp, shared_consts.ConfSite.AskInvitantesulBot)) { rec.status = Status.WAITFOR_USERNAME_INVITANTE; @@ -4072,15 +4082,6 @@ function getclTelegByidapp(idapp) { //if (!tools.testing() || true) { if (true) { let arrTeleg = MyTelegramBot.getAppTelegram(); - if (process.env.NODE_ENV === 'development') - arrTeleg = appTelegram_DEVELOP; - else if (process.env.NODE_ENV === 'test') - arrTeleg = MyTelegramBot.getAppTelegramTest(); - - const arrTelegFromSite = tools.getArrTelegramFromSite(); - if (arrTelegFromSite.length > 0) { - arrTeleg = arrTelegFromSite; - } var internetAvailable = require('internet-available'); diff --git a/src/server/tools/shared_nodejs.js b/src/server/tools/shared_nodejs.js index 6f10556..61649e8 100755 --- a/src/server/tools/shared_nodejs.js +++ b/src/server/tools/shared_nodejs.js @@ -407,6 +407,50 @@ module.exports = { CANCELLATI: { label: 'Cancellati', value: 10, icon: 'delete', color: 'text-red' }, //CANCELED }, + OrderStatusStr: [ + { + label: 'Nessuno', + value: 0, + }, + { + label: 'In Carrello', + value: 1, + }, + { + label: 'Ordine in Lavorazione', + value: 2, + }, + { + label: 'Ordine Confermato', + value: 3, + }, + { + label: 'Pagato', + value: 4, + }, + { + label: 'Consegnato', + value: 5, + }, + { + label: 'Spedito', + value: 6, + }, + { + label: 'Ricevuto', + value: 7, + }, + { + label: 'Completato', + value: 8, + }, + { + label: 'Cancellato', + value: 10, + }, + + ], + OrderStatusView: { CHECKOUT_SENT: 2, ORDER_CONFIRMED: 3, @@ -864,5 +908,9 @@ module.exports = { return '' }, + getStatusStr(status) { + const trovatorec = this.OrderStatusStr.find((rec) => rec.value === status) + return (trovatorec) ? trovatorec.label : '' + }, }; From 139d7ea33c5d03ec8b4c648539494c985247c8d6 Mon Sep 17 00:00:00 2001 From: Surya Paolo Date: Mon, 18 Dec 2023 08:02:28 +0100 Subject: [PATCH 8/8] Risolto problema blocco --- src/server/models/order.js | 10 ++++++++-- src/server/models/orderscart.js | 2 +- src/server/modules/Cart.js | 14 +++++++------- 3 files changed, 16 insertions(+), 10 deletions(-) diff --git a/src/server/models/order.js b/src/server/models/order.js index 4d59673..10583ca 100755 --- a/src/server/models/order.js +++ b/src/server/models/order.js @@ -28,7 +28,8 @@ const orderSchema = new Schema({ idScontisticas: [{ type: Schema.Types.ObjectId, ref: 'Scontistica' }], idProvider: { type: Schema.Types.ObjectId, ref: 'Provider' }, price: { - type: Number + type: Number, + default: 0, }, after_price: { type: String @@ -40,7 +41,12 @@ const orderSchema = new Schema({ type: String }, quantity: { - type: Number + type: Number, + default: 0, + }, + TotalPriceProduct: { + type: Number, + default: 0, }, evaso: { // e quindi è stato tolto dal magazzino (aggiornando il campo StockQty) type: Boolean, diff --git a/src/server/models/orderscart.js b/src/server/models/orderscart.js index bb085a7..8883e79 100755 --- a/src/server/models/orderscart.js +++ b/src/server/models/orderscart.js @@ -544,7 +544,7 @@ module.exports.getmsgorderTelegram = async function (ordersCart) { msg += '

Lista Prodotti:'; for (const ord of ordersCart.items) { msg += '
'; - msg += '✅ [' + ord.order.quantity + '] ' + ord.order.product.name + ' (' + ord.order.price + ' € ' + (ord.order.after_price ? ord.order.after_price : '') + ')'; + msg += '✅ [' + ord.order.quantity + '] ' + ord.order.product.name + ' (' + ord.order.price + ' € ' + (ord.order.after_price ? ord.order.after_price : '') + ' Tot=' + ord.order.TotalPriceProduct + '€ )'; } msg += '
'; diff --git a/src/server/modules/Cart.js b/src/server/modules/Cart.js index 31677e4..89b3660 100755 --- a/src/server/modules/Cart.js +++ b/src/server/modules/Cart.js @@ -38,8 +38,8 @@ class Cart { const myitem = this.items.find((rec) => rec.order._id.toString() === itemorder._id) if (!!myitem) { myitem.order.quantity++; - await Order.findOneAndUpdate({ _id: myitem.order._id }, { $set: myitem.order }, { new: false }); this.updatetotals(); + await Order.findOneAndUpdate({ _id: myitem.order._id }, { $set: myitem.order }, { new: false }); return myitem.order.quantity; } } @@ -49,8 +49,8 @@ class Cart { const myitem = this.items.find((rec) => rec.order._id.toString() === itemorder._id) if (!!myitem && myitem.order.quantity > 0) { myitem.order.quantity--; - await Order.findOneAndUpdate({ _id: myitem.order._id }, { $set: myitem.order }, { new: false }); this.updatetotals(); + await Order.findOneAndUpdate({ _id: myitem.order._id }, { $set: myitem.order }, { new: false }); return myitem.order.quantity; } } catch (e) { @@ -94,15 +94,17 @@ class Cart { this.totalQty = 0; this.totalPrice = 0; for (const rec in this.items) { + let mypricecalc = 0; + let order = this.items[rec].order; if (!order) { order = this.items[rec]; } + order.TotalPriceProduct = 0; this.totalQty += order.quantity; // Calcolo Sconto let sconti_da_applicare = []; - let mypricecalc = 0; if (order.scontisticas) { let qtadascontare = order.quantity @@ -131,10 +133,7 @@ class Cart { } }*/ - mypricecalc = order.price * order.quantity; - if (sconti_da_applicare.length > 0) { - mypricecalc = 0 for (const sconto of sconti_da_applicare) { if (sconto.perc_sconto > 0) { mypricecalc += (sconto.qtadascontare * order.price) * (1 - (sconto.perc_sconto / 100)) @@ -150,7 +149,8 @@ class Cart { } else { mypricecalc = order.price * order.quantity; } - this.totalPrice += mypricecalc; + order.TotalPriceProduct += mypricecalc; + this.totalPrice += order.TotalPriceProduct; } this.totalPrice = parseFloat(this.totalPrice.toFixed(2)) } catch (e) {