Files
freeplanet_serverside/src/server/router/cart_router.js

645 lines
19 KiB
JavaScript
Raw Normal View History

2021-01-18 00:48:17 +01:00
const shared_consts = require('../tools/shared_nodejs');
2020-12-25 03:54:16 +01:00
const express = require('express');
const router = express.Router();
2021-03-30 02:23:38 +02:00
const sendemail = require('../sendemail');
2020-12-25 03:54:16 +01:00
const tools = require('../tools/general');
var server_constants = require('../tools/server_constants');
var { Project } = require('../models/project');
const Scontistica = require('../models/scontistica');
2020-12-25 03:54:16 +01:00
var { authenticate, auth_default } = require('../middleware/authenticate');
const _ = require('lodash');
const Product = require('../models/product');
const Order = require('../models/order');
const Variant = require('../models/variant');
2024-01-03 15:46:42 +01:00
const { User } = require('../models/user');
2020-12-25 03:54:16 +01:00
const { ObjectId } = require('mongodb');
2024-02-13 18:13:26 +01:00
2020-12-25 03:54:16 +01:00
/*const Department = require('../models/Department')
const Category = require('../models/Category')
const TypedError = require('../modules/ErrorHandler')
const paypal_config = require('../configs/paypal-config')
const paypal = require('paypal-rest-sdk')
*/
const CartClass = require('../modules/Cart');
2020-12-25 03:54:16 +01:00
const Cart = require('../models/cart');
2021-01-18 00:48:17 +01:00
const OrdersCart = require('../models/orderscart');
2020-12-25 03:54:16 +01:00
//GET cart
2023-11-30 14:27:37 +01:00
router.get('/:userId', authenticate, async function (req, res, next) {
let userId = req.params.userId;
let idapp = req.user.idapp;
2023-11-30 14:27:37 +01:00
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) => {
2023-11-30 14:27:37 +01:00
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;
mycart = await Cart.getCartCompletoByCartId(mycart._id, idapp);
let newCart = await CartClass.constructByCart(mycart);
if (newCart) return newCart.aggiornaCarrello();
2023-11-30 14:27:37 +01:00
return newCart;
} catch (e) {
console.error('Err AggiornaCarrello', e);
return null;
}
}
2020-12-25 03:54:16 +01:00
//POST cart
router.post('/:userId', authenticate, async function (req, res, next) {
let idapp = req.body.idapp;
let userId = req.params.userId;
let addqty = req.body.addqty;
let subqty = req.body.subqty;
let order = req.body.order;
2023-11-30 14:27:37 +01:00
try {
let mycart = await Cart.getCartByUserId(userId, idapp);
2023-11-30 14:27:37 +01:00
if (!order) {
return res.send({ code: server_constants.RIS_CODE_OK, cart: null });
}
2023-11-30 14:27:37 +01:00
// const myorder = Order.getOrderByID(order._id);
if (!addqty && !subqty && order) {
order._id = await Order.createOrder(order, mycart.codice_sconto);
2023-12-18 12:11:12 +01:00
if (!order._id) {
return res.send({ code: server_constants.RIS_CODE_ERR, cart: 0 });
}
}
2023-11-30 14:27:37 +01:00
let cart = null;
let product = null;
2023-11-30 14:27:37 +01:00
// no cart save empty cart to database then return response
let nuovo = false;
2023-11-30 14:27:37 +01:00
if (!mycart) {
let oldCart = new CartClass(order);
2023-11-30 14:27:37 +01:00
cart = await Cart.createCart(oldCart.generateModel());
mycart = await Cart.getCartByUserId(userId, idapp);
nuovo = true;
}
let newCart = await CartClass.constructByCart(mycart);
2023-12-20 21:52:17 +01:00
// order = await Product.updateProductInOrder(order);
if (!nuovo) {
// Controlla se sto inserendo un prodotto con 2 Negozi, non permetterlo !
if (newCart.isSameStorehouse(order)) {
if (addqty) {
myord = await newCart.addqty(order);
} else if (subqty) {
myord = await newCart.subqty(order);
} else {
const ind = await newCart.addItem(order);
const arrord = await Order.getTotalOrderById(order._id);
myord = arrord ? arrord[0] : null;
}
2023-11-30 14:27:37 +01:00
} else {
return res.send({
code: server_constants.RIS_CODE_ERR,
cart: null,
myord: null,
msgerr: 'Non è possibile acquistare nello stesso ordine, su negozi differenti!',
});
2023-11-30 14:27:37 +01:00
}
} else {
await newCart.updatecarttotals(true);
await newCart.updateExtraOrder();
2023-12-21 01:34:33 +01:00
const arrord = await Order.getTotalOrderById(order._id);
myord = arrord ? arrord[0] : null;
2023-11-30 14:27:37 +01:00
}
cart = await Cart.updateCartByCartId(mycart._id, newCart.generateModel());
2023-11-30 14:27:37 +01:00
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);
2023-12-20 21:52:17 +01:00
return res.send({ code: server_constants.RIS_CODE_OK, cart: carttot, myord, product });
2020-12-25 03:54:16 +01:00
} else {
2023-12-20 21:52:17 +01:00
console.error('Err:', err);
return res.send({ code: server_constants.RIS_CODE_ERR, cart: null, myord: null });
2020-12-25 03:54:16 +01:00
}
2023-11-30 14:27:37 +01:00
} catch (e) {
2023-12-09 11:55:58 +01:00
console.error('Err:', e);
2023-11-30 14:27:37 +01:00
return res.send({ code: server_constants.RIS_CODE_ERR, cart: 0 });
}
});
2020-12-25 03:54:16 +01:00
router.delete('/:userId', authenticate, async function (req, res) {
console.log('DELETE Item');
let idapp = req.query.idapp;
let userId = req.params.userId;
let orderId = req.query.orderId;
const mycart = await Cart.getCartByUserId(userId, idapp);
const ord = await Order.findOne({ _id: orderId });
let idProduct = '';
let product = null;
if (ord) idProduct = ord.idProduct;
2020-12-25 03:54:16 +01:00
// Rimuovere l'Ordine
2023-12-13 19:17:53 +01:00
const recremoved = await Order.deleteOne({ _id: orderId });
2020-12-25 03:54:16 +01:00
if (recremoved) {
// Rimuovere l'id sul Carrello
let newCart = await CartClass.constructByCart(mycart);
await newCart.removeItem(orderId);
2020-12-25 03:54:16 +01:00
let carttot = null;
const cart = await Cart.updateCartByCartId(mycart._id, newCart.generateModel());
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, product });
2020-12-25 03:54:16 +01:00
}
return res.send({ code: server_constants.RIS_CODE_ERR, cart: null });
});
//PUT cart
2023-11-30 14:27:37 +01:00
router.put('/:userId', authenticate, async function (req, res, next) {
let userId = req.params.userId;
let requestProduct = req.body;
let { productId, color, size } = requestProduct.product;
2020-12-25 03:54:16 +01:00
2023-11-30 14:27:37 +01:00
try {
try {
const cart = await Cart.getCartByUserId(userId);
try {
const myprod = await Product.getProductByID(productId);
2023-11-30 14:27:37 +01:00
let newCart = oldCart.add(myprod, productId, { color, size });
2023-11-30 14:27:37 +01:00
//exist cart in databse
if (cart.length > 0) {
try {
const result = await Cart.updateCartByUserId(userId, {
2023-11-30 14:27:37 +01:00
items: newCart.items,
totalQty: newCart.totalQty,
totalPrice: newCart.totalPrice,
totalPriceCalc: newCart.totalPriceCalc,
totalPriceIntero: newCart.totalPriceIntero,
userId: userId,
});
res.json(result);
} catch (err) {
return next(err);
}
2023-11-30 14:27:37 +01:00
} else {
//no cart in database
let newCartobj = {
2020-12-25 03:54:16 +01:00
items: newCart.items,
totalQty: newCart.totalQty,
totalPrice: newCart.totalPrice,
totalPriceCalc: newCart.totalPriceCalc,
totalPriceIntero: newCart.totalPriceIntero,
userId: userId,
};
try {
const resultCart = await Cart.createCart(newCartobj);
} catch (err) {
return next(err);
}
res.status(201).json(resultCart);
2023-11-30 14:27:37 +01:00
}
} catch (err) {
return next(err);
}
const product = await Product.getProductById(productId);
return res.send({ code: server_constants.RIS_CODE_OK, product });
} catch (err) {
return next(err);
}
let oldCart = new CartClass(c || {});
2023-11-30 14:27:37 +01:00
} catch (e) {
return res.send({ code: server_constants.RIS_CODE_ERR, status: 0 });
}
});
2023-11-30 14:27:37 +01:00
router.post('/:userId/app_sc', authenticate, async function (req, res, next) {
2021-01-18 00:48:17 +01:00
let idapp = req.body.idapp;
let cart_id = req.body.cart_id;
2023-12-13 19:17:53 +01:00
let userId = req.params.userId;
let codice_sconto = req.body.code;
2024-01-02 15:24:44 +01:00
let options = req.body.options;
2021-01-18 00:48:17 +01:00
let mycart = null;
let valido = false;
let errmsg = '';
let recscontisticaTrovata = null;
2021-01-18 00:48:17 +01:00
try {
let mycart = await Cart.getCartCompletoByCartId(cart_id, idapp);
// let mycart = await Cart.findOne({ _id: cart_id }).lean();
2023-12-13 19:17:53 +01:00
if (codice_sconto === 'RIMUOVI') {
mycart = await Cart.findOneAndUpdate({ _id: cart_id }, { $set: { codice_sconto: '' } }, { new: true }).lean();
mycart = await aggiornaCarrello(mycart, userId, idapp);
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 recscontisticheTrovate = await CartClass.getRecSconto(idapp, codice_sconto, true);
if (recscontisticheTrovate && recscontisticheTrovate.length > 0) {
recscontisticaTrovata = recscontisticheTrovate[0];
}
if (recscontisticaTrovata) {
if (mycart.codice_sconto !== codice_sconto) {
mycart.codice_sconto = codice_sconto;
mycart.descr_sconto = recscontisticaTrovata.description;
await Cart.updateOne({ _id: cart_id }, { $set: { codice_sconto, descr_sconto: mycart.descr_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: recscontisticaTrovata });
} 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,
totalPriceIntero: cart.totalPriceIntero,
note_ordine_gas: cart.note_ordine_gas,
userId,
status,
note,
codice_sconto: cart.codice_sconto,
descr_sconto: cart.descr_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) {
try {
const { idapp, cart_id, status, note, options } = req.body;
const userId = req.params.userId;
// console.log('createorderscart', cart_id);
const mycart = await getCartById(cart_id);
if (!mycart) {
return res.send({
code: server_constants.RIS_CODE_OK,
status: 0,
recOrderCart: null,
});
}
2023-12-13 19:17:53 +01:00
let myorderCart = await createOrUpdateOrderFromCart({ idapp, cart: mycart, userId, status, note });
let statusOrderCart = myorderCart.status;
2024-01-04 15:43:13 +01:00
const userDest = await User.findById(userId).lean();
if (status === shared_consts.OrderStatus.CHECKOUT_SENT) {
try {
const checkoutResult = await handleCheckout({
myorderCart,
mycart,
userId,
idapp,
req,
options,
userDest,
});
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 });
2021-01-18 00:48:17 +01:00
}
}
// console.log('SEND OK', statusOrderCart);
2023-12-13 19:17:53 +01:00
return res.send({
code: server_constants.RIS_CODE_OK,
status: statusOrderCart,
recOrderCart: myorderCart,
2023-12-13 19:17:53 +01:00
});
} catch (e) {
console.error('Errore generale:', e);
2023-12-13 19:17:53 +01:00
return res.send({ code: server_constants.RIS_CODE_ERR, status: 0, recOrderCart: null });
}
});
//POST cart
2023-12-13 19:17:53 +01:00
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;
let status = req.body.status;
2024-01-02 15:24:44 +01:00
let options = req.body.options;
2023-12-14 15:20:21 +01:00
const { User } = require('../models/user');
2024-01-15 22:46:38 +01:00
let myOrdersCart = await OrdersCart.findOne({ idapp, _id: order_id }).lean();
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 {
2024-01-15 22:46:38 +01:00
if (!!myOrdersCart) {
let fields_to_update = { status };
await OrdersCart.findOneAndUpdate({ _id: order_id }, { $set: fields_to_update }, { new: false }).then(
async (ris) => {
2024-01-15 22:46:38 +01:00
const userDest = await User.findById(myOrdersCart.userId).lean();
if (ris) {
let ordertype = '';
2023-12-13 19:17:53 +01:00
// Aggiorna gli Stati Interni !
2024-01-15 22:46:38 +01:00
myOrdersCart = await OrdersCart.updateCmd(myOrdersCart, status, true, options);
if ((options.hasOwnProperty('sendmail') && options.sendmail) || !options.hasOwnProperty('sendmail')) {
if (status === shared_consts.OrderStatus.ORDER_CONFIRMED) {
ordertype = 'order_confirmed';
} else if (status === shared_consts.OrderStatus.DELIVERED) {
ordertype = 'order_consegnato';
} else if (status === shared_consts.OrderStatus.CANCELED) {
ordertype = 'order_canceled';
}
if (ordertype !== '') {
sendemail
.sendEmail_Order(userDest.lang, idapp, myOrdersCart, userDest, ordertype, status)
.then((ris) => {});
}
}
}
}
);
2024-02-13 18:13:26 +01:00
2023-12-14 15:20:21 +01:00
let orderscart = null;
if (User.isManager(req.user.perm)) {
2023-12-14 15:20:21 +01:00
// Prende Tutti gli Ordini !
2023-12-20 21:52:17 +01:00
orderscart = await OrdersCart.getOrdersCartByUserId('ALL', idapp, 0, false);
2023-12-14 15:20:21 +01:00
} else {
2023-12-20 21:52:17 +01:00
orderscart = await OrdersCart.getOrdersCartByUserId(req.user.id, idapp, 0, false);
2023-12-14 15:20:21 +01:00
}
2023-12-14 15:20:21 +01:00
return res.send({ code: server_constants.RIS_CODE_OK, status, orders: orderscart });
2021-01-18 00:48:17 +01:00
}
} catch (e) {
2024-01-15 22:46:38 +01:00
console.error('err', e);
2021-01-18 00:48:17 +01:00
return res.send({ code: server_constants.RIS_CODE_ERR, status: 0 });
}
});
2020-12-25 03:54:16 +01:00
2024-02-13 18:13:26 +01:00
//POST cart
router.post('/:userId/gestord', authenticate, async function (req, res, next) {
let idapp = req.body.idapp;
let idGasordine = req.body.idGasordine;
const { User } = require('../models/user');
try {
let queryord = [];
2024-02-13 18:13:26 +01:00
let filtroOrdini = [];
2024-02-13 18:13:26 +01:00
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);
2024-02-13 18:13:26 +01:00
}
const query = [
{
$lookup: {
from: 'products',
localField: 'idProduct',
foreignField: '_id',
as: 'product',
},
},
{
$unwind: {
path: '$product',
preserveNullAndEmptyArrays: true,
},
},
{
$lookup: {
from: 'gasordines',
localField: 'idGasordine',
foreignField: '_id',
as: 'gasordine',
},
},
{
$unwind: {
path: '$gasordine',
preserveNullAndEmptyArrays: true,
},
},
{
$match: {
$or: [
{
quantity: {
$gt: 0,
},
},
{
quantitypreordered: {
$gt: 0,
},
},
],
},
},
2024-02-15 18:58:58 +01:00
{
$lookup: {
from: 'orderscarts',
localField: '_id',
foreignField: 'items.order',
as: 'matchingOrders',
2024-02-15 18:58:58 +01:00
},
},
{
$match: {
matchingOrders: {
2024-02-15 18:58:58 +01:00
$ne: [],
},
},
},
2024-02-13 18:13:26 +01:00
{
$group: {
_id: '$product._id',
name: {
2025-08-29 23:34:08 +02:00
$first: '$product.productInfo.name',
2024-02-13 18:13:26 +01:00
},
weight: {
2025-08-29 23:34:08 +02:00
$first: '$product.productInfo.weight',
2024-02-13 18:13:26 +01:00
},
unit: {
2025-08-29 23:34:08 +02:00
$first: '$product.productInfo.unit',
2024-02-13 18:13:26 +01:00
},
price_acquistato: {
$first: '$product.price_acquistato',
},
price: {
$first: '$product.price',
},
totalQuantity: {
$sum: {
$add: ['$quantity', '$quantitypreordered'],
2024-02-13 18:13:26 +01:00
},
},
totalPrice_acquistato: {
$sum: {
$multiply: [
'$product.price_acquistato',
{
$add: ['$quantity', '$quantitypreordered'],
2024-02-13 18:13:26 +01:00
},
],
},
},
totalPrice: {
$sum: {
$multiply: [
'$product.price',
{
$add: ['$quantity', '$quantitypreordered'],
2024-02-13 18:13:26 +01:00
},
],
},
},
count: {
$sum: 1,
},
},
},
{
$sort: {
name: 1,
},
},
];
2024-02-13 18:13:26 +01:00
queryord = [...queryord, ...query];
2024-02-13 18:13:26 +01:00
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);
}
});
2020-12-25 03:54:16 +01:00
module.exports = router;