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 365ca69..6e6489b 100644 --- a/resources/RD_Ordes/rdOrderController.js +++ b/resources/RD_Ordes/rdOrderController.js @@ -1,3 +1,4 @@ +import mongoose from "mongoose"; import sendEmail from "../../Utils/sendEmail.js"; import RetailDistributor from "../RetailDistributor/RetailDistributorModel.js"; import { InvoiceRd } from "./invoiceModalRD.js"; @@ -135,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; @@ -318,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 @@ -348,18 +375,55 @@ 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; @@ -372,7 +436,7 @@ export const processOrder = async (req, res) => { const newInvoice = new InvoiceRd({ invoiceId, orderId, - items: invoiceItems, + items: updatedInvoiceItems, subtotal, gstTotal, invoiceAmount, @@ -380,34 +444,11 @@ export const processOrder = async (req, res) => { // Save the invoice const savedInvoice = await newInvoice.save(); - // Stock calculation part - const pdStock = await PDStock.findOne({ userId: order.addedBy._id }); - if (!pdStock) { - return res.status(404).json({ error: "PD Stock for the user not found" }); - } - - // Update the stock for each product in the invoice - invoiceItems.forEach((item) => { - const productInStock = pdStock.products.find( - (p) => p.productid.toString() === item.productId.toString() - ); - - if (productInStock) { - productInStock.Stock -= item.processquantity; - // console.log(productInStock.Stock); - if (productInStock.Stock < 0) { - productInStock.Stock = 0; // Prevent stock from going negative - } - } - }); - - // Save the updated PD Stock - await pdStock.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() ); @@ -453,7 +494,7 @@ export const processOrder = async (req, res) => { await order.save(); // Prepare the email content - const processedItems = invoiceItems + const processedItems = updatedInvoiceItems .map( (item, index) => ` @@ -486,7 +527,6 @@ export const processOrder = async (req, res) => { ` ) .join(""); - const pendingItems = order.orderItem .filter((item) => item.remainingQuantity > 0) .map( @@ -521,7 +561,6 @@ export const processOrder = async (req, res) => { ` ) .join(""); - // Dynamic email subject and message based on the order status const emailSubject = allItemsProcessed ? `Your Order #${order.uniqueId} is in Processing!` @@ -855,3 +894,115 @@ export const cancelOrderController = async (req, res) => { .json({ message: "An error occurred while cancelling the order" }); } }; + +export const getAllOrdersByDistributor = async (req, res) => { + const { distributorId } = req.params; + const { orderId, status } = req.query; // Added status to query parameters + // console.log(distributorId, orderId, status); + + // Handle pagination parameters + 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; + + // Search by orderId + if (orderId) { + const id = new RegExp(orderId, "i"); + orders = await RdOrder.find({ + addedBy: distributorId, + uniqueId: { $regex: id }, + }) + .sort({ createdAt: -1 }) + .skip(skip) + .limit(limit); + + // console.log(orders); + + // Return empty array if no orders are found + if (!orders || orders.length === 0) { + return res.status(200).json([]); + } + + // Get total count for pagination + const totalOrders = await RdOrder.countDocuments({ + addedBy: distributorId, + uniqueId: { $regex: id }, + }); + + // Send response with pagination info + return res.status(200).json({ + totalOrders, + totalPages: Math.ceil(totalOrders / limit), + currentPage: page, + orders, + }); + } + + // Search by status + else if (status) { + // Create a regex for case-insensitive search + const regex = new RegExp(status, "i"); + + orders = await RdOrder.find({ + addedBy: distributorId, + status: { $regex: regex }, + }) + .sort({ createdAt: -1 }) + .skip(skip) + .limit(limit); + + // console.log(orders); + + // Return empty array if no orders are found + if (!orders || orders.length === 0) { + return res.status(200).json([]); + } + + // Get total count for pagination + const totalOrders = await RdOrder.countDocuments({ + addedBy: distributorId, + status: { $regex: regex }, + }); + // console.log(totalOrders); + // Send response with pagination info + return res.status(200).json({ + totalOrders, + totalPages: Math.ceil(totalOrders / limit), + currentPage: page, + orders, + }); + } + + // Default behavior to return all orders + else { + orders = await RdOrder.find({ addedBy: distributorId }) + .sort({ createdAt: -1 }) + .skip(skip) + .limit(limit); + + // Return empty array if no orders are found + if (!orders || orders.length === 0) { + return res.status(200).json([]); + } + + // Get total count for pagination + const totalOrders = await RdOrder.countDocuments({ + addedBy: distributorId, + }); + + // Send response with pagination info + return res.status(200).json({ + totalOrders, + totalPages: Math.ceil(totalOrders / limit), + currentPage: page, + orders, + }); + } + } catch (error) { + console.error("Error fetching orders:", error); + res.status(500).json({ message: "Server error", error }); + } +}; diff --git a/resources/RD_Ordes/rdOrderRoutes.js b/resources/RD_Ordes/rdOrderRoutes.js index 5432ea0..ac9bb4d 100644 --- a/resources/RD_Ordes/rdOrderRoutes.js +++ b/resources/RD_Ordes/rdOrderRoutes.js @@ -2,9 +2,11 @@ import express from "express"; import { cancelOrderController, createOrderRD, + getAllOrdersByDistributor, getCancelledOrders, getNewOrders, getPendignOrders, + getPlacedOrderById, getPlacedOrdersForPD, getPlacedOrdersForRD, getSinglePlacedOrderForPD, @@ -12,7 +14,7 @@ import { processOrder, } from "./rdOrderController.js"; import { isAuthenticatedRD } from "../../middlewares/rdAuth.js"; -import { isAuthenticatedUser } from "../../middlewares/auth.js"; +import { authorizeRoles, isAuthenticatedUser } from "../../middlewares/auth.js"; const router = express.Router(); router.route("/rd-place-order").post(isAuthenticatedRD, createOrderRD); @@ -20,7 +22,13 @@ router.route("/rd-place-order").get(isAuthenticatedRD, getPlacedOrdersForRD); router .route("/rd-place-order/:id") .get(isAuthenticatedRD, getSinglePlacedOrderForRD); - +// routes for the Admin +router + .route("/get-single-placed-order-rd/:id") + .get(isAuthenticatedUser, authorizeRoles("admin"), getPlacedOrderById); +router + .route("/single-rd-order/:distributorId") + .get(isAuthenticatedUser, authorizeRoles("admin"), getAllOrdersByDistributor); // routes for the PD router .route("/pd-get-all-place-order")