Aggiornamento modifiche preOrdini

This commit is contained in:
Surya Paolo
2023-12-20 21:52:17 +01:00
parent 56b5bac5f0
commit 0e1fc359a0
11 changed files with 290 additions and 61 deletions

File diff suppressed because one or more lines are too long

View File

@@ -45,6 +45,7 @@ html
- var price = product.order.price
- var after_price = product.order.after_price
- var qty = product.order.quantity
- var qtypreordered = product.order.quantitypreordered
- index = index + 1
table(cellpadding="0", cellspacing="0", width="100%", summary="", border="0", align="center")
@@ -66,9 +67,14 @@ html
tr
td(class="sectionContent", valign="top")
p Prezzo: #{price} € #{after_price}
tr
td(class="sectionContent", valign="top")
p Quantità: #{qty}
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}
p Note Aggiuntive: #{note}

View File

@@ -45,6 +45,7 @@ html
- var price = product.price
- var after_price = product.after_price
- var qty = product.quantity
- var qtypreordered = product.order.quantitypreordered
- index = index + 1
table(cellpadding="0", cellspacing="0", width="100%", summary="", border="0", align="center")
@@ -66,9 +67,14 @@ html
tr
td(class="sectionContent", valign="top")
p Prezzo: #{price} € #{after_price}
tr
td(class="sectionContent", valign="top")
p Quantità: #{qty}
if (qty > 0)
tr
td(class="sectionContent", valign="top")
p Quantità: #{qty}
if (qtypreordered > 0)
tr
td(class="sectionContent", valign="top")
p Quantità Prenotata: #{qtypreordered}
p Note Aggiuntive: #{note}

View File

@@ -2,6 +2,7 @@
const mongoose = require('mongoose').set('debug', false)
const Schema = mongoose.Schema;
const shared_consts = require('../tools/shared_nodejs');
const { ObjectID } = require('mongodb');
@@ -44,11 +45,15 @@ const orderSchema = new Schema({
type: Number,
default: 0,
},
quantitypreordered: {
type: Number,
default: 0,
},
TotalPriceProduct: {
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,
},
@@ -306,7 +311,102 @@ module.exports.getTotalOrderById = async function (id) {
path: '$provider',
preserveNullAndEmptyArrays: true,
},
}
},
{
$lookup: {
from: 'orders',
let: { productId: '$product._id' },
pipeline: [
{
$match: {
$expr: {
$and: [
{ $eq: ['$idProduct', '$$productId'] },
{ $lt: ['$status', shared_consts.OrderStatus.ORDER_CONFIRMED] }
]
}
}
},
{
$group: {
_id: null,
totalQty: { $sum: '$quantity' },
}
}
],
as: 'productOrders'
}
},
{
$lookup: {
from: 'orders',
let: { productId: '$product._id' },
pipeline: [
{
$match: {
$expr: {
$and: [
{ $eq: ['$idProduct', '$$productId'] },
{ $lt: ['$status', shared_consts.OrderStatus.ORDER_CONFIRMED] }
]
}
}
},
{
$group: {
_id: null,
totalQtyPreordered: { $sum: '$quantitypreordered' }
}
}
],
as: 'productPreOrders'
}
},
{
$addFields: {
'product.QuantitaOrdinateInAttesa': {
$ifNull: [
{
$cond: {
if: { $isArray: '$productOrders' },
then: { $arrayElemAt: ['$productOrders.totalQty', 0] },
else: 0
}
},
0
]
},
'product.QuantitaPrenotateInAttesa': {
$ifNull: [
{
$cond: {
if: { $isArray: '$productPreOrders' },
then: { $arrayElemAt: ['$productPreOrders.totalQtyPreordered', 0] },
else: 0
}
},
0
]
},
},
},
{
$addFields: {
'product.quantityAvailable': {
$subtract: ["$product.stockQty", "$product.QuantitaOrdinateInAttesa"],
},
'product.bookableAvailableQty': {
$subtract: ["$product.bookableQty", "$product.QuantitaPrenotateInAttesa"],
}
}
},
{
$unset: 'productOrders'
},
{
$unset: 'productPreOrders'
},
];
return await Order.aggregate(query);

View File

@@ -22,6 +22,7 @@ const OrdersCartSchema = new Schema({
numord_pers: { type: Number },
userId: { type: Schema.Types.ObjectId, ref: 'User' },
totalQty: { type: Number, default: 0 },
totalQtyPreordered: { type: Number, default: 0 },
totalPrice: { type: Number, default: 0 },
department: {
type: String, ref: 'Department'
@@ -250,10 +251,10 @@ module.exports.getOrdersCartByQuery = async function (query) {
return myorderscart;
}
module.exports.getOrdersCartByUserId = async function (uid, idapp, numorder) {
module.exports.getOrdersCartByUserId = async function (uid, idapp, numorder, filterStatus) {
try {
let query = { idapp, status: { $gte: shared_consts.OrderStatus.CHECKOUT_SENT }, deleted: false }
let query = { idapp, deleted: false }
let myorderscart = null;
if (numorder > 0) {
query.numorder = numorder;
@@ -263,10 +264,14 @@ module.exports.getOrdersCartByUserId = async function (uid, idapp, numorder) {
query.userId = uid;
}
if (filterStatus) {
query.status = { $gte: shared_consts.OrderStatus.CHECKOUT_SENT };
}
myorderscart = await OrdersCart.getOrdersCartByQuery(query);
if (myorderscart)
console.log('*** Num myorderscart ', myorderscart.length);
// if (myorderscart)
// console.log('*** Num myorderscart ', myorderscart.length);
/*transform: function(doc, populated) {
@@ -301,6 +306,7 @@ module.exports.updateOrdersCartById = function (id, newOrdersCart, callback) {
$set: {
items: newOrdersCart.items,
totalQty: newOrdersCart.totalQty,
totalQtyPreordered: newOrdersCart.totalQtyPreordered,
totalPrice: newOrdersCart.totalPrice,
userId: userId,
status: newOrdersCart.status,
@@ -433,12 +439,18 @@ module.exports.updateStockQtaDalMagazzino = async function (idorderscart) {
let order = myorderscart.items[idkey].order;
if (!order.evaso) {
const update = {
let update = {
$inc: {
stockQty: -order.quantity
}
};
await Product.findOneAndUpdate({ _id: order.idProduct }, update, { new: false });
update = {
$inc: {
bookableQty: -order.quantitypreordered
}
};
await Product.findOneAndUpdate({ _id: order.idProduct }, update, { new: false });
}
}
@@ -544,12 +556,17 @@ module.exports.getmsgorderTelegram = async function (ordersCart) {
msg += '<br><br>Lista Prodotti:';
for (const ord of ordersCart.items) {
msg += '<br>';
msg += '✅ [' + ord.order.quantity + '] ' + ord.order.product.name + ' (' + ord.order.price + ' € ' + (ord.order.after_price ? ord.order.after_price : '') + ' Tot=' + ord.order.TotalPriceProduct + '€ )';
let qtystr = ''
if (ord.order.quantity > 0)
qtystr += 'Ordinate: ' + ord.order.quantity
if (ord.order.quantitypreordered > 0)
qtystr += 'Prenotate: ' + 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 += '<br>';
msg += '<br>Totale Prodotti: ' + ordersCart.totalQty;
msg += '<br>Totale Prodotti: ' + ordersCart.totalQty + ordersCart.totalQtyPreordered;
msg += '<br>Totale Ordine: ' + ordersCart.totalPrice + ' € 💰';

View File

@@ -96,6 +96,10 @@ const productSchema = new Schema({
type: Number,
default: 0,
},
bookableQty: { // Quantità prenotabili
type: Number,
default: 0,
},
quantityLow: { //Soglia disponibilità bassa
type: Number,
default: 0,
@@ -275,27 +279,82 @@ module.exports.findAllIdApp = async function (idapp, code, id) {
{
$group: {
_id: null,
totalQty: { $sum: '$quantity' }
totalQty: { $sum: '$quantity' },
}
}
],
as: 'productOrders'
}
},
{
$lookup: {
from: 'orders',
let: { productId: '$_id' },
pipeline: [
{
$match: {
$expr: {
$and: [
{ $eq: ['$idProduct', '$$productId'] },
{ $lt: ['$status', shared_consts.OrderStatus.ORDER_CONFIRMED] }
]
}
}
},
{
$group: {
_id: null,
totalQtyPreordered: { $sum: '$quantitypreordered' }
}
}
],
as: 'productPreOrders'
}
},
{
$addFields: {
QuantitaOrdinateInAttesa: {
$cond: {
if: { $isArray: '$productOrders' },
then: { $arrayElemAt: ['$productOrders.totalQty', 0] },
else: 0
}
$ifNull: [
{
$cond: {
if: { $isArray: '$productOrders' },
then: { $arrayElemAt: ['$productOrders.totalQty', 0] },
else: 0
}
},
0
]
},
QuantitaPrenotateInAttesa: {
$ifNull: [
{
$cond: {
if: { $isArray: '$productPreOrders' },
then: { $arrayElemAt: ['$productPreOrders.totalQtyPreordered', 0] },
else: 0
}
},
0
]
},
},
},
{
$addFields: {
quantityAvailable: {
$subtract: ["$stockQty", "$QuantitaOrdinateInAttesa"],
},
bookableAvailableQty: {
$subtract: ["$bookableQty", "$QuantitaPrenotateInAttesa"],
}
}
},
{
$unset: 'productOrders'
},
{
$unset: 'productPreOrders'
},
);
@@ -352,6 +411,14 @@ module.exports.getProductByID = function (id, callback) {
Product.findById(id, callback);
}
module.exports.updateProductInOrder = async function (order) {
if (order.product)
order.product = await Product.getProductById(order.product._id);
return order;
}
module.exports.createIndexes((err) => {
if (err) throw err;
});

View File

@@ -34,24 +34,49 @@ class Cart {
}
}
isAvailableByOrder(order) {
if (order && order.product) {
return (order.product.quantityAvailable > 0)
}
return false;
}
isInPreorderByOrder(order) {
if (order && order.product) {
return (order.product.bookableAvailableQty > 0)
}
return false;
}
async addqty(itemorder) {
const myitem = this.items.find((rec) => rec.order._id.toString() === itemorder._id)
if (!!myitem) {
myitem.order.quantity++;
if (this.isAvailableByOrder(myitem.order)) {
myitem.order.quantity++;
} else {
myitem.order.quantitypreordered++;
}
this.updatetotals();
await Order.findOneAndUpdate({ _id: myitem.order._id }, { $set: myitem.order }, { new: false });
return myitem.order.quantity;
return myitem.order;
}
}
async subqty(itemorder) {
try {
const myitem = this.items.find((rec) => rec.order._id.toString() === itemorder._id)
if (!!myitem && myitem.order.quantity > 0) {
myitem.order.quantity--;
if (!!myitem) {
if (myitem.order.quantitypreordered > 0) {
myitem.order.quantitypreordered--;
} else {
if (myitem.order.quantity > 0) {
myitem.order.quantity--;
}
}
this.updatetotals();
await Order.findOneAndUpdate({ _id: myitem.order._id }, { $set: myitem.order }, { new: false });
return myitem.order.quantity;
return myitem.order;
}
} catch (e) {
console.error('Err: ', e);
@@ -76,17 +101,22 @@ class Cart {
}
generateModel() {
let newCart = new cartModel({
idapp: this.idapp,
items: this.generateArray(),
totalQty: this.totalQty,
totalPrice: this.totalPrice,
userId: this.userId,
department: this.department,
note: this.note,
modify_at: this.modify_at
})
return newCart
try {
let newCart = new cartModel({
idapp: this.idapp,
items: this.generateArray(),
totalQty: this.totalQty,
totalPrice: this.totalPrice,
userId: this.userId,
department: this.department,
note: this.note,
modify_at: this.modify_at
})
return newCart
} catch (e) {
console.error('Err', e);
}
return null;
}
updatetotals() {
@@ -95,19 +125,19 @@ class Cart {
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.totalQty += order.quantity + order.quantitypreordered;
// Calcolo Sconto
let sconti_da_applicare = [];
if (order.scontisticas) {
let qtadascontare = order.quantity
let qtadascontare = order.quantity + order.quantitypreordered
let qtanonscontata = 0
while (qtadascontare > 0) {
@@ -145,9 +175,9 @@ class Cart {
if (qtanonscontata > 0) {
mypricecalc += order.price * qtanonscontata;
}
} else {
mypricecalc = order.price * order.quantity;
mypricecalc = (order.price * order.quantity) + (order.price * order.quantitypreordered);
}
order.TotalPriceProduct += mypricecalc;
this.totalPrice += order.TotalPriceProduct;

View File

@@ -64,7 +64,6 @@ router.post('/:userId', authenticate, async function (req, res, next) {
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)
@@ -75,16 +74,19 @@ router.post('/:userId', authenticate, async function (req, res, next) {
}
let newCart = CartClass.constructByCart(mycart);
// order = await Product.updateProductInOrder(order);
if (!nuovo) {
if (addqty) {
myqty = await newCart.addqty(order);
myord = await newCart.addqty(order);
} else if (subqty) {
myqty = await newCart.subqty(order);
myord = await newCart.subqty(order);
} else {
const ind = newCart.addItem(order);
myord = order;
}
} else {
await newCart.updatetotals();
myord = order;
}
cart = await Cart.updateCartByCartId(mycart._id, newCart.generateModel());
@@ -95,9 +97,10 @@ router.post('/:userId', authenticate, async function (req, res, next) {
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 });
return res.send({ code: server_constants.RIS_CODE_OK, cart: carttot, myord, product });
} else {
return res.send({ code: server_constants.RIS_CODE_ERR, cart: null });
console.error('Err:', err);
return res.send({ code: server_constants.RIS_CODE_ERR, cart: null, myord: null });
}
/*
@@ -360,9 +363,9 @@ router.post('/:userId/ordercartstatus', authenticate, async function (req, res,
if (User.isManager(user.perm)) {
// Prende Tutti gli Ordini !
orderscart = await OrdersCart.getOrdersCartByUserId('ALL', idapp, 0);
orderscart = await OrdersCart.getOrdersCartByUserId('ALL', idapp, 0, false);
} else {
orderscart = await OrdersCart.getOrdersCartByUserId(req.user.id, idapp, 0);
orderscart = await OrdersCart.getOrdersCartByUserId(req.user.id, idapp, 0, false);
}
return res.send({ code: server_constants.RIS_CODE_OK, status, orders: orderscart });

View File

@@ -1466,9 +1466,9 @@ function load(req, res, version) {
cart = Cart.getCartByUserId(req.user.id, idapp);
if (User.isManager(req.user.perm)) {
// Prende Tutti gli Ordini !
orderscart = OrdersCart.getOrdersCartByUserId('ALL', idapp, 0);
orderscart = OrdersCart.getOrdersCartByUserId('ALL', idapp, 0, false);
} else {
orderscart = OrdersCart.getOrdersCartByUserId(req.user.id, idapp, 0);
orderscart = OrdersCart.getOrdersCartByUserId(req.user.id, idapp, 0, false);
}
}
let askedfriends = [];

View File

@@ -30,14 +30,15 @@ const OrdersCart = require('../models/orderscart');
router.get('/:userId', authenticate, function (req, res, next) {
let userId = req.body.userId
let idapp = req.body.idapp
OrdersCart.getOrdersCartByUserId(userId, idapp, 0, function (err, cart) {
if (err) return next(err)
OrdersCart.getOrdersCartByUserId(userId, idapp, 0, false)
.then((cart) => {
if (cart)
res.send({ code: server_constants.RIS_CODE_OK, cart });
else
res.status(400).send(e);
})
if (cart)
res.send({ code: server_constants.RIS_CODE_OK, cart });
else
res.status(400).send(e);
})
})
module.exports = router;

View File

@@ -36,9 +36,9 @@ router.post('/', auth_default, async function (req, res, next) {
let orders = null;
if (await User.isManagerById(userId)) {
// Prende Tutti gli Ordini !
orders = await OrdersCart.getOrdersCartByUserId('ALL', idapp, 0);
orders = await OrdersCart.getOrdersCartByUserId('ALL', idapp, 0, false);
} else {
orders = await OrdersCart.getOrdersCartByUserId(userId, idapp, 0);
orders = await OrdersCart.getOrdersCartByUserId(userId, idapp, 0, false);
}
if (products)