conflict resolved'

This commit is contained in:
ROSHAN GARG 2024-09-30 16:33:38 +05:30
commit fb1ed55ebf
3 changed files with 207 additions and 28 deletions

View File

@ -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,

View File

@ -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 = [];
// Check each item in invoiceItems for quantity limits
for (const item of invoiceItems) {
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);
// 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) => `
<tr>
@ -463,7 +526,6 @@ export const processOrder = async (req, res) => {
`
)
.join("");
const pendingItems = order.orderItem
.filter((item) => item.remainingQuantity > 0)
.map(
@ -498,7 +560,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!`
@ -1362,3 +1423,115 @@ const formatDate = (date) => {
};
return new Intl.DateTimeFormat("en-US", options).format(new Date(date));
};
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 });
}
};

View File

@ -2,12 +2,14 @@ import express from "express";
import {
cancelOrderController,
createOrderRD,
getAllOrdersByDistributor,
getCancelledOrders,
getDeliveredInvoicesForPd,
getDispatchedInvoicesForPd,
getInvoiceDetailsByIdForPD,
getNewOrders,
getPendignOrders,
getPlacedOrderById,
getPlacedOrdersForPD,
getPlacedOrdersForRD,
getProcessingInvoicesForPd,
@ -19,10 +21,8 @@ import {
} from "./rdOrderController.js";
import { isAuthenticatedRD } from "../../middlewares/rdAuth.js";
import { isAuthenticatedUser } from "../../middlewares/auth.js";
import {
getDispatchedInvoices,
getProcessingInvoices,
} from "../PD_Orders/pdOrderController.js";
import { authorizeRoles, isAuthenticatedUser } from "../../middlewares/auth.js";
const router = express.Router();
router.route("/rd-place-order").post(isAuthenticatedRD, createOrderRD);
@ -30,7 +30,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")