diff --git a/resources/PD_Orders/pdOrderController.js b/resources/PD_Orders/pdOrderController.js index 93b93a6..d97e941 100644 --- a/resources/PD_Orders/pdOrderController.js +++ b/resources/PD_Orders/pdOrderController.js @@ -1371,7 +1371,7 @@ export const getAllOrdersByDistributor = async (req, res) => { const page = parseInt(req.query.page, 10) || 1; const limit = parseInt(req.query.limit, 10) || 5; const skip = (page - 1) * limit; - +// console.log(distributorId, orderId, status, page, limit, skip); try { let orders; @@ -1396,9 +1396,9 @@ export const getAllOrdersByDistributor = async (req, res) => { // Get total count for pagination const totalOrders = await PdOrder.countDocuments({ addedBy: distributorId, - status: { $regex: id }, + uniqueId: { $regex: id }, }); - + // console.log(totalOrders); // Send response with pagination info return res.status(200).json({ totalOrders, diff --git a/resources/RD_Ordes/rdOrderController.js b/resources/RD_Ordes/rdOrderController.js index f1e2498..e113748 100644 --- a/resources/RD_Ordes/rdOrderController.js +++ b/resources/RD_Ordes/rdOrderController.js @@ -1,7 +1,9 @@ +import mongoose from "mongoose"; import sendEmail from "../../Utils/sendEmail.js"; import RetailDistributor from "../RetailDistributor/RetailDistributorModel.js"; import { InvoiceRd } from "./invoiceModalRD.js"; import { RdOrder } from "./rdOrderModal.js"; +import { PDStock } from "../Stock/PdStockModel.js"; // Controller to create a new order by RD export const createOrderRD = async (req, res) => { @@ -134,7 +136,31 @@ export const getSinglePlacedOrderForRD = async (req, res) => { res.status(500).json({ message: "Server error", error }); } }; +export const getPlacedOrderById = async (req, res) => { + try { + const id = req.params.id; + if (!mongoose.Types.ObjectId.isValid(id)) { + return res + .status(404) + .json({ return_msg: "Not Valid id to search the doc " }); + } + const doc = await RdOrder.findById(id) + .populate({ + path: "orderItem.productId", + }) + .populate({ path: "invoices" }); + if (doc) { + return res + .status(200) + .json({ singleOrder: doc, return_msg: "Doc found" }); + } + return res.status(404).json({ return_msg: "Not Found doc " }); + } catch (error) { + console.log(error); + return res.status(500).json({ return_msg: "Internal Server Error" }); + } +}; export const getPlacedOrdersForPD = async (req, res) => { try { const pdId = req.user?._id; @@ -317,24 +343,26 @@ export const processOrder = async (req, res) => { // Find the order by ID const order = await RdOrder.findById(orderId).populate("addedBy"); - if (!order) { return res.status(404).json({ error: "Order not found" }); } // Validate quantities - const exceededItems = []; + const exceededItems = invoiceItems + .filter((item) => { + const orderItem = order.orderItem.find( + (i) => i.productId.toString() === item.productId.toString() + ); + return orderItem && item.processquantity > orderItem.remainingQuantity; + }) + .map((item) => item.name); - // Check each item in invoiceItems for quantity limits - for (const item of invoiceItems) { - const orderItem = order.orderItem.find( - (i) => i.productId.toString() === item.productId.toString() - ); - - // If processquantity exceeds remainingQuantity, add the item name to exceededItems - if (orderItem && item.processquantity > orderItem.remainingQuantity) { - exceededItems.push(item.name); - } + if (exceededItems.length > 0) { + return res.status(400).json({ + error: `The following items have more quantity than remaining in the order: ${exceededItems.join( + ", " + )}`, + }); } // If there are any exceeded items, return an error with their names @@ -347,18 +375,54 @@ export const processOrder = async (req, res) => { } // Continue with the rest of the logic if no quantity limits are exceeded + // Stock calculation part + const pdStock = await PDStock.findOne({ userId: order.pd }); + if (!pdStock) { + return res.status(404).json({ error: "Stock not available" }); + } + // Update stock and validate + const updatedInvoiceItems = invoiceItems.filter((item) => { + // Find the product in the stock + const productInStock = pdStock.products.find( + (p) => p.productid.toString() === item.productId.toString() + ); + + // If the product exists in stock + if (productInStock) { + // Check if the processquantity is less than or equal to available stock + if (item.processquantity <= productInStock.Stock) { + // Deduct the quantity from the stock + productInStock.Stock -= item.processquantity; + // Add the item to updatedInvoiceItems (since stock is sufficient) + return true; + } + } + + // If no stock or insufficient stock, don't add the item + return false; + }); + + // If no items are left after stock validation, return an error + if (updatedInvoiceItems.length === 0) { + return res + .status(400) + .json({ error: "No stock available for the requested items." }); + } + + // Save updated stock + await pdStock.save(); // Generate unique invoice number const existingInvoices = await InvoiceRd.find({ orderId }); const invoiceNumber = existingInvoices.length + 1; - const invoiceId = `ch/${order.uniqueId}/${invoiceItems.length}/${invoiceNumber}`; + const invoiceId = `ch/${order.uniqueId}/${updatedInvoiceItems.length}/${invoiceNumber}`; // Calculate subtotal, gstTotal, and invoiceAmount for processed items let subtotal = 0; let gstTotal = 0; let invoiceAmount = 0; - invoiceItems.forEach((item) => { + updatedInvoiceItems.forEach((item) => { const itemSubtotal = item.price * item.processquantity; const itemGST = ((item.price * item.GST) / 100) * item.processquantity; @@ -371,7 +435,7 @@ export const processOrder = async (req, res) => { const newInvoice = new InvoiceRd({ invoiceId, orderId, - items: invoiceItems, + items: updatedInvoiceItems, subtotal, gstTotal, invoiceAmount, @@ -379,12 +443,11 @@ export const processOrder = async (req, res) => { // Save the invoice const savedInvoice = await newInvoice.save(); - // Update the order's order items with the remaining quantity let allItemsProcessed = true; // Flag to check if all items are processed order.orderItem.forEach((item) => { - const invoicedItem = invoiceItems.find( + const invoicedItem = updatedInvoiceItems.find( (i) => i.productId.toString() === item.productId.toString() ); @@ -430,7 +493,7 @@ export const processOrder = async (req, res) => { await order.save(); // Prepare the email content - const processedItems = invoiceItems + const processedItems = updatedInvoiceItems .map( (item, index) => `