Compare commits

..

No commits in common. "6e620d22b3b3cedf40f41d0083ef24ca41e3c217" and "2745d0b33087174910911ec46b23c7d47cede042" have entirely different histories.

3 changed files with 39 additions and 77 deletions

View File

@ -1,19 +1,12 @@
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,
@ -21,17 +14,13 @@ const ProductRecordSchema = new mongoose.Schema({
}); });
// Define main Stock schema // Define main Stock schema
const StockSchema = new mongoose.Schema( const StockSchema = new mongoose.Schema({
{ userId: {
userId: { type: mongoose.Schema.Types.ObjectId,
type: mongoose.Schema.Types.ObjectId, ref: 'User',
refPath: "User", required: true,
required: true,
unique: true,
},
products: [ProductRecordSchema],
}, },
{ timestamps: true, versionKey: false } products: [ProductRecordSchema],
); }, { timestamps: true, versionKey: false });
export const PDStock = mongoose.model("PDStock", StockSchema); export const PDStock = mongoose.model('PDStock', StockSchema);

View File

@ -202,53 +202,37 @@ export const getProductsAndStockByRD = async (req, res) => {
}; };
// Create or Update Stock // Create or Update Stock
export const createOrUpdateInventory = async (req, res) => { export const createOrUpdateStock = 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());
// Find existing stock data for the user // Get all product IDs from the Product collection
let stock = await PDStock.findOne({ userId }); 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 updatedProducts = allProductIds.map((productId) => {
const productInRequest = products.find((p) => p.productid === productId); const productInRequest = products.find((p) => p.productid === productId);
const existingProduct = stock?.products.find(
(p) => p.productid.toString() === productId
);
if (existingProduct) { return {
// Product exists, only update opening inventory productid: productId,
return { Stock: productInRequest ? productInRequest.Stock : 0,
...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,
};
}
}); });
// Check if stock entry already exists for the user
let stock = await PDStock.findOne({ userId });
if (stock) { if (stock) {
// Update existing stock entry // Replace stock with the updated product list
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 new stock entry // Create a new stock entry if it doesn't exist
const newStock = new PDStock({ userId, products: updatedProducts }); const newStock = new PDStock({ userId, products: updatedProducts });
await newStock.save(); await newStock.save();
return res return res
@ -263,10 +247,10 @@ export const createOrUpdateInventory = async (req, res) => {
export const getStockPD = async (req, res) => { export const getStockPD = async (req, res) => {
try { try {
const userId = req.user._id; // userId from request const userId = req.user._id; // userId is provided in the URL
// 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"); const allProducts = await Product.find({}, "_id name SKU"); // Adjust field names if needed
// Map products into an object for easy access // Map products into an object for easy access
const productMap = new Map( const productMap = new Map(
@ -281,35 +265,23 @@ 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) => [ stock.products.map((p) => [p.productid.toString(), p.Stock])
p.productid.toString(),
{ Stock: p.Stock, openingInventory: p.openingInventory || 0 },
])
); );
// Iterate over all products, assigning stock and opening inventory // Iterate over all products, assigning stock or initializing to 0
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,7 @@
import express from "express"; import express from "express";
import { import {
createOrUpdateInventory, createOrUpdateStock,
getAllUsersWithStock,
getProductsAndStockByPD, getProductsAndStockByPD,
getProductsAndStockByRD, getProductsAndStockByRD,
getStockPD, getStockPD,
@ -11,7 +12,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, createOrUpdateInventory); router.put("/pd/stock-update", isAuthenticatedUser, createOrUpdateStock);
router.get( router.get(
"/rd/stock/:userId", "/rd/stock/:userId",
isAuthenticatedUser, isAuthenticatedUser,