gpt-4o-mini-2024-07-18· OpenAI
WildChat-4.8M (AI2)
Description: in this code the stock should reduce according to the current order const…
- User
Description: in this code the stock should reduce according to the current order
const express = require('express'); const mongoose = require('mongoose'); const Order = require('../models/Order'); const User = require('../models/User'); const Product = require('../models/Product');
const placeOrder = async (req, res) => { try { const { orderItems, discount } = req.body; const userId = req.user.id;
codeif (!Array.isArray(orderItems) || orderItems.length === 0) { return res.status(400).send('Order items must be an array of Product IDs.'); } // Validate all orderItems are valid mongoose ids for (const item of orderItems) { if (!mongoose.Types.ObjectId.isValid(item)) { return res.status(400).send('Invalid Product ID: ' + item); } } // Find user and get address and phone number const user = await User.findById(userId); if (!user) { return res.status(404).send('User not found.'); } const orderAddress = user.address; // assume address field exists in User schema const phoneNumber = user.phone; // assume phone field exists in User schema // Calculate total price and total quantity let totalPrice = 0; let totalItemsCount = 0; for (const itemId of orderItems) { const product = await Product.findById(itemId); if (!product) { return res.status(404).send('Product not found: ' + itemId); } if (product.stock <= 0) { return res.status(400).send('Product is out of stock: ' + product.name); } totalPrice += product.price; totalItemsCount++; } // Apply discount let discountValue = 0; if (discount) { if (typeof discount === 'string' && discount.endsWith('%')) { const percentage = parseFloat(discount.slice(0, -1)); discountValue = (totalPrice * percentage) / 100; } else { discountValue = parseFloat(discount); } } totalPrice -= discountValue; // Create order const order = new Order({ userId, orderItems, orderAddress, phoneNumber, price: totalPrice, totalItemsCount, discount: discountValue }); const savedOrder = await order.save(); return res.status(201).json(savedOrder); } catch (error) { console.error(error); return res.status(500).send('Internal server error.'); } - Assistant