pd stock model and get api

This commit is contained in:
Sibunnayak 2024-09-27 21:51:08 +05:30
parent f405476976
commit 736226cca5

View File

@ -2,6 +2,7 @@ import sendEmail from "../../Utils/sendEmail.js";
import RetailDistributor from "../RetailDistributor/RetailDistributorModel.js"; import RetailDistributor from "../RetailDistributor/RetailDistributorModel.js";
import { InvoiceRd } from "./invoiceModalRD.js"; import { InvoiceRd } from "./invoiceModalRD.js";
import { RdOrder } from "./rdOrderModal.js"; import { RdOrder } from "./rdOrderModal.js";
import { PDStock } from "../Stock/PdStockModel.js";
// Controller to create a new order by RD // Controller to create a new order by RD
export const createOrderRD = async (req, res) => { export const createOrderRD = async (req, res) => {
@ -379,7 +380,29 @@ export const processOrder = async (req, res) => {
// Save the invoice // Save the invoice
const savedInvoice = await newInvoice.save(); 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 // Update the order's order items with the remaining quantity
let allItemsProcessed = true; // Flag to check if all items are processed let allItemsProcessed = true; // Flag to check if all items are processed