api done for Rd OI
This commit is contained in:
parent
537f693dde
commit
78369465af
@ -1,26 +1,45 @@
|
||||
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,
|
||||
},
|
||||
Stock: {
|
||||
type: Number,
|
||||
default: 0,
|
||||
},
|
||||
productName: {
|
||||
type: String,
|
||||
required: true,
|
||||
},
|
||||
openingInventory: {
|
||||
type: Number,
|
||||
default: 0,
|
||||
set: (value) => {
|
||||
if (typeof value === "string") {
|
||||
// Convert to number and remove leading zeros
|
||||
return Number(value.replace(/^0+/, "")) || undefined;
|
||||
}
|
||||
return value;
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// Define main Stock schema
|
||||
const StockSchema = new mongoose.Schema({
|
||||
const StockSchema = new mongoose.Schema(
|
||||
{
|
||||
userId: {
|
||||
type: mongoose.Schema.Types.ObjectId,
|
||||
refPath: 'RetailDistributor',
|
||||
refPath: "RetailDistributor",
|
||||
required: true,
|
||||
unique: true,
|
||||
},
|
||||
products: [ProductRecordSchema],
|
||||
}, { timestamps: true, versionKey: false });
|
||||
},
|
||||
{ timestamps: true, versionKey: false }
|
||||
);
|
||||
|
||||
export const RDStock = mongoose.model('RDStock', StockSchema);
|
||||
export const RDStock = mongoose.model("RDStock", StockSchema);
|
||||
|
@ -420,68 +420,7 @@ export const getProductsAndStockByRD = async (req, res) => {
|
||||
}
|
||||
};
|
||||
|
||||
// Create or Update Stock
|
||||
// export const createOrUpdateInventory = async (req, res) => {
|
||||
// const userId = req.body.userId ? req.body.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());
|
||||
|
||||
// // 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.openingInventory
|
||||
// : existingProduct.openingInventory,
|
||||
// Stock: productInRequest ? productInRequest.openingInventory : 0,
|
||||
// };
|
||||
// } else {
|
||||
// // New product, set both stock and opening inventory to the same value
|
||||
|
||||
// return {
|
||||
// productid: productId,
|
||||
// SKU: allProducts.find((p) => p._id.toString() === productId).SKU,
|
||||
// openingInventory: productInRequest
|
||||
// ? productInRequest.openingInventory
|
||||
// : 0,
|
||||
// Stock: productInRequest ? productInRequest.openingInventory : 0,
|
||||
// };
|
||||
// }
|
||||
// });
|
||||
|
||||
// if (stock) {
|
||||
// // Update existing stock entry
|
||||
// stock.products = updatedProducts;
|
||||
// await stock.save();
|
||||
// return res
|
||||
// .status(200)
|
||||
// .json({ message: "Stock updated successfully", stock });
|
||||
// } else {
|
||||
// // Create new stock entry
|
||||
// const newStock = new PDStock({ userId, products: updatedProducts });
|
||||
// await newStock.save();
|
||||
// return res
|
||||
// .status(201)
|
||||
// .json({ message: "Stock created successfully", stock: newStock });
|
||||
// }
|
||||
// } catch (error) {
|
||||
// console.error("Error updating or creating stock:", error);
|
||||
// res.status(500).json({ message: "Server error", error });
|
||||
// }
|
||||
// };
|
||||
// PD inventory
|
||||
export const createOrUpdateInventory = async (req, res) => {
|
||||
const userId = req.body.userId ? req.body.userId : req.user._id;
|
||||
// console.log(userId);
|
||||
@ -624,6 +563,145 @@ export const getStockPD = async (req, res) => {
|
||||
res.status(500).json({ message: "Server error", error });
|
||||
}
|
||||
};
|
||||
|
||||
// RD inventory
|
||||
export const createOrUpdateInventoryForRD = async (req, res) => {
|
||||
const userId = req.body.userId ? req.body.userId : req.user._id;
|
||||
console.log("res came here ");
|
||||
try {
|
||||
const { products } = req.body;
|
||||
const allProducts = await Product.find({}, "_id SKU name");
|
||||
|
||||
let stock = await RDStock.findOne({ userId });
|
||||
|
||||
if (!products || products.length === 0) {
|
||||
return res.status(400).json({ message: "No products provided." });
|
||||
}
|
||||
|
||||
const updatedProducts = [];
|
||||
|
||||
// Loop through the requested products and process them
|
||||
for (const reqProduct of products) {
|
||||
const { SKU, openingInventory } = reqProduct;
|
||||
|
||||
// Find the product by SKU in the Product collection
|
||||
const productInSystem = allProducts.find((p) => p.SKU === SKU);
|
||||
|
||||
if (!productInSystem) {
|
||||
// Skip products that don't exist in the system
|
||||
console.log(
|
||||
`Product with SKU ${SKU} not found in the system. Skipping...`
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Find the product in existing PDStock (if any)
|
||||
const existingProductInStock = stock?.products.find(
|
||||
(p) => p.productid.toString() === productInSystem._id.toString()
|
||||
);
|
||||
|
||||
if (existingProductInStock) {
|
||||
// If the product exists in stock, update opening inventory and stock
|
||||
existingProductInStock.openingInventory =
|
||||
openingInventory || existingProductInStock.openingInventory;
|
||||
existingProductInStock.Stock =
|
||||
openingInventory || existingProductInStock.Stock;
|
||||
updatedProducts.push(existingProductInStock);
|
||||
} else {
|
||||
// If the product doesn't exist in PDStock, create a new entry
|
||||
const newProductInStock = {
|
||||
productid: productInSystem._id,
|
||||
SKU: productInSystem.SKU,
|
||||
productName: productInSystem.name,
|
||||
openingInventory: openingInventory || 0,
|
||||
Stock: openingInventory || 0,
|
||||
};
|
||||
updatedProducts.push(newProductInStock);
|
||||
}
|
||||
}
|
||||
// console.log(updatedProducts);
|
||||
if (stock) {
|
||||
// Update existing stock entry
|
||||
stock.products = updatedProducts;
|
||||
await stock.save();
|
||||
return res
|
||||
.status(200)
|
||||
.json({ message: "Stock updated successfully", stock });
|
||||
} else {
|
||||
// Create new stock entry
|
||||
const newStock = new RDStock({ userId, products: updatedProducts });
|
||||
await newStock.save();
|
||||
return res
|
||||
.status(201)
|
||||
.json({ message: "Stock created successfully", stock: newStock });
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error updating or creating stock:", error);
|
||||
res.status(500).json({ message: "Server error", error });
|
||||
}
|
||||
};
|
||||
export const getStockRD = async (req, res) => {
|
||||
try {
|
||||
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");
|
||||
|
||||
// Map products into an object for easy access
|
||||
const productMap = new Map(
|
||||
allProducts.map((p) => [p._id.toString(), { name: p.name, sku: p.SKU }])
|
||||
);
|
||||
|
||||
// Fetch the user's stock from the PDStock model
|
||||
let stock = await RDStock.findOne({ userId });
|
||||
|
||||
let productsWithStock = [];
|
||||
|
||||
if (stock) {
|
||||
// Create a map of product stocks from the user's stock
|
||||
const stockMap = new Map(
|
||||
stock.products.map((p) => [
|
||||
p.productid.toString(),
|
||||
{ Stock: p.Stock, openingInventory: p.openingInventory || 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: 0,
|
||||
openingInventory: 0,
|
||||
}));
|
||||
}
|
||||
|
||||
return res.status(200).json({
|
||||
message: "Stock fetched successfully",
|
||||
stocks: productsWithStock,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Error fetching stock:", error);
|
||||
res.status(500).json({ message: "Server error", error });
|
||||
}
|
||||
};
|
||||
|
||||
export const getAllUsersWithStock = async (req, res) => {
|
||||
try {
|
||||
// Destructure query parameters for pagination and filtering
|
||||
|
@ -1,10 +1,12 @@
|
||||
import express from "express";
|
||||
import {
|
||||
createOrUpdateInventory,
|
||||
createOrUpdateInventoryForRD,
|
||||
getAllUsersWithStock,
|
||||
getProductsAndStockByPD,
|
||||
getProductsAndStockByRD,
|
||||
getStockPD,
|
||||
getStockRD,
|
||||
uploadOpeningInventory,
|
||||
} from "./StockController.js";
|
||||
import { authorizeRoles, isAuthenticatedUser } from "../../middlewares/auth.js";
|
||||
@ -21,6 +23,9 @@ router.post(
|
||||
router.get("/pd/stock/:userId", isAuthenticatedUser, getProductsAndStockByPD);
|
||||
router.get("/pd/stock", isAuthenticatedUser, getStockPD);
|
||||
router.put("/pd/stock-update", isAuthenticatedUser, createOrUpdateInventory);
|
||||
|
||||
router.get("/rd/stock", isAuthenticatedRD, getStockRD);
|
||||
router.put("/rd/stock-update", isAuthenticatedRD, createOrUpdateInventoryForRD);
|
||||
router.get(
|
||||
"/rd/stock/:userId",
|
||||
isAuthenticatedUser,
|
||||
|
Loading…
Reference in New Issue
Block a user