From a5bc315013c5db00da2d3721a46d0dd2a131bb6a Mon Sep 17 00:00:00 2001 From: ROSHAN GARG Date: Thu, 24 Oct 2024 10:32:17 +0530 Subject: [PATCH] update inventory --- resources/Stock/PdStockModel.js | 31 +++++++---- resources/Stock/StockController.js | 88 ++++++++++++++++++++---------- resources/Stock/StockRoute.js | 4 +- 3 files changed, 81 insertions(+), 42 deletions(-) diff --git a/resources/Stock/PdStockModel.js b/resources/Stock/PdStockModel.js index 689c73e..2fc699f 100644 --- a/resources/Stock/PdStockModel.js +++ b/resources/Stock/PdStockModel.js @@ -1,12 +1,19 @@ -import mongoose from 'mongoose'; +import mongoose from "mongoose"; // Define Product record schema const ProductRecordSchema = new mongoose.Schema({ productid: { type: mongoose.Schema.Types.ObjectId, - ref: 'Product', + ref: "Product", required: true, }, + SKU: { + type: String, + }, + openingInventory: { + type: Number, + default: 0, + }, Stock: { type: Number, default: 0, @@ -14,13 +21,17 @@ const ProductRecordSchema = new mongoose.Schema({ }); // Define main Stock schema -const StockSchema = new mongoose.Schema({ - userId: { - type: mongoose.Schema.Types.ObjectId, - refPath: 'User', - required: true, +const StockSchema = new mongoose.Schema( + { + userId: { + type: mongoose.Schema.Types.ObjectId, + refPath: "User", + required: true, + unique: true, + }, + products: [ProductRecordSchema], }, - products: [ProductRecordSchema], -}, { timestamps: true, versionKey: false }); + { timestamps: true, versionKey: false } +); -export const PDStock = mongoose.model('PDStock', StockSchema); +export const PDStock = mongoose.model("PDStock", StockSchema); diff --git a/resources/Stock/StockController.js b/resources/Stock/StockController.js index ae06891..f94ea2b 100644 --- a/resources/Stock/StockController.js +++ b/resources/Stock/StockController.js @@ -202,37 +202,53 @@ export const getProductsAndStockByRD = async (req, res) => { }; // Create or Update Stock -export const createOrUpdateStock = async (req, res) => { +export const createOrUpdateInventory = async (req, res) => { const userId = req.user._id; try { const { products } = req.body; // products: [{ productid, Stock }] + console.log(products); + // Fetch all products in the system + const allProducts = await Product.find({}, "_id SKU"); // Fetch only _id and SKU fields + const allProductIds = allProducts.map((p) => p._id.toString()); - // Get all product IDs from the Product collection - const allProducts = await Product.find({}, "_id"); // Fetch only the _id field - const allProductIds = allProducts.map((p) => p._id.toString()); // Convert to string array - - // Initialize stock for all products as 0 - const updatedProducts = allProductIds.map((productId) => { - const productInRequest = products.find((p) => p.productid === productId); - - return { - productid: productId, - Stock: productInRequest ? productInRequest.Stock : 0, - }; - }); - - // Check if stock entry already exists for the user + // Find existing stock data for the user let stock = await PDStock.findOne({ userId }); + const updatedProducts = allProductIds.map((productId) => { + const productInRequest = products.find((p) => p.productid === productId); + const existingProduct = stock?.products.find( + (p) => p.productid.toString() === productId + ); + + if (existingProduct) { + // Product exists, only update opening inventory + return { + ...existingProduct, + openingInventory: productInRequest + ? productInRequest.Stock + : existingProduct.openingInventory, + }; + } else { + // New product, set both stock and opening inventory to the same value + console.log("came here "); + return { + productid: productId, + SKU: allProducts.find((p) => p._id.toString() === productId).SKU, + openingInventory: productInRequest ? productInRequest.Stock : 0, + Stock: productInRequest ? productInRequest.Stock : 0, + }; + } + }); + if (stock) { - // Replace stock with the updated product list + // Update existing stock entry stock.products = updatedProducts; await stock.save(); return res .status(200) .json({ message: "Stock updated successfully", stock }); } else { - // Create a new stock entry if it doesn't exist + // Create new stock entry const newStock = new PDStock({ userId, products: updatedProducts }); await newStock.save(); return res @@ -247,10 +263,10 @@ export const createOrUpdateStock = async (req, res) => { export const getStockPD = async (req, res) => { try { - const userId = req.user._id; // userId is provided in the URL + const userId = req.user._id; // userId from request // Fetch all products with their _id, name, and SKU - const allProducts = await Product.find({}, "_id name SKU"); // Adjust field names if needed + const allProducts = await Product.find({}, "_id name SKU"); // Map products into an object for easy access const productMap = new Map( @@ -265,23 +281,35 @@ export const getStockPD = async (req, res) => { if (stock) { // Create a map of product stocks from the user's stock const stockMap = new Map( - stock.products.map((p) => [p.productid.toString(), p.Stock]) + stock.products.map((p) => [ + p.productid.toString(), + { Stock: p.Stock, openingInventory: p.openingInventory || 0 }, + ]) ); - // Iterate over all products, assigning stock or initializing to 0 + // Iterate over all products, assigning stock and opening inventory + productsWithStock = allProducts.map((product) => { + const productStock = stockMap.get(product._id.toString()) || { + Stock: 0, + openingInventory: 0, + }; + + return { + productid: product._id, + name: product.name, + SKU: product.SKU, + Stock: productStock.Stock, + openingInventory: productStock.openingInventory, + }; + }); + } else { + // If no stock entry exists, initialize all products with stock and opening inventory as 0 productsWithStock = allProducts.map((product) => ({ productid: product._id, name: product.name, SKU: product.SKU, - Stock: stockMap.get(product._id.toString()) || 0, - })); - } else { - // If no stock entry exists, initialize all products with stock 0 - productsWithStock = allProducts.map((product) => ({ - productid: product._id, - name: product.name, - sku: product.sku, Stock: 0, + openingInventory: 0, })); } diff --git a/resources/Stock/StockRoute.js b/resources/Stock/StockRoute.js index 26710e0..f2fb33a 100644 --- a/resources/Stock/StockRoute.js +++ b/resources/Stock/StockRoute.js @@ -1,6 +1,6 @@ import express from "express"; import { - createOrUpdateStock, + createOrUpdateInventory, getProductsAndStockByPD, getProductsAndStockByRD, getStockPD, @@ -11,7 +11,7 @@ const router = express.Router(); router.get("/pd/stock/:userId", isAuthenticatedUser, getProductsAndStockByPD); router.get("/pd/stock", isAuthenticatedUser, getStockPD); -router.put("/pd/stock-update", isAuthenticatedUser, createOrUpdateStock); +router.put("/pd/stock-update", isAuthenticatedUser, createOrUpdateInventory); router.get( "/rd/stock/:userId", isAuthenticatedUser,