Gestione Ordini: evaso...

This commit is contained in:
Surya Paolo
2023-12-13 19:17:53 +01:00
parent a2bd4f6e97
commit fcdd826c54
11 changed files with 314 additions and 125 deletions

View File

@@ -42,6 +42,41 @@ const orderSchema = new Schema({
quantity: {
type: Number
},
evaso: { // e quindi è stato tolto dal magazzino (aggiornando il campo StockQty)
type: Boolean,
default: false,
},
date_evaso: {
type: Date
},
pagato: {
type: Boolean,
default: false,
},
date_pagato: {
type: Date
},
spedito: {
type: Boolean,
default: false,
},
date_spedito: {
type: Date
},
completed: {
type: Boolean,
default: false,
},
date_completed: {
type: Date
},
consegnato: {
type: Boolean,
default: false,
},
date_consegnato: {
type: Date
},
weight: {
type: Number
},
@@ -148,6 +183,14 @@ module.exports.updateStatusOrders = async function (arrOrders, 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) {
const query = [
{ $match: { _id: ObjectID(id) } },

View File

@@ -31,6 +31,41 @@ const OrdersCartSchema = new Schema({
type: Number,
Default: 0,
},
evaso: { // e quindi è stato tolto dal magazzino (aggiornando il campo StockQty)
type: Boolean,
default: false,
},
date_evaso: {
type: Date
},
pagato: {
type: Boolean,
default: false,
},
date_pagato: {
type: Date
},
spedito: {
type: Boolean,
default: false,
},
date_spedito: {
type: Date
},
completed: {
type: Boolean,
default: false,
},
date_completed: {
type: Date
},
consegnato: {
type: Boolean,
default: false,
},
date_consegnato: {
type: Date
},
note: {
type: String
},
@@ -67,20 +102,15 @@ module.exports.getFieldsForSearch = function () {
};
module.exports.getNewNumOrder = async function (uid, idapp) {
module.exports.getLastNumOrder = 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);
if (numorderrec.length <= 0)
numorder = 1;
else
if (numorderrec && numorderrec.length > 0)
numorder = numorderrec[0].numorder;
if (numorder) {
numorder++
} else {
numorder = 1;
}
else
numorder = 0;
return numorder;
@@ -100,6 +130,25 @@ module.exports.getStatusCartByUserId = async function (uid, idapp, numorder) {
else
return shared_consts.OrderStatus.NONE
}
module.exports.getRecCartByUserId = async function (uid, idapp, numorder) {
let query = { userId: uid, idapp, status: { $gte: shared_consts.OrderStatus.CHECKOUT_SENT } }
let myorderscart = null;
if (numorder > 0) {
query = { userId: uid, idapp, numorder, status: { $gte: shared_consts.OrderStatus.CHECKOUT_SENT } }
}
myorderscart = await OrdersCart.findOne(query).lean();
return myorderscart
}
module.exports.getOrdersCartById = async function (id) {
let query = { _id: id };
return await OrdersCart.findOne(query);
}
module.exports.getOrdersCartByUserId = async function (uid, idapp, numorder) {
@@ -223,7 +272,7 @@ module.exports.updateOrdersCartById = function (id, newOrdersCart, callback) {
//exist cart in databse
if (c.length > 0) {
OrdersCart.findOneAndUpdate(
return OrdersCart.findOneAndUpdate(
{ _id: id },
{
$set: {
@@ -242,14 +291,111 @@ module.exports.updateOrdersCartById = function (id, newOrdersCart, callback) {
)
} else {
//no cart in database
newOrdersCart.save(callback)
return newOrdersCart.save(callback)
}
})
}
module.exports.setEvasoById = async function (id, evaso) {
return await OrdersCart.findOneAndUpdate(
{ _id: id },
{
$set: {
evaso,
date_evaso: new Date(),
}
},
{ new: false }
)
}
module.exports.setConsegnatoById = async function (id, consegnato) {
return await OrdersCart.findOneAndUpdate(
{ _id: id },
{
$set: {
consegnato,
date_consegnato: new Date(),
}
},
{ new: false }
)
}
module.exports.setSpeditoById = async function (id, spedito) {
return await OrdersCart.findOneAndUpdate(
{ _id: id },
{
$set: {
spedito,
date_spedito: new Date(),
}
},
{ new: false }
)
}
module.exports.setPagatoById = async function (id, pagato) {
return await OrdersCart.findOneAndUpdate(
{ _id: id },
{
$set: {
pagato,
date_pagato: new Date(),
}
},
{ new: false }
)
}
module.exports.setCompletatoById = async function (id, completato) {
return await OrdersCart.findOneAndUpdate(
{ _id: id },
{
$set: {
completato,
date_completato: new Date(),
}
},
{ new: false }
)
}
module.exports.createOrdersCart = async function (newOrdersCart) {
return await newOrdersCart.save()
}
module.exports.updateCmd = async function (idorderscart, cmd, value) {
let myOrderCart = await OrdersCart.findOne({ _id: idorderscart });
try {
if (!!myOrderCart) {
const id = myOrderCart._id;
if (cmd === shared_consts.OrderStatus.ORDER_CONFIRMED) {
ris = await OrdersCart.setEvasoById(id, value);
} else if (cmd === shared_consts.OrderStatus.DELIVERED) {
ris = await OrdersCart.setConsegnatoById(id, value);
} else if (cmd === shared_consts.OrderStatus.SHIPPED) {
ris = await OrdersCart.setSpeditoById(id, value);
} else if (cmd === shared_consts.OrderStatus.PAYED) {
ris = await OrdersCart.setPagatoById(id, value);
} else if (cmd === shared_consts.OrderStatus.COMPLETED) {
ris = await OrdersCart.setCompletatoById(id, value);
}
// myOrderCart = await OrdersCart.findOne({ _id: idorderscart });
}
} catch (e) {
console.error('Err:', e)
}
}
OrdersCartSchema.pre('save', async function (next) {

View File

@@ -21,6 +21,7 @@ const productSchema = new Schema({
},
active: {
type: Boolean,
default: true,
},
idProducer: { type: Schema.Types.ObjectId, ref: 'Producer' },
idStorehouses: [
@@ -172,50 +173,44 @@ module.exports.findAllIdApp = async function (idapp, code) {
},
{
$lookup: {
from: "orders",
localField: "_id",
foreignField: "idProduct",
as: "productOrders",
},
},
{
$unwind: {
path: "$productOrders",
preserveNullAndEmptyArrays: true,
},
},
{
$group: {
_id: "$_id",
products: { $push: "$$ROOT" },
totalQty: {
$sum: {
$cond: {
if: { $lt: ["$productOrders.status", 4] }, // Include stati minori di 4
then: "$productOrders.quantity",
else: 0
}
from: 'orders',
let: { productId: '$_id' },
pipeline: [
{
$match: {
$expr: {
$and: [
{ $eq: ['$idProduct', '$$productId'] },
{ $lt: ['$status', shared_consts.OrderStatus.ORDER_CONFIRMED] }
]
}
},
},
},
{
$project: {
_id: 0,
products: {
$map: {
input: "$products",
as: "product",
in: {
$mergeObjects: [
"$$product",
{ totalQty: { quantity: "$totalQty" } }
]
}
},
{
$group: {
_id: null,
totalQty: { $sum: '$quantity' }
}
}
],
as: 'productOrders'
}
},
{
$addFields: {
totalQty: {
$cond: {
if: { $isArray: '$productOrders' },
then: { $arrayElemAt: ['$productOrders.totalQty', 0] },
else: 0
}
}
}
}
},
{
$unset: 'productOrders'
},
];
let ris = await Product.aggregate(query)

View File

@@ -79,7 +79,7 @@ router.delete('/:id/:notify/:idapp', authenticate, (req, res) => {
const notify = req.params.notify;
const idapp = req.params.idapp;
Booking.findByIdAndRemove(id).then((recbooking) => {
Booking.deleteOne({_id: id}).then((recbooking) => {
if (!recbooking) {
return res.status(404).send();
}

View File

@@ -113,7 +113,7 @@ router.delete('/:userId', authenticate, async function (req, res) {
const mycart = await Cart.getCartByUserId(userId, idapp);
// Rimuovere l'Ordine
const recremoved = await Order.findByIdAndRemove(orderId);
const recremoved = await Order.deleteOne({ _id: orderId });
if (recremoved) {
// Rimuovere l'id sul Carrello
@@ -186,41 +186,52 @@ router.put('/:userId', authenticate, async function (req, res, next) {
})
//POST cart
router.post('/:userId/cartstatus', authenticate, async function (req, res, next) {
router.post('/:userId/createorderscart', authenticate, async function (req, res, next) {
let idapp = req.body.idapp;
let userId = req.params.userId;
let cart_id = req.body.cart_id;
let userId = req.params.userId;
const user = req.user;
let status = req.body.status;
const mycart = await Cart.getCartByUserId(userId, idapp);
const numorder = await OrdersCart.getNewNumOrder(userId, idapp);
let statusOrderCart = await OrdersCart.getStatusCartByUserId(userId, idapp, numorder);
try {
const mycart = await Cart.findOne({ _id: cart_id });
let numorder = await OrdersCart.getLastNumOrder(userId, idapp);
// Esiste l'ordine ?
let myorderCart = await OrdersCart.getRecCartByUserId(userId, idapp, numorder);
if (!myorderCart) {
// crea il nuovo numero d'ordine
numorder++;
// SE non esiste allora lo creo !
myorderCart = new OrdersCart({
idapp,
items: mycart.items,
totalQty: mycart.totalQty,
totalPrice: mycart.totalPrice,
userId,
status,
note: mycart.note,
numorder,
created_at: new Date(),
modify_at: new Date(),
})
}
statusOrderCart = myorderCart.status;
if (!!mycart) {
if (status === shared_consts.OrderStatus.CHECKOUT_SENT) {
// Porta tutto il Cart nell'Ordine
const newOrderCart = new OrdersCart({
idapp,
items: mycart.items,
totalQty: mycart.totalQty,
totalPrice: mycart.totalPrice,
userId,
status,
note: mycart.note,
numorder,
created_at: new Date(),
modify_at: new Date(),
})
return await OrdersCart.updateOrdersCartById(-1, newOrderCart, async function (err, ris) {
// Porta tutto il Cart nell'Ordine e lo CREO
return await OrdersCart.updateOrdersCartById(-1, myorderCart, async function (err, ris) {
//if (err) return next(err)
if (err)
return res.send({ code: server_constants.RIS_CODE_ERR, status: 0 });
else {
await Product.updateStatusOrders(mycart.items, status);
await Order.updateStatusOrders(mycart.items, status);
const myris = ris;
// Cancella il Cart appena salvato in OrdersCart
@@ -228,15 +239,19 @@ router.post('/:userId/cartstatus', authenticate, async function (req, res, next)
return Cart.deleteCartByCartId(mycart._id)
.then((ris) => {
const orders = OrdersCart.getOrdersCartByUserId(userId, idapp, numorder)
return OrdersCart.getOrdersCartByUserId(userId, idapp, numorder)
.then((orders) => {
if (!!orders) {
// Invia la email dell'Ordine
sendemail.sendEmail_OrderProduct(user.lang, idapp, orders[0], user)
.then((ris) => {
.then(async (ris) => {
myorderCart = await OrdersCart.getRecCartByUserId(userId, idapp, numorder);
return res.send({
code: server_constants.RIS_CODE_OK,
status: myris.status,
orders: orders
orders: orders,
recOrderCart: myorderCart
});
});
}
@@ -244,34 +259,22 @@ router.post('/:userId/cartstatus', authenticate, async function (req, res, next)
})
}
})
// mycart.numorder = await Cart.getNewNumOrder(userId, idapp);
// mycart.status = shared_consts.OrderStatus.CHECKOUT_CONFIRMED
/* const status = await Cart.findOneAndUpdate(
{ userId },
{
$set: {
status: mycart.status, numorder: mycart.numorder
}
},
{ new: false })
.then((rec) => {
return rec.status
}) */
}
}
return res.send({ code: server_constants.RIS_CODE_OK, status: statusOrderCart });
return res.send({
code: server_constants.RIS_CODE_OK,
status: statusOrderCart,
recOrderCart: myorderCart
});
} catch (e) {
return res.send({ code: server_constants.RIS_CODE_ERR, status: 0 });
return res.send({ code: server_constants.RIS_CODE_ERR, status: 0, recOrderCart: null });
}
});
//POST cart
router.post('/:userId/orderstatus', authenticate, async function (req, res, next) {
router.post('/:userId/ordercartstatus', authenticate, async function (req, res, next) {
let idapp = req.body.idapp;
let userId = req.params.userId;
let order_id = req.body.order_id;
@@ -290,24 +293,20 @@ router.post('/:userId/orderstatus', authenticate, async function (req, res, next
let fields_to_update = { status };
if (status === shared_consts.OrderStatus.RECEIVED) {
fields_to_update = {
status,
completed_at: new Date()
}
}
await OrdersCart.findOneAndUpdate({ _id: order_id }, { $set: fields_to_update }
, { new: false })
.then((ris) => {
.then(async (ris) => {
if (ris) {
let ordertype = '';
// Aggiorna gli Stati Interni !
await OrdersCart.updateCmd(orderCart, status, true);
let ordertype = '';
if (status === shared_consts.OrderStatus.ORDER_CONFIRMED) {
ordertype = 'order_confirmed';
} else if (status === shared_consts.OrderStatus.RECEIVED) {
} else if (status === shared_consts.OrderStatus.COMPLETED) {
ordertype = 'order_completed';
} else if (status === shared_consts.OrderStatus.CANCELED) {
ordertype = 'order_canceled';

View File

@@ -1255,7 +1255,7 @@ router.delete('/delrec/:table/:id', authenticate, async (req, res) => {
if (!cancellato) {
// ELIMINA VERAMENTE IL RECORD !!!
ris = await mytable.findByIdAndRemove(id).then((rec) => {
ris = await mytable.deleteOne({_id: id}).then((rec) => {
if (!rec) {
// res.status(404).send();
return false;

View File

@@ -73,7 +73,7 @@ router.delete('/:id/:notify/:idapp', authenticate, (req, res) => {
const notify = req.params.notify;
const idapp = req.params.idapp;
myevent.findByIdAndRemove(id).then((recmyevent) => {
myevent.deleteOne({_id: id}).then((recmyevent) => {
if (!recmyevent) {
return res.status(404).send();
}

View File

@@ -251,7 +251,7 @@ router.delete('/:id', authenticate, (req, res) => {
} else {
Project.findByIdAndRemove(id).then((project) => {
Project.deleteOne({_id: id}).then((project) => {
if (!project) {
return res.status(404).send();
}

View File

@@ -254,7 +254,7 @@ router.delete('/:id', authenticate, (req, res) => {
});
} else {
Todo.findByIdAndRemove(id).then((todo) => {
Todo.deleteOne({_id: id}).then((todo) => {
if (!todo) {
return res.status(404).send();
}

View File

@@ -784,7 +784,7 @@ module.exports = {
mylocalsconf = this.setParamsForTemplate(user, mylocalsconf);
if ((status !== shared_consts.OrderStatus.CANCELED) && (status !== shared_consts.OrderStatus.RECEIVED)) {
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);

View File

@@ -242,8 +242,8 @@ module.exports = {
{ table: 'skills', key: 'descr' },
{ table: 'statusSkills', key: 'descr' },
],
VISIB_ALL: 0,
VISIB_ONLYIF_VERIFIED: 1,
VISIB_ONLY_MANAGER: 2,
@@ -376,24 +376,30 @@ module.exports = {
ENTRA_RIS_ITALIA: 30,
},
OrderStatus: {
NONE: 0,
IN_CART: 1,
CHECKOUT_SENT: 2,
ORDER_CONFIRMED: 3,
PAYED: 4,
DELIVEDED: 5,
RECEIVED: 6,
DELIVERED: 5, // Consegnato
SHIPPED: 6, //Spedito
RECEIVED: 7,
COMPLETED: 6,
CANCELED: 10,
},
OrderStatStr: {
IN_CORSO: 1,
CONFERMATI: 2,
PAGATI: 3,
COMPLETATI: 4,
CANCELLATI: 5,
OrderStat: {
// IN_CART: { label: 'In Carrello', value: 1 }, //IN_CART
IN_CORSO: { label: 'In Corso', value: 2, icon: 'fas fa-tasks', color: 'text-black' }, //CHECKOUT_SENT
CONFERMATI: { label: 'Confermati', value: 3, icon: 'fas fa-calendar', color: 'text-blue' }, //ORDER_CONFIRMED
PAGATI: { label: 'Pagati', value: 4, icon: 'money', color: 'text-green' }, //PAYED
DELIVERED: { label: 'Consegnato', value: 5, icon: 'fas fa-calendar', color: 'text-blue' }, //DELIVERED
SHIPPED: { label: 'Spediti', value: 6, icon: 'fas fa-shipping-fast', color: 'text-green' }, //SHIPPED
RECEIVED: { label: 'Ricevuti', value: 7, icon: '', color: 'text-blue' }, //RECEIVED
COMPLETATI: { label: 'Completati', value: 8, icon: 'fas fa-check', color: 'text-blue' }, //COMPLETED
CANCELLATI: { label: 'Cancellati', value: 10, icon: 'delete', color: 'text-red' }, //CANCELED
},
OrderStatusView: {
@@ -769,7 +775,7 @@ module.exports = {
'mygrp.groupname': 1,
'mygrp.title': 1,
'mygrp.photos': 1,
//**ADDFIELD_MYBACHECAS
//**ADDFIELD_MYBACHECAS
}
}
@@ -822,7 +828,7 @@ module.exports = {
if (proj_add)
proj = Object.assign({}, proj, proj_add);
proj = {...proj, ...this.REACTIONS_FIELD};
proj = { ...proj, ...this.REACTIONS_FIELD };
if (table) {
let proj_add3 = this.getProjectByTable(table);