import { POSOrder } from "./PosorderModel.js"; import { shippingAddress } from "../ShippingAddresses/ShippingAddressModel.js"; //generate unique order id const generateOrderId = async () => { const currentYear = new Date().getFullYear(); // Find the latest order to get the last serial number const latestOrder = await POSOrder.findOne({}, {}, { sort: { orderID: -1 } }); let serialNumber = 1; if (latestOrder) { const lastYear = parseInt(latestOrder.orderID.substring(0, 4), 10); if (lastYear === currentYear) { // If the last order was in the current year, increment the serial number serialNumber = parseInt(latestOrder.orderID.substring(4), 10) + 1; } } // Pad the serial number with zeros and concatenate with the current year const paddedSerialNumber = serialNumber.toString().padStart(7, "0"); const orderId = `${currentYear}${paddedSerialNumber}`; return orderId; }; export const createOrderCheckout = async (req, res) => { try { const { address, cart, user, SalesType, paymentMode } = req.body; // console.log(req.body) // Perform validation if (!address || !cart || cart.length === 0 || !SalesType || !user || !paymentMode) { return res.status(400).json({ message: "Invalid order data" }); } // Retrieve shipping address from database const shippingInfo = await shippingAddress.findById(address); if (!shippingInfo) { return res.status(404).json({ message: "Shipping address not found" }); } // Ensure that addressId is included in the shippingInfo object const { _id: addressId, ...restOfShippingInfo } = shippingInfo.toObject(); // Calculate total amount based on the product_Subtotal of each product const totalAmount = cart.reduce( (acc, item) => acc + item.product_Subtotal, 0 ); // Construct order items array const orderItems = cart.map((item) => ({ product: item.product, name: item.name, price: item.price, quantity: item.quantity, product_Subtotal: item.total_amount, gst_amount: item.gst_amount, image: item.image, variant_Name: item.variant_Name, })); // Generate a unique order ID const orderId = await generateOrderId(); // Create the order document const order = await POSOrder.create({ orderID: orderId, total_amount: totalAmount, orderItems, shippingInfo: { addressId: addressId, // Include the addressId ...restOfShippingInfo, // Include other shipping information }, user, // Assuming you have authenticated users SalesType, paymentMode, }); return res.status(201).json({ success: true, order }); } catch (error) { console.error("Error creating order:", error); return res .status(500) .json({ success: false, message: "Internal server error" }); } };