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/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/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/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/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/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/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 cd59553..10583ca 100755 --- a/src/server/models/order.js +++ b/src/server/models/order.js @@ -25,8 +25,11 @@ 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 + type: Number, + default: 0, }, after_price: { type: String @@ -38,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, @@ -148,8 +156,41 @@ module.exports.findAllIdApp = async function (idapp) { as: 'producer' } }, - { $unwind: '$product' }, - { $unwind: '$producer' }, + { + $lookup: { + from: 'providers', + localField: 'idProvider', + foreignField: '_id', + as: 'provider' + } + }, + { + $lookup: { + from: 'scontisticas', + localField: 'idScontisticas', + foreignField: '_id', + as: 'scontistica' + } + }, + { + $unwind: { + path: '$product', + preserveNullAndEmptyArrays: true, + }, + }, + { + $unwind: { + path: '$producer', + preserveNullAndEmptyArrays: true, + }, + }, + { + $unwind: { + path: '$provider', + preserveNullAndEmptyArrays: true, + }, + } + ]; return await Order.aggregate(query) @@ -170,30 +211,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) { @@ -223,9 +267,46 @@ module.exports.getTotalOrderById = async function (id) { as: 'storehouse' } }, - { $unwind: '$product' }, - { $unwind: '$producer' }, - { $unwind: '$storehouse' }, + { + $lookup: { + from: 'providers', + localField: 'idProvider', + foreignField: '_id', + as: 'provider' + } + }, + { + $lookup: { + from: 'scontisticas', + localField: 'idScontisticas', + foreignField: '_id', + as: 'scontisticas' + } + }, + { + $unwind: { + path: '$product', + preserveNullAndEmptyArrays: true, + }, + }, + { + $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 485378f..8883e79 100755 --- a/src/server/models/orderscart.js +++ b/src/server/models/orderscart.js @@ -6,7 +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 Storehouse = require('../models/storehouse'); +const Provider = require('../models/provider'); const Product = require('../models/product'); const tools = require('../tools/general'); @@ -18,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 }, @@ -34,7 +36,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, }, @@ -109,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); @@ -140,10 +156,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(); @@ -152,36 +168,24 @@ 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.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; - } +module.exports.getOrdersCartByQuery = async function (query) { - if (uid !== 'ALL') { - query.userId = uid; - } - - myorderscart = await OrdersCart.find(query).populate('items.order') + let 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', @@ -189,12 +193,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', @@ -202,126 +207,84 @@ module.exports.getOrdersCartByUserId = async function (uid, idapp, numorder) { 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(); + .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.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; - 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) { + myorderscart = myorderscart.map(order => { + order.user = order.userId + order.userId = order.user._id + order.items = order.items.map(item => { + if (item.order) { 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]; - } + 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.log('err', e); + console.error('Err: ', e); } } - return mycart; - }*/ - return myorderscart - // return null; + return item; + }); + return order; + }); + + return myorderscart; + } +module.exports.getOrdersCartByUserId = async function (uid, idapp, numorder) { -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); - } + try { + let query = { idapp, status: { $gte: shared_consts.OrderStatus.CHECKOUT_SENT }, deleted: false } + let myorderscart = null; + if (numorder > 0) { + query.numorder = numorder; } - } - 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); - } + if (uid !== 'ALL') { + query.userId = uid; } - } - return myorderscart + 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; + delete populated.idProduct; + return populated; + },*/ + + + return myorderscart + } catch (e) { + console.error('Err:', e); + } // return null; } + module.exports.updateOrdersCartById = function (id, newOrdersCart, callback) { let query = { id, @@ -342,6 +305,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(), } @@ -358,23 +322,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); } } @@ -459,7 +430,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) { @@ -482,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) { @@ -510,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; @@ -557,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 : '') + ' Tot=' + ord.order.TotalPriceProduct + '€ )'; + } + + 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 e5445a9..7d34ef9 100755 --- a/src/server/models/product.js +++ b/src/server/models/product.js @@ -4,9 +4,14 @@ 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 Scontistica = require('../models/scontistica'); const shared_consts = require('../tools/shared_nodejs'); +const { ObjectID } = require('mongodb'); + mongoose.Promise = global.Promise; mongoose.level = "F"; @@ -29,8 +34,13 @@ 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, + unique: true, }, codice_EAN: { type: String, @@ -86,10 +96,6 @@ const productSchema = new Schema({ type: Number, default: 0, }, - quantityAvailable: { - type: Number, - default: 0, - }, quantityLow: { //Soglia disponibilità bassa type: Number, default: 0, @@ -140,7 +146,10 @@ const productSchema = new Schema({ producer_name: { type: String, }, - fornitore_name: { + provider_name: { + type: String, + }, + magazzino_name: { type: String, }, }); @@ -158,79 +167,149 @@ 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: 'storehouses', - localField: 'idStorehouses', - foreignField: '_id', - as: 'storehouses' + myfind = { + $expr: { + $eq: ["$_id", "$myId1"], + }, } - }, - { - $lookup: { - from: 'orders', - let: { productId: '$_id' }, - pipeline: [ - { - $match: { - $expr: { - $and: [ - { $eq: ['$idProduct', '$$productId'] }, - { $lt: ['$status', shared_consts.OrderStatus.ORDER_CONFIRMED] } - ] + + query.push(myqueryadd); + } + + // DA TOGLIEREE + // myfind = { ...myfind, code: '4012824406094' }; + + // return await Product.find(myfind); + + query.push( + { $match: myfind }, + { + $lookup: { + from: 'producers', + localField: 'idProducer', + foreignField: '_id', + as: 'producer' + } + }, + { + $unwind: { + path: '$producer', + preserveNullAndEmptyArrays: true, + }, + }, + { + $lookup: { + from: 'providers', + localField: 'idProvider', + foreignField: '_id', + as: 'provider' + } + }, + { + $unwind: { + path: '$provider', + preserveNullAndEmptyArrays: true, + }, + }, + { + $lookup: { + from: 'scontisticas', + localField: 'idScontisticas', + foreignField: '_id', + as: 'scontisticas' + } + }, + { + $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) + // console.log('query=', query); - return ris; + let ris = await Product.aggregate(query) + + // console.table('ris', ris); + + return ris; + + } catch (e) { + console.error('E', e); + } }; @@ -251,10 +330,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 } }; @@ -281,31 +356,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 ris = null; + let recproducer = await Producer.findOne({ idapp, name: prod.producer_name }).lean(); + if (!recproducer) { + // Non esiste questo produttore, quindi lo creo ! + recproducer = new Producer({ idapp, name: prod.producer_name }); + ris = await recproducer.save(); + recproducer = await Producer.findOne({ idapp, name: prod.producer_name }).lean(); + } if (recproducer) { - ris = await Product.findOneAndUpdate({ _id: prod._id }, { $set: { idProducer: recproducer._id } }) - console.log('Ris', ris); - ris = await Product.findOneAndUpdate({ _id: prod._id }, { $unset: { [campodarimuovere]: 1 } }) - console.log('Ris', ris); + 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 = new Storehouse({ idapp, name: prod.magazzino_name }); + ris = await recstorehouse.save(); + recstorehouse = await Storehouse.findOne({ idapp, name: prod.magazzino_name }).lean(); + } + + 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) { + recprovider = new Provider({ idapp, name: prod.provider_name }); + // Non esiste questo produttore, quindi lo creo ! + ris = await recprovider.save(); + recprovider = await Provider.findOne({ idapp, name: prod.provider_name }).lean(); + } + + 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/models/scontistica.js b/src/server/models/scontistica.js new file mode 100755 index 0000000..ec448dc --- /dev/null +++ b/src/server/models/scontistica.js @@ -0,0 +1,62 @@ +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: 'code', type: tools.FieldType.string }, + { field: 'description', 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/models/site.js b/src/server/models/site.js index 4be0b69..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, }, @@ -176,6 +182,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); @@ -335,7 +344,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 87fb04a..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'; @@ -625,6 +626,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) === @@ -5368,6 +5379,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; @@ -5375,7 +5387,9 @@ 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) { + const MyTelegramBot = require('../telegram/telegrambot'); + // Nessun Sito Installato e Nessun Utente installato ! let myuser = new User(); myuser._id = new ObjectID(); @@ -5392,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/modules/Cart.js b/src/server/modules/Cart.js index 2becf20..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,14 +94,64 @@ 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; - this.totalPrice += order.price * order.quantity; - } + // Calcolo Sconto + let sconti_da_applicare = []; + 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) + } + }*/ + + if (sconti_da_applicare.length > 0) { + for (const sconto of sconti_da_applicare) { + if (sconto.perc_sconto > 0) { + mypricecalc += (sconto.qtadascontare * order.price) * (1 - (sconto.perc_sconto / 100)) + } else { + mypricecalc += sconto.price + } + } + } + if (qtanonscontata > 0) { + mypricecalc += order.price * qtanonscontata; + } + + } else { + mypricecalc = order.price * order.quantity; + } + order.TotalPriceProduct += mypricecalc; + this.totalPrice += order.TotalPriceProduct; + } this.totalPrice = parseFloat(this.totalPrice.toFixed(2)) } catch (e) { console.error('Err: ', e); 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/cart_router.js b/src/server/router/cart_router.js index 673b4e1..bf9d903 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,11 +219,13 @@ 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 }); - 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); @@ -204,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({ @@ -213,14 +243,17 @@ router.post('/:userId/createorderscart', authenticate, async function (req, res, totalPrice: mycart.totalPrice, userId, status, - note: mycart.note, + note, numorder, + numord_pers, created_at: new Date(), modify_at: new Date(), }) } statusOrderCart = myorderCart.status; + const idordercart = myorderCart._id; + if (!!mycart) { if (status === shared_consts.OrderStatus.CHECKOUT_SENT) { @@ -246,7 +279,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/index_router.js b/src/server/router/index_router.js index b398a93..f501fc6 100755 --- a/src/server/router/index_router.js +++ b/src/server/router/index_router.js @@ -65,6 +65,8 @@ 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 Scontistica = require('../models/scontistica'); const Department = require('../models/department'); const { Category } = require('../models/category'); const Group = require('../models/group'); @@ -1431,6 +1433,8 @@ 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 scontisticas = Scontistica.findAllIdApp(idapp); let departments = Department.findAllIdApp(idapp); let categories = Category.findAllIdApp(idapp); @@ -1517,6 +1521,8 @@ function load(req, res, version) { listcircuits, // 37 myelems, // 38 categories, // 39 + providers, + scontisticas, ]).then((arrdata) => { // console.table(arrdata); let myuser = req.user; @@ -1599,6 +1605,8 @@ function load(req, res, version) { listcircuits: arrdata[37], myelems: arrdata[38], categories: arrdata[39], + providers: arrdata[40], + scontisticas: arrdata[41], }); const prova = 1; diff --git a/src/server/router/products_router.js b/src/server/router/products_router.js index 658f793..fcfd9f2 100755 --- a/src/server/router/products_router.js +++ b/src/server/router/products_router.js @@ -7,11 +7,14 @@ 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'); const Product = require('../models/product'); +const OrdersCart = require('../models/orderscart'); const Variant = require('../models/variant'); /*const Department = require('../models/Department') @@ -27,11 +30,19 @@ 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, ""); + 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 }); + res.send({ code: server_constants.RIS_CODE_OK, products, orders }); else res.status(400).send(e); diff --git a/src/server/router/users_router.js b/src/server/router/users_router.js index b6d39ef..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'); @@ -566,8 +568,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); @@ -1410,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/sendemail.js b/src/server/sendemail.js index 185fb25..5ed4f84 100755 --- a/src/server/sendemail.js +++ b/src/server/sendemail.js @@ -742,57 +742,78 @@ 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 msg = await OrdersCart.getmsgorderTelegram(orders); + const msginizio = msg; + console.log(msginizio); - await telegrambot.sendMsgTelegramToTheManagers(idapp, msginizio); + await telegrambot.sendMsgTelegramToTheManagers(idapp, msginizio); - let mylocalsconf = { - idapp, - locale: lang, - nomeapp: tools.getNomeAppByIdApp(idapp), - orders, - baseurl: tools.getHostByIdApp(idapp), - dataemail: await this.getdataemail(idapp), - ordernumber: orders.numorder, - user, - }; + if (process.env.SEND_EMAIL_ORDERS === '1') { - 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 msg = await OrdersCart.getmsgorderTelegram(orders); + const msginizio = msg; + console.log(msginizio); - await telegrambot.sendMsgTelegramToTheManagers(idapp, msginizio); + await telegrambot.sendMsgTelegramToTheManagers(idapp, msginizio); - let mylocalsconf = { - idapp, - locale: lang, - nomeapp: tools.getNomeAppByIdApp(idapp), - orders, - baseurl: tools.getHostByIdApp(idapp), - dataemail: await this.getdataemail(idapp), - ordernumber: orders.numorder, - user, - }; + if (process.env.SEND_EMAIL_ORDERS === '1') { - 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); } }, diff --git a/src/server/telegram/telegrambot.js b/src/server/telegram/telegrambot.js index cf48f94..ad8c6f1 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]; @@ -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', @@ -706,11 +707,21 @@ 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; + }, getAppTelegramTest: function () { @@ -719,7 +730,7 @@ const MyTelegramBot = { } else { return appTelegram_TEST; } - + }, local_sendMsgTelegramByIdTelegram: async function (idapp, idtelegram, text, @@ -978,7 +989,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 +3446,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)) { @@ -4060,16 +4082,12 @@ 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(); 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 +4098,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 +4115,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 30668cf..7bcba2c 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', @@ -1803,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 : ''; @@ -1822,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 = [ @@ -4024,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); diff --git a/src/server/tools/globalTables.js b/src/server/tools/globalTables.js index 9613577..98674f1 100755 --- a/src/server/tools/globalTables.js +++ b/src/server/tools/globalTables.js @@ -60,6 +60,8 @@ 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 Scontistica = require('../models/scontistica'); const Department = require('../models/department'); const { Category } = require('../models/category'); const ShareWithUs = require('../models/sharewithus'); @@ -104,6 +106,10 @@ module.exports = { mytable = Product; else if (tablename === 'storehouses') mytable = Storehouse; + else if (tablename === 'providers') + mytable = Provider; + else if (tablename === 'scontisticas') + mytable = Scontistica; else if (tablename === 'departments') mytable = Department; else if (tablename === 'categorys') 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 : '' + }, };