update inventory

This commit is contained in:
ROSHAN GARG 2024-10-24 10:32:17 +05:30
parent 6b4cd0e76d
commit a5bc315013
3 changed files with 81 additions and 42 deletions

View File

@ -1,12 +1,19 @@
import mongoose from 'mongoose'; import mongoose from "mongoose";
// Define Product record schema // Define Product record schema
const ProductRecordSchema = new mongoose.Schema({ const ProductRecordSchema = new mongoose.Schema({
productid: { productid: {
type: mongoose.Schema.Types.ObjectId, type: mongoose.Schema.Types.ObjectId,
ref: 'Product', ref: "Product",
required: true, required: true,
}, },
SKU: {
type: String,
},
openingInventory: {
type: Number,
default: 0,
},
Stock: { Stock: {
type: Number, type: Number,
default: 0, default: 0,
@ -14,13 +21,17 @@ const ProductRecordSchema = new mongoose.Schema({
}); });
// Define main Stock schema // Define main Stock schema
const StockSchema = new mongoose.Schema({ const StockSchema = new mongoose.Schema(
userId: { {
type: mongoose.Schema.Types.ObjectId, userId: {
refPath: 'User', type: mongoose.Schema.Types.ObjectId,
required: true, 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);

View File

@ -202,37 +202,53 @@ export const getProductsAndStockByRD = async (req, res) => {
}; };
// Create or Update Stock // Create or Update Stock
export const createOrUpdateStock = async (req, res) => { export const createOrUpdateInventory = async (req, res) => {
const userId = req.user._id; const userId = req.user._id;
try { try {
const { products } = req.body; // products: [{ productid, Stock }] 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 // Find existing stock data for the user
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
let stock = await PDStock.findOne({ userId }); 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) { if (stock) {
// Replace stock with the updated product list // Update existing stock entry
stock.products = updatedProducts; stock.products = updatedProducts;
await stock.save(); await stock.save();
return res return res
.status(200) .status(200)
.json({ message: "Stock updated successfully", stock }); .json({ message: "Stock updated successfully", stock });
} else { } else {
// Create a new stock entry if it doesn't exist // Create new stock entry
const newStock = new PDStock({ userId, products: updatedProducts }); const newStock = new PDStock({ userId, products: updatedProducts });
await newStock.save(); await newStock.save();
return res return res
@ -247,10 +263,10 @@ export const createOrUpdateStock = async (req, res) => {
export const getStockPD = async (req, res) => { export const getStockPD = async (req, res) => {
try { 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 // 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 // Map products into an object for easy access
const productMap = new Map( const productMap = new Map(
@ -265,23 +281,35 @@ export const getStockPD = async (req, res) => {
if (stock) { if (stock) {
// Create a map of product stocks from the user's stock // Create a map of product stocks from the user's stock
const stockMap = new Map( 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) => ({ productsWithStock = allProducts.map((product) => ({
productid: product._id, productid: product._id,
name: product.name, name: product.name,
SKU: product.SKU, 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, Stock: 0,
openingInventory: 0,
})); }));
} }

View File

@ -1,6 +1,6 @@
import express from "express"; import express from "express";
import { import {
createOrUpdateStock, createOrUpdateInventory,
getProductsAndStockByPD, getProductsAndStockByPD,
getProductsAndStockByRD, getProductsAndStockByRD,
getStockPD, getStockPD,
@ -11,7 +11,7 @@ const router = express.Router();
router.get("/pd/stock/:userId", isAuthenticatedUser, getProductsAndStockByPD); router.get("/pd/stock/:userId", isAuthenticatedUser, getProductsAndStockByPD);
router.get("/pd/stock", isAuthenticatedUser, getStockPD); router.get("/pd/stock", isAuthenticatedUser, getStockPD);
router.put("/pd/stock-update", isAuthenticatedUser, createOrUpdateStock); router.put("/pd/stock-update", isAuthenticatedUser, createOrUpdateInventory);
router.get( router.get(
"/rd/stock/:userId", "/rd/stock/:userId",
isAuthenticatedUser, isAuthenticatedUser,