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

424 lines
13 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 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;
}
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 = 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 {
await newCart.updatetotals();
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
/*
Cart.updateCartByUserId(
userId,
newCart,
function (err, result) {
if (err) return next(err)
return res.status(200).json({ cart: result })
})
*/
} 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);
newCart.removeItem(orderId);
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
await Cart.getCartByUserId(userId, async function (err, c) {
2023-11-30 14:27:37 +01:00
if (err) return next(err)
let oldCart = new CartClass(c || {})
2023-11-30 14:27:37 +01:00
await Product.getProductByID(productId, async function (err, p) {
2023-11-30 14:27:37 +01:00
if (err) return next(err)
let newCart = oldCart.add(p, productId, { color, size })
//exist cart in databse
if (c.length > 0) {
await Cart.updateCartByUserId(
2023-11-30 14:27:37 +01:00
userId,
{
items: newCart.items,
totalQty: newCart.totalQty,
totalPrice: newCart.totalPrice,
userId: userId
},
function (err, result) {
if (err) return next(err)
res.json(result)
})
} else {
//no cart in database
let newCartobj = {
2020-12-25 03:54:16 +01:00
items: newCart.items,
totalQty: newCart.totalQty,
totalPrice: newCart.totalPrice,
userId: userId
}
await Cart.createCart(newCartobj, function (err, resultCart) {
2020-12-25 03:54:16 +01:00
if (err) return next(err)
2023-11-30 14:27:37 +01:00
res.status(201).json(resultCart)
2020-12-25 03:54:16 +01:00
})
2023-11-30 14:27:37 +01:00
}
})
2020-12-25 03:54:16 +01:00
})
2023-11-30 14:27:37 +01:00
const product = await Product.getProductById(productId);
return res.send({ code: server_constants.RIS_CODE_OK, product });
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-03-30 02:23:38 +02:00
const user = req.user;
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 {
2023-12-18 12:11:12 +01:00
let mycart = await Cart.findOne({ _id: cart_id });
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,
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
// Porta tutto il Cart nell'Ordine e lo CREO
return await OrdersCart.updateOrdersCartById(-1, myorderCart, async function (err, ris) {
2021-01-18 00:48:17 +01:00
//if (err) return next(err)
if (err)
return res.send({ code: server_constants.RIS_CODE_ERR, status: 0 });
else {
2023-12-12 15:42:41 +01:00
2024-01-02 15:24:44 +01:00
await Order.updateStatusOrders(mycart.items, status);
2023-12-12 15:42:41 +01:00
2021-01-18 00:48:17 +01:00
const myris = ris;
// Cancella il Cart appena salvato in OrdersCart
2021-03-30 02:23:38 +02:00
return Cart.deleteCartByCartId(mycart._id)
2021-01-18 00:48:17 +01:00
.then((ris) => {
2021-03-30 02:23:38 +02:00
2023-12-13 19:17:53 +01:00
return OrdersCart.getOrdersCartByUserId(userId, idapp, numorder)
2024-01-02 15:24:44 +01:00
.then(async (orders) => {
2021-03-30 02:23:38 +02:00
if (!!orders) {
2023-12-13 19:17:53 +01:00
2024-01-02 15:24:44 +01:00
await OrdersCart.updateCmd(orders[0], status, true, req, options);
2023-12-13 19:17:53 +01:00
// Invia la email dell'Ordine
2024-01-03 15:46:42 +01:00
sendemail.sendEmail_OrderProduct(userDest.lang, idapp, orders[0], userDest)
2023-12-13 19:17:53 +01:00
.then(async (ris) => {
myorderCart = await OrdersCart.findById(idordercart).lean();
2021-03-30 02:23:38 +02:00
return res.send({
code: server_constants.RIS_CODE_OK,
status: myris.status,
2023-12-13 19:17:53 +01:00
orders: orders,
recOrderCart: myorderCart
2021-03-30 02:23:38 +02:00
});
});
}
2021-01-18 00:48:17 +01:00
});
})
}
})
2023-12-21 01:34:33 +01:00
} else if (status < shared_consts.OrderStatus.CHECKOUT_SENT) {
// Aggiorna il carrello !
/*const cartpao = await Cart.getCartByUserId(userId, idapp);
let newCart = CartClass.constructByCart(cartpao);
if (newCart)
await newCart.updatetotals();
newCart;*/
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;
const user = req.user;
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
2023-12-14 15:20:21 +01:00
let orderCart = 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 {
if (!!orderCart) {
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-04 15:43:13 +01:00
const userDest = await User.findById(orderCart.userId).lean();
if (ris) {
2023-12-13 19:17:53 +01:00
// Aggiorna gli Stati Interni !
2024-01-02 15:24:44 +01:00
orderCart = await OrdersCart.updateCmd(orderCart, status, true, options);
2023-12-13 19:17:53 +01:00
let ordertype = '';
if (status === shared_consts.OrderStatus.ORDER_CONFIRMED) {
ordertype = 'order_confirmed';
2023-12-29 21:17:17 +01:00
} else if (status === shared_consts.OrderStatus.DELIVERED) {
ordertype = 'order_consegnato';
} else if (status === shared_consts.OrderStatus.CANCELED) {
ordertype = 'order_canceled';
}
if (ordertype !== '') {
2024-01-03 15:46:42 +01:00
sendemail.sendEmail_Order(userDest.lang, idapp, orderCart, userDest, ordertype, status)
.then((ris) => {
})
}
}
})
2023-12-14 15:20:21 +01:00
let orderscart = null;
if (User.isManager(user.perm)) {
// 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) {
return res.send({ code: server_constants.RIS_CODE_ERR, status: 0 });
}
});
2020-12-25 03:54:16 +01:00
module.exports = router;