- Esporta Lista Carrello (Totale)

- Sconto Applicato
This commit is contained in:
Surya Paolo
2025-06-09 09:48:40 +02:00
parent f88f433003
commit d1d4b73da0
7 changed files with 646 additions and 567 deletions

View File

@@ -10,6 +10,8 @@ var server_constants = require('../tools/server_constants');
var { Project } = require('../models/project');
const Scontistica = require('../models/scontistica');
var { authenticate, auth_default } = require('../middleware/authenticate');
const _ = require('lodash');
@@ -28,26 +30,46 @@ const paypal_config = require('../configs/paypal-config')
const paypal = require('paypal-rest-sdk')
*/
const CartClass = require('../modules/Cart')
const CartClass = require('../modules/Cart');
const Cart = require('../models/cart');
const OrdersCart = require('../models/orderscart');
//GET cart
router.get('/:userId', authenticate, async function (req, res, next) {
let userId = req.params.userId
let idapp = req.user.idapp
let userId = req.params.userId;
let idapp = req.user.idapp;
return await Cart.getCartByUserId(userId, idapp)
.then((cart) => {
if (cart)
return res.send({ code: server_constants.RIS_CODE_OK, cart });
else
return res.send({ code: server_constants.RIS_CODE_OK, cart: null });
}).catch((err) => {
if (cart) return res.send({ code: server_constants.RIS_CODE_OK, cart });
else return res.send({ code: server_constants.RIS_CODE_OK, cart: null });
})
.catch((err) => {
console.error('Err', err);
return res.send({ code: server_constants.RIS_CODE_ERR, cart: null });
});
});
})
async function aggiornaCarrello(mycartpar, userId, idapp) {
try {
let mycart = mycartpar;
if (!mycart) mycart = await Cart.getCartByUserId(userId, idapp);
if (!mycart) {
return null;
}
let newCart = await CartClass.constructByCart(mycart);
// order = await Product.updateProductInOrder(order);
await newCart.updatecarttotals(true);
await newCart.updateExtraOrder();
return newCart;
} catch (e) {
console.error('Err AggiornaCarrello', e);
return null;
}
}
//POST cart
router.post('/:userId', authenticate, async function (req, res, next) {
@@ -60,7 +82,6 @@ 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 });
}
@@ -78,15 +99,14 @@ router.post('/:userId', authenticate, async function (req, res, next) {
// no cart save empty cart to database then return response
let nuovo = false;
if (!mycart) {
let oldCart = new CartClass(order)
let oldCart = new CartClass(order);
cart = await Cart.createCart(oldCart.generateModel());
mycart = await Cart.getCartByUserId(userId, idapp);
nuovo = true;
}
let newCart = CartClass.constructByCart(mycart);
let newCart = await CartClass.constructByCart(mycart);
// order = await Product.updateProductInOrder(order);
if (!nuovo) {
// Controlla se sto inserendo un prodotto con 2 Negozi, non permetterlo !
@@ -101,35 +121,35 @@ router.post('/:userId', authenticate, async function (req, res, next) {
myord = arrord ? arrord[0] : null;
}
} else {
return res.send({ code: server_constants.RIS_CODE_ERR, cart: null, myord: null, msgerr: 'Non è possibile acquistare nello stesso ordine, su negozi differenti!' });
return res.send({
code: server_constants.RIS_CODE_ERR,
cart: null,
myord: null,
msgerr: 'Non è possibile acquistare nello stesso ordine, su negozi differenti!',
});
}
} else {
newCart.updatecarttotals(true);
await newCart.updatecarttotals(true);
await newCart.updateExtraOrder();
const arrord = await Order.getTotalOrderById(order._id);
myord = arrord ? arrord[0] : null;
}
cart = await Cart.updateCartByCartId(mycart._id, newCart.generateModel());
if (cart) {
const carttot = await Cart.getCartByUserId(userId, idapp);
if (order.idProduct)
product = await Product.getProductById(order.idProduct);
else if (order.product)
product = await Product.getProductById(order.product._id);
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, myord, product });
} else {
console.error('Err:', err);
return res.send({ code: server_constants.RIS_CODE_ERR, cart: null, myord: null });
}
} catch (e) {
console.error('Err:', e);
return res.send({ code: server_constants.RIS_CODE_ERR, cart: 0 });
}
})
});
router.delete('/:userId', authenticate, async function (req, res) {
console.log('DELETE Item');
@@ -140,17 +160,16 @@ 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 idProduct = '';
let product = null;
if (ord)
idProduct = ord.idProduct;
if (ord) idProduct = ord.idProduct;
// Rimuovere l'Ordine
const recremoved = await Order.deleteOne({ _id: orderId });
if (recremoved) {
// Rimuovere l'id sul Carrello
let newCart = CartClass.constructByCart(mycart);
let newCart = await CartClass.constructByCart(mycart);
await newCart.removeItem(orderId);
let carttot = null;
const cart = await Cart.updateCartByCartId(mycart._id, newCart.generateModel());
@@ -161,29 +180,27 @@ router.delete('/:userId', authenticate, async function (req, res) {
product = await Product.getProductById(idProduct);
}
console.log('carttot', carttot)
console.log('carttot', carttot);
return res.send({ code: server_constants.RIS_CODE_OK, cart: carttot, product });
}
return res.send({ code: server_constants.RIS_CODE_ERR, cart: null });
});
//PUT cart
router.put('/:userId', authenticate, async function (req, res, next) {
let userId = req.params.userId
let requestProduct = req.body
let { productId, color, size } = requestProduct.product
let userId = req.params.userId;
let requestProduct = req.body;
let { productId, color, size } = requestProduct.product;
try {
try {
const cart = await Cart.getCartByUserId(userId);
try {
const myprod = await Product.getProductByID(productId);
let newCart = oldCart.add(myprod, productId, { color, size })
let newCart = oldCart.add(myprod, productId, { color, size });
//exist cart in databse
if (cart.length > 0) {
@@ -193,7 +210,7 @@ router.put('/:userId', authenticate, async function (req, res, next) {
totalQty: newCart.totalQty,
totalPrice: newCart.totalPrice,
totalPriceCalc: newCart.totalPriceCalc,
userId: userId
userId: userId,
});
res.json(result);
} catch (err) {
@@ -206,16 +223,15 @@ router.put('/:userId', authenticate, async function (req, res, next) {
totalQty: newCart.totalQty,
totalPrice: newCart.totalPrice,
totalPriceCalc: newCart.totalPriceCalc,
userId: userId
}
userId: userId,
};
try {
const resultCart = await Cart.createCart(newCartobj);
} catch (err) {
return next(err)
return next(err);
}
res.status(201).json(resultCart);
}
} catch (err) {
return next(err);
}
@@ -223,32 +239,132 @@ router.put('/:userId', authenticate, async function (req, res, next) {
const product = await Product.getProductById(productId);
return res.send({ code: server_constants.RIS_CODE_OK, product });
} catch (err) {
return next(err)
return next(err);
}
let oldCart = new CartClass(c || {})
let oldCart = new CartClass(c || {});
} catch (e) {
return res.send({ code: server_constants.RIS_CODE_ERR, status: 0 });
}
});
})
//POST cart
router.post('/:userId/createorderscart', authenticate, async function (req, res, next) {
router.post('/:userId/app_sc', authenticate, async function (req, res, next) {
let idapp = req.body.idapp;
let cart_id = req.body.cart_id;
let userId = req.params.userId;
let status = req.body.status;
let note = req.body.note;
let codice_sconto = req.body.code;
let options = req.body.options;
let mycart = null;
let valido = false;
let errmsg = '';
try {
let mycart = await Cart.findOne({ _id: cart_id }).lean();
if (codice_sconto === 'RIMUOVI') {
mycart = await Cart.findOneAndUpdate({ _id: cart_id }, { $set: { codice_sconto: '' } }, { new: true }).lean();
return res.send({ mycart, valido, msg: 'Codice Sconto rimosso', rimuovi: true });
}
// attendi 3 secondi prima di poter inviare una nuova richiesta
await tools.attendiNSecondi(1);
if (codice_sconto) {
const condSconto = { $regex: new RegExp(`^${codice_sconto}$`, 'i') };
recscontisticheTrovate = await Scontistica.find({
idapp: idapp,
code: condSconto,
applica: shared_consts.SCONTI_APPLICA.A_TUTTI,
}).lean();
if (recscontisticheTrovate && recscontisticheTrovate.length > 0) {
if (mycart.codice_sconto !== codice_sconto) {
mycart.codice_sconto = codice_sconto;
await Cart.updateOne({ _id: cart_id }, { $set: { codice_sconto: codice_sconto } });
}
valido = true;
mycart = await aggiornaCarrello(mycart, userId, idapp);
} else {
errmsg = `Codice sconto "${codice_sconto}" non valido oppure scaduto`;
}
}
return res.send({ mycart, valido, errmsg, recsconto: recscontisticheTrovate });
} catch (e) {
console.error('Err Applica Sconto', e);
return res.send({ valido: false, mycart: null, errmsg: e.message });
}
});
// Recupera il carrello
async function getCartById(cart_id) {
const cart = await Cart.findOne({ _id: cart_id }).lean();
return cart;
}
// Crea o aggiorna un ordine partendo dal cart
async function createOrUpdateOrderFromCart({ idapp, cart, userId, status, note }) {
let numorder = await OrdersCart.getLastNumOrder(idapp);
let numord_pers = await OrdersCart.getLastNumOrdPers(userId, idapp);
let myorderCart = await OrdersCart.getRecCartByUserId(userId, idapp, numorder);
if (!myorderCart) {
numorder++;
numord_pers++;
myorderCart = new OrdersCart({
idapp,
items: cart.items,
totalQty: cart.totalQty,
totalPrice: cart.totalPrice,
totalPriceCalc: cart.totalPriceCalc,
note_ordine_gas: cart.note_ordine_gas,
userId,
status,
note,
codice_sconto: cart.codice_sconto,
numorder,
numord_pers,
created_at: new Date(),
modify_at: new Date(),
});
}
return myorderCart;
}
// Gestisce l'invio ordine (checkout)
async function handleCheckout({ myorderCart, mycart, userId, idapp, req, options, userDest }) {
try {
const ris = await OrdersCart.updateOrdersCartById(-1, myorderCart);
await Order.updateStatusOrders(mycart.items, shared_consts.OrderStatus.CHECKOUT_SENT);
await Cart.deleteCartByCartId(mycart._id);
const orders = await OrdersCart.getOrdersCartByUserId(userId, idapp, myorderCart.numorder);
if (orders?.[0]) {
await OrdersCart.updateCmd(orders[0], shared_consts.OrderStatus.CHECKOUT_SENT, true, req, options);
await sendemail.sendEmail_OrderProduct(userDest.lang, idapp, orders[0], userDest);
const updatedOrder = await OrdersCart.findById(myorderCart._id).lean();
return { status: ris.status, orders, recOrderCart: updatedOrder };
}
} catch (err) {
console.error('Errore durante il checkout:', err);
throw err;
}
}
//POST cart
router.post('/:userId/createorderscart', authenticate, async function (req, res) {
const { idapp, cart_id, status, note, options } = req.body;
const userId = req.params.userId;
try {
const mycart = await getCartById(cart_id);
if (!mycart) {
return res.send({
code: server_constants.RIS_CODE_OK,
@@ -257,93 +373,43 @@ router.post('/:userId/createorderscart', authenticate, async function (req, res,
});
}
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);
if (!myorderCart) {
// crea il nuovo numero d'ordine
numorder++;
numord_pers++;
// SE non esiste allora lo creo !
myorderCart = new OrdersCart({
idapp,
items: mycart.items,
totalQty: mycart.totalQty,
totalPrice: mycart.totalPrice,
totalPriceCalc: mycart.totalPriceCalc,
note_ordine_gas: mycart.note_ordine_gas,
userId,
status,
note,
numorder,
numord_pers,
created_at: new Date(),
modify_at: new Date(),
})
}
statusOrderCart = myorderCart.status;
const idordercart = myorderCart._id;
let myorderCart = await createOrUpdateOrderFromCart({ idapp, cart: mycart, userId, status, note });
let statusOrderCart = myorderCart.status;
const userDest = await User.findById(userId).lean();
if (!!mycart) {
if (status === shared_consts.OrderStatus.CHECKOUT_SENT) {
if (status === shared_consts.OrderStatus.CHECKOUT_SENT) {
try {
const checkoutResult = await handleCheckout({
myorderCart,
mycart,
userId,
idapp,
req,
options,
userDest,
});
try {
const ris = await OrdersCart.updateOrdersCartById(-1, myorderCart);
// Gestisci il risultato qui
await Order.updateStatusOrders(mycart.items, status);
const myris = ris;
// Cancella il Cart appena salvato in OrdersCart
return Cart.deleteCartByCartId(mycart._id)
.then((ris) => {
return OrdersCart.getOrdersCartByUserId(userId, idapp, numorder)
.then(async (orders) => {
if (!!orders) {
if (orders[0]) {
await OrdersCart.updateCmd(orders[0], status, true, req, options);
// Invia la email dell'Ordine
sendemail.sendEmail_OrderProduct(userDest.lang, idapp, orders[0], userDest)
.then(async (ris) => {
myorderCart = await OrdersCart.findById(idordercart).lean();
return res.send({
code: server_constants.RIS_CODE_OK,
status: myris.status,
orders: orders,
recOrderCart: myorderCart
});
});
}
}
});
})
} catch (err) {
console.error("Errore durante l'aggiornamento dell'ordine:", err);
return res.send({ code: server_constants.RIS_CODE_ERR, status: 0 });
}
return res.send({
code: server_constants.RIS_CODE_OK,
status: checkoutResult.status,
orders: checkoutResult.orders,
recOrderCart: checkoutResult.recOrderCart,
});
} catch (err) {
return res.send({ code: server_constants.RIS_CODE_ERR, status: 0 });
}
}
return res.send({
code: server_constants.RIS_CODE_OK,
status: statusOrderCart,
recOrderCart: myorderCart
recOrderCart: myorderCart,
});
} catch (e) {
console.error('Err', e);
console.error('Errore generale:', e);
return res.send({ code: server_constants.RIS_CODE_ERR, status: 0, recOrderCart: null });
}
});
//POST cart
@@ -356,22 +422,19 @@ router.post('/:userId/ordercartstatus', authenticate, async function (req, res,
const { User } = require('../models/user');
let myOrdersCart = await OrdersCart.findOne({ idapp, _id: order_id }).lean();
if ((userId !== String(req.user._id)) && !User.isManager(req.user.perm)) {
if (userId !== String(req.user._id) && !User.isManager(req.user.perm)) {
// I'm trying to write something not mine!
return res.status(404).send({ code: server_constants.RIS_CODE_TODO_CREATING_NOTMYUSER });
}
try {
if (!!myOrdersCart) {
let fields_to_update = { status };
await OrdersCart.findOneAndUpdate({ _id: order_id }, { $set: fields_to_update }
, { new: false })
.then(async (ris) => {
await OrdersCart.findOneAndUpdate({ _id: order_id }, { $set: fields_to_update }, { new: false }).then(
async (ris) => {
const userDest = await User.findById(myOrdersCart.userId).lean();
if (ris) {
@@ -390,15 +453,14 @@ router.post('/:userId/ordercartstatus', authenticate, async function (req, res,
}
if (ordertype !== '') {
sendemail.sendEmail_Order(userDest.lang, idapp, myOrdersCart, userDest, ordertype, status)
.then((ris) => {
})
sendemail
.sendEmail_Order(userDest.lang, idapp, myOrdersCart, userDest, ordertype, status)
.then((ris) => {});
}
}
}
})
}
);
let orderscart = null;
@@ -410,14 +472,11 @@ router.post('/:userId/ordercartstatus', authenticate, async function (req, res,
}
return res.send({ code: server_constants.RIS_CODE_OK, status, orders: orderscart });
}
} catch (e) {
console.error('err', e);
return res.send({ code: server_constants.RIS_CODE_ERR, status: 0 });
}
});
//POST cart
@@ -428,24 +487,22 @@ router.post('/:userId/gestord', authenticate, async function (req, res, next) {
const { User } = require('../models/user');
try {
let queryord = [];
let queryord = []
let filtroOrdini = []
let filtroOrdini = [];
if (idGasordine) {
const gasordine = {
$match: {
idGasordine: {
$type: "objectId", // Checks if the field is of type ObjectId
$eq: new ObjectId(idGasordine) // Compares the value to a specific ObjectId
}
}
}
queryord.push(gasordine)
$type: 'objectId', // Checks if the field is of type ObjectId
$eq: new ObjectId(idGasordine), // Compares the value to a specific ObjectId
},
},
};
queryord.push(gasordine);
}
const query = [
{
$lookup: {
@@ -506,15 +563,15 @@ router.post('/:userId/gestord', authenticate, async function (req, res, next) {
},
{
$lookup: {
from: "orderscarts",
localField: "_id",
foreignField: "items.order",
as: "matchingOrders",
from: 'orderscarts',
localField: '_id',
foreignField: 'items.order',
as: 'matchingOrders',
},
},
{
$match: {
"matchingOrders": {
matchingOrders: {
$ne: [],
},
},
@@ -539,10 +596,7 @@ router.post('/:userId/gestord', authenticate, async function (req, res, next) {
},
totalQuantity: {
$sum: {
$add: [
'$quantity',
'$quantitypreordered',
],
$add: ['$quantity', '$quantitypreordered'],
},
},
totalPrice_acquistato: {
@@ -550,10 +604,7 @@ router.post('/:userId/gestord', authenticate, async function (req, res, next) {
$multiply: [
'$product.price_acquistato',
{
$add: [
'$quantity',
'$quantitypreordered',
],
$add: ['$quantity', '$quantitypreordered'],
},
],
},
@@ -563,10 +614,7 @@ router.post('/:userId/gestord', authenticate, async function (req, res, next) {
$multiply: [
'$product.price',
{
$add: [
'$quantity',
'$quantitypreordered',
],
$add: ['$quantity', '$quantitypreordered'],
},
],
},
@@ -580,25 +628,22 @@ router.post('/:userId/gestord', authenticate, async function (req, res, next) {
$sort: {
name: 1,
},
}
]
},
];
queryord = [...queryord, ...query]
queryord = [...queryord, ...query];
filtroOrdini = queryord;
const arrout = await Order.aggregate(filtroOrdini);
for (const rec of arrout) {
}
return res.send({ code: server_constants.RIS_CODE_OK, arrout });
} catch (e) {
console.error('Err', e);
}
});
module.exports = router;