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

605 lines
16 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');
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')
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
return await Cart.getCartByUserId(userId, idapp)
.then((cart) => {
if (cart)
return res.send({ code: server_constants.RIS_CODE_OK, cart });
else
2023-12-12 15:42:41 +01:00
return res.send({ code: server_constants.RIS_CODE_OK, cart: null });
2023-11-30 14:27:37 +01:00
}).catch((err) => {
console.error('Err', err);
return res.send({ code: server_constants.RIS_CODE_ERR, cart: 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) {
2023-11-30 14:27:37 +01:00
order._id = await Order.createOrder(order);
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)
cart = await Cart.createCart(oldCart.generateModel());
mycart = await Cart.getCartByUserId(userId, idapp);
nuovo = true;
}
2024-02-13 18:13:26 +01:00
let newCart = 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 {
2024-01-02 15:24:44 +01:00
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 {
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 = 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);
}
2020-12-25 03:54:16 +01:00
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) {
2020-12-25 03:54:16 +01:00
let userId = req.params.userId
let requestProduct = req.body
let { productId, color, size } = requestProduct.product
2023-11-30 14:27:37 +01:00
try {
2020-12-25 03:54:16 +01:00
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,
2023-11-30 14:27:37 +01:00
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,
2020-12-25 03:54:16 +01:00
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 });
}
2020-12-25 03:54:16 +01:00
})
2021-01-18 00:48:17 +01:00
//POST cart
2023-12-13 19:17:53 +01:00
router.post('/:userId/createorderscart', 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;
2021-01-18 00:48:17 +01:00
let status = req.body.status;
let note = req.body.note;
2024-01-02 15:24:44 +01:00
let options = req.body.options;
2021-01-18 00:48:17 +01:00
try {
let mycart = await Cart.findOne({ _id: cart_id }).lean();
2023-12-13 19:17:53 +01:00
if (!mycart) {
return res.send({
code: server_constants.RIS_CODE_OK,
status: 0,
recOrderCart: null,
});
}
2023-12-13 19:17:53 +01:00
2023-12-15 23:36:43 +01:00
let numorder = await OrdersCart.getLastNumOrder(idapp);
let numord_pers = await OrdersCart.getLastNumOrdPers(userId, idapp);
2023-12-13 19:17:53 +01:00
// Esiste l'ordine ?
let myorderCart = await OrdersCart.getRecCartByUserId(userId, idapp, numorder);
if (!myorderCart) {
// crea il nuovo numero d'ordine
numorder++;
2023-12-15 23:36:43 +01:00
numord_pers++;
2023-12-13 19:17:53 +01:00
// 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,
2023-12-13 19:17:53 +01:00
userId,
status,
note,
2023-12-13 19:17:53 +01:00
numorder,
2023-12-15 23:36:43 +01:00
numord_pers,
2023-12-13 19:17:53 +01:00
created_at: new Date(),
modify_at: new Date(),
})
}
statusOrderCart = myorderCart.status;
const idordercart = myorderCart._id;
2024-01-04 15:43:13 +01:00
const userDest = await User.findById(userId).lean();
2021-01-18 00:48:17 +01:00
if (!!mycart) {
2021-03-30 02:23:38 +02:00
if (status === shared_consts.OrderStatus.CHECKOUT_SENT) {
2023-12-13 19:17:53 +01:00
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
});
2021-03-30 02:23:38 +02:00
});
}
}
});
})
2023-12-21 01:34:33 +01:00
} catch (err) {
console.error("Errore durante l'aggiornamento dell'ordine:", err);
return res.send({ code: server_constants.RIS_CODE_ERR, status: 0 });
}
2021-01-18 00:48:17 +01:00
}
2021-03-30 02:23:38 +02:00
}
2023-12-13 19:17:53 +01:00
return res.send({
code: server_constants.RIS_CODE_OK,
status: statusOrderCart,
recOrderCart: myorderCart
});
} catch (e) {
2023-12-18 12:11:12 +01:00
console.error('Err', 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-03 15:46:42 +01:00
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 })
2023-12-13 19:17:53 +01:00
.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 = []
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
2024-02-13 18:13:26 +01:00
}
}
}
queryord.push(gasordine)
}
const query = [
{
$lookup: {
from: 'products',
localField: 'idProduct',
foreignField: '_id',
as: 'product',
},
},
{
$unwind: {
path: '$product',
preserveNullAndEmptyArrays: true,
},
},
{
$lookup: {
from: 'productinfos',
localField: 'product.idProductInfo',
foreignField: '_id',
as: 'productInfo',
},
},
{
$unwind: {
path: '$productInfo',
},
},
{
$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",
},
},
{
$match: {
"matchingOrders": {
$ne: [],
},
},
},
2024-02-13 18:13:26 +01:00
{
$group: {
_id: '$product._id',
name: {
$first: '$productInfo.name',
},
weight: {
$first: '$productInfo.weight',
},
unit: {
$first: '$productInfo.unit',
},
price_acquistato: {
$first: '$product.price_acquistato',
},
price: {
$first: '$product.price',
},
totalQuantity: {
$sum: {
$add: [
'$quantity',
'$quantitypreordered',
],
},
},
totalPrice_acquistato: {
$sum: {
$multiply: [
'$product.price_acquistato',
{
$add: [
'$quantity',
'$quantitypreordered',
],
},
],
},
},
totalPrice: {
$sum: {
$multiply: [
'$product.price',
{
$add: [
'$quantity',
'$quantitypreordered',
],
},
],
},
},
count: {
$sum: 1,
},
},
},
{
$sort: {
name: 1,
},
}
]
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);
}
});
2020-12-25 03:54:16 +01:00
module.exports = router;