From 15d831eeccefce947448e04215a86a6b2af37707 Mon Sep 17 00:00:00 2001 From: Surya Paolo Date: Wed, 27 Dec 2023 02:58:15 +0100 Subject: [PATCH] - Categorie - ProductInfo --- emails/ecommerce/makeorder/it/html.pug | 38 +++-- emails/ecommerce/order_confirmed/it/html.pug | 25 +-- src/server/models/catprod.js | 56 +++++++ src/server/models/gasordine.js | 2 + src/server/models/order.js | 90 +++++++---- src/server/models/orderscart.js | 101 ++---------- src/server/models/product.js | 134 +++++++--------- src/server/models/productInfo.js | 156 +++++++++++++++++++ src/server/models/storehouse.js | 11 +- src/server/modules/Cart.js | 9 +- src/server/router/admin_router.js | 84 ++++++++-- src/server/router/cart_router.js | 2 +- src/server/router/index_router.js | 8 + src/server/router/users_router.js | 21 +++ src/server/tools/general.js | 3 + src/server/tools/globalTables.js | 6 + 16 files changed, 516 insertions(+), 230 deletions(-) create mode 100755 src/server/models/catprod.js create mode 100755 src/server/models/productInfo.js diff --git a/emails/ecommerce/makeorder/it/html.pug b/emails/ecommerce/makeorder/it/html.pug index 0e6351b..d698c06 100755 --- a/emails/ecommerce/makeorder/it/html.pug +++ b/emails/ecommerce/makeorder/it/html.pug @@ -39,14 +39,19 @@ html - var note = orders.note - 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 gasordine = product.order.gasordine.name - - var qty = product.order.quantity - - var qtypreordered = product.order.quantitypreordered + each rec in orders.items + - var descr = rec.order.product.productInfo.name + - var img = rec.order.product.productInfo.img + - var price = rec.order.price + - var after_price = rec.order.after_price + - var TotalPriceProduct = rec.order.TotalPriceProduct + if (rec.order.gasordine) + - var gasordine = rec.order.gasordine.name + else + - var gasordine = '' + + - var qty = rec.order.quantity + - var qtypreordered = rec.order.quantitypreordered - index = index + 1 table(cellpadding="0", cellspacing="0", width="100%", summary="", border="0", align="center") @@ -62,7 +67,7 @@ html td(class="column", valign="top") table(cellpadding="0", cellspacing="0", summary="", border="0") - if (qtypreordereded > 0) + if (qtypreordered > 0) tr td(class="sectionContent", valign="top") p Gas Ordine: #{gasordine} @@ -73,13 +78,14 @@ html td(class="sectionContent", valign="top") p Prezzo: #{price} € #{after_price} if (qty > 0) - tr - td(class="sectionContent", valign="top") - p Quantità: #{qty} - if (qtypreordereded > 0) - tr - td(class="sectionContent", valign="top") - p Quantità Prenotata: #{qtypreorder} + td(class="sectionContent", valign="top") + p Quantità: #{qty} + if (qtypreordered > 0) + td(class="sectionContent", valign="top") + p Quantità Prenotata: #{qtypreordered} + tr + td(class="sectionContent", valign="top") + p Totale: #{TotalPriceProduct} € p Note Aggiuntive: #{note} diff --git a/emails/ecommerce/order_confirmed/it/html.pug b/emails/ecommerce/order_confirmed/it/html.pug index 57bfa16..bb858fe 100755 --- a/emails/ecommerce/order_confirmed/it/html.pug +++ b/emails/ecommerce/order_confirmed/it/html.pug @@ -39,14 +39,18 @@ html - var note = orders.note - var index = 0 - each product in orders.items - - var descr = product.order.product.name - - var img = product.order.product.img - - var price = product.order.product.price - - var after_price = product.order.product.after_price - - var gasordine = product.order.gasordine.name - - var qty = product.order.product.quantity - - var qtypreordered = product.order.quantitypreordered + each rec in orders.items + - var descr = rec.order.product.productInfo.name + - var img = rec.order.product.productInfo.img + - var price = rec.order.product.price + - var after_price = rec.order.product.after_price + if (rec.order.gasordine) + - var gasordine = rec.order.gasordine.name + else + - var gasordine = '' + - var qty = rec.order.product.quantity + - var qtypreordered = rec.order.quantitypreordered + - var TotalPriceProduct = rec.order.TotalPriceProduct - index = index + 1 table(cellpadding="0", cellspacing="0", width="100%", summary="", border="0", align="center") @@ -62,7 +66,7 @@ html td(class="column", valign="top") table(cellpadding="0", cellspacing="0", summary="", border="0") - if (qtypreordereded > 0) + if (qtypreordered > 0) tr td(class="sectionContent", valign="top") p Gas Ordine: #{gasordine} @@ -80,6 +84,9 @@ html tr td(class="sectionContent", valign="top") p Quantità Prenotata: #{qtypreordered} + tr + td(class="sectionContent", valign="top") + p Totale: #{TotalPriceProduct} € p Note Aggiuntive: #{note} diff --git a/src/server/models/catprod.js b/src/server/models/catprod.js new file mode 100755 index 0000000..3a7a19b --- /dev/null +++ b/src/server/models/catprod.js @@ -0,0 +1,56 @@ + +const mongoose = require('mongoose').set('debug', false) +const Schema = mongoose.Schema; + +mongoose.Promise = global.Promise; +mongoose.level = "F"; + +const tools = require('../tools/general'); + +// Resolving error Unknown modifier: $pushAll +mongoose.plugin(schema => { + schema.options.usePushEach = true +}); + +const CatProdSchema = new Schema({ + idapp: { + type: String, + }, + name: { + type: String, + }, + img: { + type: String, + }, +}); + +CatProdSchema.statics.getAllCategories = function (callback) { + CatProd.find(callback) +} + +CatProdSchema.statics.getCatProdById = function (id, callback) { + CatProd.findById(id, callback); +} + +CatProdSchema.statics.getFieldsForSearch = function () { + return [{ field: 'name', type: tools.FieldType.string }] +}; + +CatProdSchema.statics.executeQueryTable = function (idapp, params) { + return tools.executeQueryTable(this, idapp, params); +}; + +CatProdSchema.statics.findAllIdApp = async function (idapp) { + const myfind = { idapp }; + + return await CatProd.find(myfind).sort({ name: 1 }); +}; + +const CatProd = mongoose.model('CatProd', CatProdSchema); + +CatProd.createIndexes((err) => { + if (err) throw err; +}); + + +module.exports = CatProd; diff --git a/src/server/models/gasordine.js b/src/server/models/gasordine.js index 18da9ef..caa8786 100755 --- a/src/server/models/gasordine.js +++ b/src/server/models/gasordine.js @@ -34,6 +34,7 @@ const gasordineSchema = new Schema({ img: { type: String, }, + dataora_chiusura_ordini: { type: Date, }, @@ -43,6 +44,7 @@ const gasordineSchema = new Schema({ dataora_termine_pagamento: { type: Date, }, + }); var Gasordine = module.exports = mongoose.model('Gasordine', gasordineSchema); diff --git a/src/server/models/order.js b/src/server/models/order.js index 3e8d3e0..596d7bb 100755 --- a/src/server/models/order.js +++ b/src/server/models/order.js @@ -154,10 +154,24 @@ module.exports.findAllIdApp = async function (idapp) { as: 'product' } }, + { + $lookup: { + from: 'productinfos', + localField: 'product.idProduct', + foreignField: '_id', + as: 'product.productInfo' + } + }, + { + $unwind: { + path: '$product.productInfo', + preserveNullAndEmptyArrays: true, + }, + }, { $lookup: { from: 'producers', - localField: 'idProducer', + localField: 'product.idProducer', foreignField: '_id', as: 'producer' } @@ -165,7 +179,7 @@ module.exports.findAllIdApp = async function (idapp) { { $lookup: { from: 'providers', - localField: 'idProvider', + localField: 'product.idProvider', foreignField: '_id', as: 'provider' } @@ -178,15 +192,24 @@ module.exports.findAllIdApp = async function (idapp) { as: 'gasordine' } }, + { + $unwind: { + path: '$gasordine', + preserveNullAndEmptyArrays: true, + }, + }, { $match: { - 'gasordine.active': true + $or: [ + { 'gasordine': { $exists: false } }, + { 'gasordine.active': true } + ] } }, { $lookup: { from: 'scontisticas', - localField: 'idScontisticas', + localField: 'product.idScontisticas', foreignField: '_id', as: 'scontistica' } @@ -209,12 +232,6 @@ module.exports.findAllIdApp = async function (idapp) { preserveNullAndEmptyArrays: true, }, }, - { - $unwind: { - path: '$gasordine', - preserveNullAndEmptyArrays: true, - }, - } ]; @@ -270,9 +287,9 @@ module.exports.updateTotals = function (order) { try { if (!order) { - return; + return; } - + let mypricecalc = 0; order.TotalPriceProduct = 0; @@ -342,10 +359,30 @@ module.exports.getTotalOrderById = async function (id) { as: 'product' } }, + { + $unwind: { + path: '$product', + preserveNullAndEmptyArrays: true, + }, + }, + { + $lookup: { + from: 'productinfos', + localField: 'product.idProductInfo', + foreignField: '_id', + as: 'product.productInfo' + } + }, + { + $unwind: { + path: '$product.productInfo', + preserveNullAndEmptyArrays: true, + }, + }, { $lookup: { from: 'producers', - localField: 'idProducer', + localField: 'product.idProducer', foreignField: '_id', as: 'producer' } @@ -361,7 +398,7 @@ module.exports.getTotalOrderById = async function (id) { { $lookup: { from: 'providers', - localField: 'idProvider', + localField: 'product.idProvider', foreignField: '_id', as: 'provider' } @@ -374,25 +411,28 @@ module.exports.getTotalOrderById = async function (id) { as: 'gasordine' } }, + { + $unwind: { + path: '$gasordine', + preserveNullAndEmptyArrays: true, + }, + }, { $match: { - 'gasordine.active': true + $or: [ + { 'gasordine': { $exists: false } }, + { 'gasordine.active': true } + ] } }, { $lookup: { from: 'scontisticas', - localField: 'idScontisticas', + localField: 'product.idScontisticas', foreignField: '_id', as: 'scontisticas' } }, - { - $unwind: { - path: '$product', - preserveNullAndEmptyArrays: true, - }, - }, { $unwind: { path: '$producer', @@ -411,12 +451,6 @@ module.exports.getTotalOrderById = async function (id) { preserveNullAndEmptyArrays: true, }, }, - { - $unwind: { - path: '$gasordine', - preserveNullAndEmptyArrays: true, - }, - }, { $lookup: { from: 'orders', diff --git a/src/server/models/orderscart.js b/src/server/models/orderscart.js index f4258e7..c987dc0 100755 --- a/src/server/models/orderscart.js +++ b/src/server/models/orderscart.js @@ -10,6 +10,7 @@ const Storehouse = require('../models/storehouse'); const Provider = require('../models/provider'); const Gasordine = require('../models/gasordine'); const Product = require('../models/product'); +const ProductInfo = require('../models/productinfo'); const tools = require('../tools/general'); @@ -178,90 +179,6 @@ module.exports.getOrdersCartById = async function (id) { } -module.exports.getOLDOrdersCartByQuery = 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: 'idGasordine', - model: 'Gasordine' - }, - }) - .populate({ - path: 'items.order', - populate: { - path: 'idStorehouse', - model: 'Storehouse' - }, - }) - .populate({ - path: 'items.order', - populate: { - path: 'idScontisticas', - model: 'Scontistica' - }, - }) - .populate({ - path: 'userId', - model: 'User', - select: '_id name surname username profile', // 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.gasordine = item.order.idGasordine; - item.order.idGasordine = item.order.gasordine ? item.order.gasordine._id : ''; - item.order.scontisticas = item.order.scontisticas; - item.order.idScontisticas = item.order.idScontisticas ? item.order.idScontisticas._id : ''; - } catch (e) { - console.error('Err: ', e); - } - } - return item; - }); - return order; - }); - - return myorderscart; - -} - module.exports.getOrdersCartByQuery = async function (query) { @@ -274,6 +191,16 @@ module.exports.getOrdersCartByQuery = async function (query) { model: 'Product' }, }) + .populate({ + path: 'items.order', + populate: { + path: 'idProduct', + populate: { + path: 'idProductInfo', + model: 'ProductInfo' + }, + }, + }) .populate({ path: 'items.order', populate: { @@ -324,6 +251,10 @@ module.exports.getOrdersCartByQuery = async function (query) { try { item.order.product = item.order.idProduct; item.order.idProduct = item.order.product ? item.order.product._id : ''; + if (item.order.product.idProductInfo) { + item.order.product.productInfo = item.order.product.idProductInfo; + item.order.product.idProductInfo = item.order.product ? item.order.product.productInfo._id : ''; + } item.order.producer = item.order.idProducer; item.order.idProducer = item.order.producer ? item.order.producer._id : ''; item.order.storehouse = item.order.idStorehouse; @@ -653,7 +584,7 @@ module.exports.getmsgorderTelegram = async function (ordersCart) { qtystr += 'Ordinate: ' + ord.order.quantity if (ord.order.quantitypreordered > 0) qtystr += ' Pre-Ordinate: ' + ord.order.quantitypreordered - msg += '✅ [' + qtystr + '] ' + ord.order.product.name + ' (' + ord.order.price + ' € ' + (ord.order.after_price ? ord.order.after_price : '') + ' Tot=' + ord.order.TotalPriceProduct + '€ )'; + msg += '✅ [' + qtystr + '] ' + ord.order.product.productInfo.name + ' (' + ord.order.price + ' € ' + (ord.order.after_price ? ord.order.after_price : '') + ' Tot=' + ord.order.TotalPriceProduct + '€ )'; } msg += '
'; diff --git a/src/server/models/product.js b/src/server/models/product.js index 70a4ba9..bea3abc 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 CatProd = require('../models/catprod'); const Gasordine = require('../models/gasordine'); const Scontistica = require('../models/scontistica'); @@ -31,6 +32,7 @@ const productSchema = new Schema({ type: Boolean, default: true, }, + idProductInfo: { type: Schema.Types.ObjectId, ref: 'ProductInfo' }, idProducer: { type: Schema.Types.ObjectId, ref: 'Producer' }, idStorehouses: [ { type: Schema.Types.ObjectId, ref: 'Storehouse' } @@ -42,29 +44,6 @@ const productSchema = new Schema({ { type: Schema.Types.ObjectId, ref: 'Scontistica' } ], idProvider: { type: Schema.Types.ObjectId, ref: 'Provider' }, - code: { - type: String, - unique: true, - required: true, - }, - codice_EAN: { - type: String, - }, - barcode: { - type: String, - }, - name: { - type: String, - }, - description: { - type: String, - }, - department: { - type: String, ref: 'Department' - }, - category: { - type: Array, - }, prezzo_ivato: { // Con IVA type: Number }, @@ -82,26 +61,15 @@ const productSchema = new Schema({ after_price: { type: String }, - color: { - type: String - }, - size: { - type: String - }, - weight: { - type: Number - }, - vegan: { - type: Boolean - }, - unit: { - type: Number - }, minBuyQty: { // quantità minima acquistabile type: Number, default: 1, required: true, }, + maxBookableQty: { // quantità massima Pre-ordinabile (singolarmente) + type: Number, + default: 0, + }, stockQty: { // in magazzino type: Number, default: 0, @@ -133,30 +101,6 @@ const productSchema = new Schema({ dateAvailableFrom: { type: Date }, - icon: { - type: String, - }, - img: { - type: String, - }, - link: { - type: String, - }, - img2: { - type: String, - }, - img3: { - type: String, - }, - ingredienti: { - type: String, - }, - valori_nutrizionali: { - type: String, - }, - note: { - type: String, - }, producer_name: { type: String, }, @@ -166,6 +110,9 @@ const productSchema = new Schema({ magazzino_name: { type: String, }, + cat_name: { + type: String, + }, }); var Product = module.exports = mongoose.model('Product', productSchema); @@ -244,6 +191,20 @@ module.exports.findAllIdApp = async function (idapp, code, id) { preserveNullAndEmptyArrays: true, }, }, + { + $lookup: { + from: 'productinfos', + localField: 'idProductInfo', + foreignField: '_id', + as: 'productInfo' + } + }, + { + $unwind: { + path: '$productInfo', + preserveNullAndEmptyArrays: true, + }, + }, { $lookup: { from: 'gasordines', @@ -300,6 +261,14 @@ module.exports.findAllIdApp = async function (idapp, code, id) { preserveNullAndEmptyArrays: true, }, }, + { + $lookup: { + from: 'catprods', + localField: 'idCatProds', + foreignField: '_id', + as: 'catprods' + } + }, { $lookup: { from: 'scontisticas', @@ -410,7 +379,11 @@ module.exports.findAllIdApp = async function (idapp, code, id) { { $unset: 'productPreOrders' }, - + { + $sort: { + 'productInfo.name': 1 // 1 for ascending order, -1 for descending order + } + }, ); // console.log('query=', query); @@ -436,7 +409,7 @@ module.exports.getProductByDepartment = function (query, sort, callback) { Product.find(query, null, sort, callback) } -module.exports.getProductByCategory = function (query, sort, callback) { +module.exports.getProductByCatProd = function (query, sort, callback) { Product.find(query, null, sort, callback) } @@ -450,9 +423,9 @@ module.exports.filterProductByDepartment = function (department, callback) { Product.find(query, callback) } -module.exports.filterProductByCategory = function (category, callback) { - let regexp = new RegExp(`^${category}$`, 'i') - var query = { category: { $regex: regexp } }; +module.exports.filterProductByCatProd = function (catprod, callback) { + let regexp = new RegExp(`^${catprod}$`, 'i') + var query = { catprod: { $regex: regexp } }; Product.find(query, callback); } @@ -487,16 +460,20 @@ module.exports.convertAfterImport = async function (idapp, dataObjects) { }; -module.exports.singlerecconvert_AfterImport = async function (idapp, prod) { +module.exports.singlerecconvert_AfterImport = async function (idapp, prod, isnuovo) { let setta = false; try { + let objtoset = {} + // Impostazioni Base: - let objtoset = { - idapp, - img: 'upload/products/' + prod.code + '.jpg', - minBuyQty: 1, + if (isnuovo) { + objtoset = { + idapp, + minBuyQty: 1, + maxBookableQty: 0, + } } if (prod.producer_name) { @@ -569,8 +546,17 @@ module.exports.singlerecconvert_AfterImport = async function (idapp, prod) { } } - if (setta) { - const ris = await Product.findOneAndUpdate({ _id: ObjectID(prod._id) }, { $set: objtoset }) + if (!tools.isObjectEmpty(objtoset)) { + ris = await Product.findOneAndUpdate({ _id: ObjectID(prod._id) }, { $set: objtoset }) + + const objDelete = { + cat_name: 1, + producer_name: 1, + provider_name: 1, + magazzino_name: 1, + }; + + ris = await Product.updateOne({ _id: ObjectID(prod._id) }, { $unset: objDelete }) if (ris) { console.log('ris', ris); diff --git a/src/server/models/productInfo.js b/src/server/models/productInfo.js new file mode 100755 index 0000000..4532a00 --- /dev/null +++ b/src/server/models/productInfo.js @@ -0,0 +1,156 @@ +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 productInfoSchema = new Schema({ + idapp: { + type: String, + }, + department: { + type: String, ref: 'Department' + }, + code: { + type: String, + unique: true, + required: true, + }, + codice_EAN: { + type: String, + }, + barcode: { + type: String, + }, + name: { + type: String, + }, + description: { + type: String, + }, + idCatProds: [{ type: Schema.Types.ObjectId, ref: 'CatProd' }], + color: { + type: String + }, + size: { + type: String + }, + weight: { + type: Number + }, + vegan: { + type: Boolean + }, + unit: { + type: Number + }, + icon: { + type: String, + }, + img: { + type: String, + }, + link: { + type: String, + }, + img2: { + type: String, + }, + img3: { + type: String, + }, + ingredienti: { + type: String, + }, + valori_nutrizionali: { + type: String, + }, + note: { + type: String, + }, + +}); + +var productInfo = module.exports = mongoose.model('ProductInfo', productInfoSchema); + +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, code, id) { + let myfind = {}; + let myqueryadd = {}; + let query = []; + + try { + + if (idapp) + myfind = { idapp }; + + if (code) { + myfind = { ...myfind, code } + } + if (id) { + myqueryadd = { + $addFields: { + myId1: { + $toObjectId: id, + }, + }, + } + myfind = { + $expr: { + $eq: ["$_id", "$myId1"], + }, + } + + query.push(myqueryadd); + } + + query.push( + { $match: myfind }, + { + $lookup: { + from: 'catprods', + localField: 'idCatProds', + foreignField: '_id', + as: 'catprods' + } + }, + { + $sort: { + name: 1 // 1 for ascending order, -1 for descending order + } + }, + ); + + let ris = await productInfo.aggregate(query) + + return ris; + + } catch (e) { + console.error('E', e); + } + +}; + +module.exports.getProductByCode = function (idapp, code) { + return productInfo.findAllIdApp(idapp, code); +} + +module.exports.createIndexes((err) => { + if (err) throw err; +}); diff --git a/src/server/models/storehouse.js b/src/server/models/storehouse.js index 8eabb9d..5aaf052 100755 --- a/src/server/models/storehouse.js +++ b/src/server/models/storehouse.js @@ -40,12 +40,21 @@ const storehouseSchema = new Schema({ website: { type: String, }, + stockQty: { // in magazzino + type: Number, + default: 0, + }, + bookableQty: { // Quantità prenotabili + type: Number, + default: 0, + }, + }); var Storehouse = module.exports = mongoose.model('Storehouse', storehouseSchema); module.exports.getFieldsForSearch = function () { - return [{field: 'name', type: tools.FieldType.string}] + return [{ field: 'name', type: tools.FieldType.string }] }; module.exports.executeQueryTable = function (idapp, params) { diff --git a/src/server/modules/Cart.js b/src/server/modules/Cart.js index 44a811f..2437bb1 100755 --- a/src/server/modules/Cart.js +++ b/src/server/modules/Cart.js @@ -61,16 +61,16 @@ class Cart { let step = 1; if (this.isAvailableByOrder(myitem.order)) { if (myitem.order.quantity === 0) - step = myitem.order.minBuyQty + step = myitem.order.product.minBuyQty | 1 else if (myitem.order.quantity >= 10) step = 2 else if (myitem.order.quantity >= 20) step = 5 - + myitem.order.quantity += step; } else { if (myitem.order.quantitypreordered === 0) - step = myitem.order.minBuyQty + step = myitem.order.product.minBuyQty | 1 else if (myitem.order.quantitypreordered >= 10) step = 2 else if (myitem.order.quantitypreordered >= 20) @@ -90,7 +90,7 @@ class Cart { const myitem = this.items.find((rec) => rec.order._id.toString() === itemorder._id) if (!!myitem) { if (myitem.order.quantitypreordered > 0) { - myitem.order.quantitypreordered -= myitem.order.product.minBuyQty | 1; + myitem.order.quantitypreordered--; } else { if (myitem.order.quantity > 0) { myitem.order.quantity--; @@ -108,6 +108,7 @@ class Cart { addItem(itemorder) { // this.items.push(itemorder); + let ind = this.items.length; this.items[ind] = {}; this.items[ind].order = itemorder; diff --git a/src/server/router/admin_router.js b/src/server/router/admin_router.js index 379fb72..f72e4ff 100755 --- a/src/server/router/admin_router.js +++ b/src/server/router/admin_router.js @@ -9,6 +9,8 @@ const tools = require('../tools/general'); const { City } = require('../models/city'); const Product = require('../models/product'); +const ProductInfo = require('../models/productinfo'); +const CatProd = require('../models/catprod'); var { authenticate } = require('../middleware/authenticate'); @@ -55,32 +57,90 @@ router.post('/import', authenticate, async (req, res) => { let errors = 0; for (const product of dataObjects) { + let isnuovo = false + let setta = false + + let productInfo = { + idapp: product.idapp, + code: product.code, + name: product.name, + link: product.link, + idCatProds: [], + img: 'upload/products/' + product.code + '.jpg', + } + + if (product.cat_name) { + // Cerca la Categoria + let reccateg = await CatProd.findOne({ idapp, name: product.cat_name }).lean(); + if (!reccateg) { + // Non esiste questo produttore, quindi lo creo ! + reccateg = new CatProd({ idapp, name: product.cat_name }); + ris = await reccateg.save(); + reccateg = await CatProd.findOne({ idapp, name: product.cat_name }).lean(); + } + + if (reccateg) { + productInfo.idCatProds.push(reccateg._id); + } + } + if (!product.hasOwnProperty('active')) { product.active = true; } - let risrec = await Product.findOneAndUpdate({ code: product.code }, { $set: product }, { new: true, upsert: true }); - let recnew = await Product.findOne({ code: product.code }).lean(); + delete product.code; + delete product.name; + delete product.link; - if (risrec) { - if (risrec._id) { + // Update ProductInfo + let risrecInfo = await ProductInfo.findOneAndUpdate({ code: productInfo.code }, { $set: productInfo }, { new: true, upsert: true }); + if (risrecInfo) { + product.idProductInfo = risrecInfo._id; + + recnewInfo = await ProductInfo.findOne({ code: productInfo.code }).lean(); + + if (risrecInfo._id) { // Record existed, so it was updated - let arrfieldchange = tools.differentObjects(product, recnew); + let arrfieldchange = tools.differentObjects(productInfo, recnewInfo); if (arrfieldchange.length > 0) { - updated++; - console.log('Changed: ', product.name + ': ' + arrfieldchange); + // updated++; + console.log('Changed: ', recnewInfo.name + ': ' + arrfieldchange); + } + } + + let recProductExist = await Product.findOne({ idProductInfo: product.idProductInfo }).lean(); + if (!recProductExist) { + isnuovo = true; + } + + let risrec = await Product.findOneAndUpdate({ idProductInfo: product.idProductInfo }, { $set: product }, { new: true, upsert: true }); + + let recnew = await Product.findOne({ idProductInfo: product.idProductInfo }).lean(); + + if (risrec) { + if (risrec._id) { + // Record existed, so it was updated + let arrfieldchange = tools.differentObjects(product, recnew); + if (arrfieldchange.length > 0) { + updated++; + console.log('Changed: ', product.idProductInfo + ': ' + arrfieldchange); + } + } else { + // Record didn't exist, so it was created + imported++; } } else { - // Record didn't exist, so it was created - imported++; + // risrec is null or undefined, indicating an error + console.error('Error: ', product.productInfo.name); + errors++; } + + await Product.singlerecconvert_AfterImport(idapp, recnew, isnuovo); } else { - // risrec is null or undefined, indicating an error - console.error('Error: ', product.name); + console.error('Error ProductInfo: ', product.code); errors++; } - await Product.singlerecconvert_AfterImport(idapp, recnew); } // L'opzione ordered: false gestisce gli errori senza interrompere l'inserimento diff --git a/src/server/router/cart_router.js b/src/server/router/cart_router.js index 70c5606..73bfec5 100755 --- a/src/server/router/cart_router.js +++ b/src/server/router/cart_router.js @@ -57,6 +57,7 @@ router.post('/:userId', authenticate, async function (req, res, next) { try { let mycart = await Cart.getCartByUserId(userId, idapp); + if (!order) { return res.send({ code: server_constants.RIS_CODE_OK, cart: null }); } @@ -272,7 +273,6 @@ router.post('/:userId/createorderscart', authenticate, async function (req, res, }) } statusOrderCart = myorderCart.status; - const idordercart = myorderCart._id; if (!!mycart) { diff --git a/src/server/router/index_router.js b/src/server/router/index_router.js index 7e6bf39..77cc676 100755 --- a/src/server/router/index_router.js +++ b/src/server/router/index_router.js @@ -66,7 +66,9 @@ const Cart = require('../models/cart'); const OrdersCart = require('../models/orderscart'); const Storehouse = require('../models/storehouse'); const Provider = require('../models/provider'); +const CatProd = require('../models/catprod'); const Gasordine = require('../models/gasordine'); +const ProductInfo = require('../models/productinfo'); const Scontistica = require('../models/scontistica'); const Department = require('../models/department'); const { Category } = require('../models/category'); @@ -1435,7 +1437,9 @@ function load(req, res, version) { let workers = User.getusersWorkersList(idapp); let storehouses = Storehouse.findAllIdApp(idapp); let providers = Provider.findAllIdApp(idapp); + let catprods = CatProd.findAllIdApp(idapp); let gasordines = Gasordine.findAllIdApp(idapp); + let productInfos = ProductInfo.findAllIdApp(idapp); let scontisticas = Scontistica.findAllIdApp(idapp); let departments = Department.findAllIdApp(idapp); let categories = Category.findAllIdApp(idapp); @@ -1526,6 +1530,8 @@ function load(req, res, version) { providers, scontisticas, gasordines, + productInfos, + catprods, ]).then((arrdata) => { // console.table(arrdata); let myuser = req.user; @@ -1611,6 +1617,8 @@ function load(req, res, version) { providers: arrdata[40], scontisticas: arrdata[41], gasordines: arrdata[42], + productInfos: arrdata[43], + catprods: arrdata[44], }); const prova = 1; diff --git a/src/server/router/users_router.js b/src/server/router/users_router.js index ba91322..9d08bf0 100755 --- a/src/server/router/users_router.js +++ b/src/server/router/users_router.js @@ -36,6 +36,8 @@ const { authenticate, authenticate_noerror } = require('../middleware/authentica const Cart = require('../models/cart'); const CartClass = require('../modules/Cart'); const Product = require('../models/product'); +const Order = require('../models/order'); +const OrdersCart = require('../models/orderscart'); const Variant = require('../models/variant'); const TypedError = require('../modules/ErrorHandler'); @@ -1303,6 +1305,25 @@ async function eseguiDbOp(idapp, mydata, locale, req, res) { ris = populate.popolaTabelleNuove(); + } else if (mydata.dbop === 'dropProducts') { + + ris = Product.collection.drop(); + ris = ProductInfo.collection.drop(); + + } else if (mydata.dbop === 'dropAllOrders') { + + try { + ris = Order.collection.drop(); + ris = OrdersCart.collection.drop(); + ris = Cart.collection.drop(); + } catch (e) { + console.error('Err:', e); + } + + } else if (mydata.dbop === 'dropAllCarts') { + + ris = Cart.collection.drop(); + } else if (mydata.dbop === 'RewriteCitiesTable') { ris = populate.rewriteTable('cities'); diff --git a/src/server/tools/general.js b/src/server/tools/general.js index 5131605..8ebcf62 100755 --- a/src/server/tools/general.js +++ b/src/server/tools/general.js @@ -4364,6 +4364,9 @@ module.exports = { } }, + isObjectEmpty(obj) { + return Object.keys(obj).length === 0; + }, }; diff --git a/src/server/tools/globalTables.js b/src/server/tools/globalTables.js index cfa764e..9bb43a8 100755 --- a/src/server/tools/globalTables.js +++ b/src/server/tools/globalTables.js @@ -56,6 +56,7 @@ const { Permission } = require('../models/permission'); const { MsgTemplate } = require('../models/msg_template'); const { Graduatoria } = require('../models/graduatoria'); const Product = require('../models/product'); +const ProductInfo = require('../models/productinfo'); const Producer = require('../models/producer'); const Cart = require('../models/cart'); const OrdersCart = require('../models/orderscart'); @@ -64,6 +65,7 @@ const Provider = require('../models/provider'); const Gasordine = require('../models/gasordine'); const Scontistica = require('../models/scontistica'); const Department = require('../models/department'); +const CatProd = require('../models/catprod'); const { Category } = require('../models/category'); const ShareWithUs = require('../models/sharewithus'); const Site = require('../models/site'); @@ -105,6 +107,8 @@ module.exports = { mytable = Operator; else if (tablename === 'products') mytable = Product; + else if (tablename === 'productinfos') + mytable = ProductInfo; else if (tablename === 'storehouses') mytable = Storehouse; else if (tablename === 'providers') @@ -117,6 +121,8 @@ module.exports = { mytable = Department; else if (tablename === 'categorys') mytable = Category; + else if (tablename === 'catprods') + mytable = CatProd; else if (tablename === 'sharewithus') mytable = ShareWithUs; else if (tablename === 'sites')