Untitled
unknown
plain_text
10 months ago
3.2 kB
4
Indexable
exports.AddOrder = catchAsync(async (req, res, next) => { const { productDetails, billingDetails, userId } = req.body; const session = await mongoose.startSession(); try { session.startTransaction(); let total = 0; const user = await checkUser(userId, next); // await checkProductDetails(productDetails,session,next); if (!Array.isArray(productDetails)) { return next(new AppError('products Details not array', 400)); } if (productDetails.length < 1) { return next(new AppError('no products in this order', 400)); } for (const prod of productDetails) { const product = await Product.findById(toObjectId(prod.product, next)); if (!product) { return next(new AppError('Product not found', 400)); } if (prod.quantity < 1) { return next(new AppError('invalid Quantity value', 400)); } if (product.quantity < prod.quantity) { return next(new AppError('Quantity for this Product not found', 400)); } product.quantity = product.quantity - prod.quantity; prod.initialPrice = product.pricing.initialPrice; if (user.role == 'client') { prod.price = product.pricing.publicPrice; }else if (user.role == 'retailer') { const retailer = await Retailer.findById({_id : user.profile}).select('pricingType'); prod.price = product.pricing.discountPrices[retailer.pricingType-1] }else{ return next(new AppError("this user isn't client or retailer", 400)); } if(product.offer){ const offer = await Offer.findById(product.offer) prod.price = Number.parseFloat(prod.price * (1-(offer.discount/100))).toFixed(2) } total += prod.price * prod.quantity; await product.save({ session: session }); } await checkbillingDetails(billingDetails, next); const order = await Order.create( [{ products: productDetails, cart_address: billingDetails, totalPrice: Number.parseFloat(total).toFixed(2), ordered_by: user._id }], { session } ); if (user.role == 'client') { await Client.updateOne({ _id: user.profile }, { $push: { orders: order[0]._id } }, { session }); } else if (user.role == 'retailer') { await Retailer.updateOne({ _id: user.profile }, { $push: { orders: order[0]._id } }, { session }); } const users = await User.find({ $or :[{role:'manager'},{role:'admin'}]}); const usersIds = [] for(let i=0;i<users.length;i++){ const notification = await Notification.create([{content:'new order', type:'order'}],{ session }) await User.updateOne({_id : users[i]._id},{ $push: { notifications: notification[0]._id } }, { session }) usersIds.push({id :users[i]._id.toString(),data: notification}) } Socket.SocketConnectedList(usersIds) await session.commitTransaction(); session.endSession(); res.status(200).json({ message: 'Order added successfully', order: order }); } catch (error) { await session.abortTransaction(); session.endSession(); return next(error); } });
Editor is loading...
Leave a Comment