rd stock calculation done using the inventory

This commit is contained in:
Sibunnayak 2024-10-10 10:54:56 +05:30
parent 3da91069e1
commit 45e54f6c74
6 changed files with 224 additions and 69 deletions

View File

@ -6,32 +6,74 @@ import TerritoryManager from "../TerritoryManagers/TerritoryManagerModel.js";
import SalesCoordinator from "../SalesCoOrdinators/SalesCoOrdinatorModel.js"; import SalesCoordinator from "../SalesCoOrdinators/SalesCoOrdinatorModel.js";
import crypto from "crypto"; import crypto from "crypto";
import RetailDistributor from "../RetailDistributor/RetailDistributorModel.js"; import RetailDistributor from "../RetailDistributor/RetailDistributorModel.js";
import { RDStock } from "../Stock/RdStockModel.js";
// Add inventory data // Add inventory data
export const addInventory = async (req, res) => { export const addInventory = async (req, res) => {
try { try {
const { products, addedFor, addedForId } = req.body; const { products, addedFor, addedForId } = req.body;
const userId = req.user._id; const userId = req.user._id;
const userType = req.userType; const userType = req.userType;
// console.log("req.user", req.user);
const currentYear = new Date().getFullYear().toString().slice(-2); if (addedFor === "RetailDistributor") {
const randomChars = crypto.randomBytes(4).toString("hex").toUpperCase(); // Find the RetailDistributor stock
const uniqueId = `${currentYear}-${randomChars}`; const rdStock = await RDStock.findOne({ userId: addedForId });
// console.log("uniqueId", uniqueId); if (!rdStock) {
return res.status(404).json({ error: "Stock not available for the RetailDistributor" });
}
// Array to hold product names that have issues
let invalidProducts = [];
// Loop through products in the request and check stock availability
for (const product of products) {
const { productid, Sale, ProductName } = product;
// Find product in the RetailDistributor's stock
const rdProduct = rdStock.products.find(p => p.productid.toString() === productid.toString());
if (rdProduct) {
// Check if sales quantity is less than or equal to the stock
if (Sale <= rdProduct.Stock) {
// Decrease the stock by sales amount
rdProduct.Stock -= Sale;
} else {
// If sales > stock, add to invalid products list
invalidProducts.push(ProductName);
}
} else {
// Product not found in stock, add to invalid products list
invalidProducts.push(ProductName);
}
}
// If there are any invalid products, return error message
if (invalidProducts.length > 0) {
return res.status(400).json({
success: false,
message: `Insufficient stock or product not found for: ${invalidProducts.join(", ")}`,
});
}
// Save updated stock if all products are valid
await rdStock.save();
}
// Create and save new inventory record
const newInventory = new Inventory({ const newInventory = new Inventory({
userId, userId,
userType, userType,
addedFor, addedFor,
addedForId, addedForId,
products, products,
uniqueId,
}); });
// console.log("newInventory", newInventory);
await newInventory.save(); await newInventory.save();
res.status(201).json({ res.status(201).json({
success: true, success: true,
message: "Inventory added successfully", message: "Inventory added successfully",
data: newInventory, data: newInventory,
}); });
} catch (error) { } catch (error) {
res.status(500).json({ success: false, message: "Server error", error }); res.status(500).json({ success: false, message: "Server error", error });
} }

View File

@ -1,7 +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: {
type: mongoose.Schema.Types.ObjectId,
ref: "Product",
required: true,
},
SKU: { SKU: {
type: String, type: String,
required: true, required: true,
@ -21,7 +26,8 @@ const ProductRecordSchema = new mongoose.Schema({
}); });
// Define main Inventory schema // Define main Inventory schema
const InventorySchema = new mongoose.Schema({ const InventorySchema = new mongoose.Schema(
{
uniqueId: { uniqueId: {
type: String, type: String,
required: true, required: true,
@ -29,25 +35,35 @@ const InventorySchema = new mongoose.Schema({
}, },
userId: { userId: {
type: mongoose.Schema.Types.ObjectId, type: mongoose.Schema.Types.ObjectId,
refPath: 'userType', refPath: "userType",
required: true, required: true,
}, },
userType: { userType: {
type: String, type: String,
required: true, required: true,
enum: ['SalesCoOrdinator', 'TerritoryManager'], enum: ["SalesCoOrdinator", "TerritoryManager"],
}, },
addedFor: { addedFor: {
type: String, type: String,
required: true, required: true,
enum: ['PrincipalDistributor', 'RetailDistributor'], enum: ["PrincipalDistributor", "RetailDistributor"],
}, },
addedForId: { addedForId: {
type: mongoose.Schema.Types.ObjectId, type: mongoose.Schema.Types.ObjectId,
refPath: 'addedFor', refPath: "addedFor",
required: true, required: true,
}, },
products: [ProductRecordSchema], products: [ProductRecordSchema],
}, { timestamps: true, versionKey: false }); },
{ timestamps: true, versionKey: false }
);
export const Inventory = mongoose.model('Inventory', InventorySchema); InventorySchema.pre("save", function (next) {
if (!this.uniqueId) {
const currentYear = new Date().getFullYear().toString().slice(-2);
const randomChars = crypto.randomBytes(4).toString("hex").toUpperCase();
this.uniqueId = `${currentYear}-${randomChars}`;
}
next();
});
export const Inventory = mongoose.model("Inventory", InventorySchema);

View File

@ -3,11 +3,12 @@ import { addInventory, getDistributors,getAllInventories,getSingleInventory } fr
import { isAuthenticatedSalesCoOrdinator } from "../../middlewares/SalesCoOrdinatorAuth.js"; import { isAuthenticatedSalesCoOrdinator } from "../../middlewares/SalesCoOrdinatorAuth.js";
import { isAuthenticatedTerritoryManager } from "../../middlewares/TerritoryManagerAuth.js"; import { isAuthenticatedTerritoryManager } from "../../middlewares/TerritoryManagerAuth.js";
import { authorizeRoles, isAuthenticatedUser } from "../../middlewares/auth.js"; import { authorizeRoles, isAuthenticatedUser } from "../../middlewares/auth.js";
import {isAuthenticated_SC_TM } from "../../middlewares/generalAuth.js";
const router = express.Router(); const router = express.Router();
// Route to add inventory data // Route to add inventory data
router.post("/add-SC", isAuthenticatedSalesCoOrdinator, addInventory); router.post("/add", isAuthenticated_SC_TM, addInventory);
router.post("/add-TM", isAuthenticatedTerritoryManager, addInventory); // router.post("/add-TM", isAuthenticatedTerritoryManager, addInventory);
// Route to get all PD or RD names based on type // Route to get all PD or RD names based on type
router.get( router.get(
"/distributors-SC/:type", "/distributors-SC/:type",

View File

@ -7,7 +7,7 @@ import { PDStock } from "../Stock/PdStockModel.js";
import { createKYC } from "../../Utils/rejectKyc.js"; import { createKYC } from "../../Utils/rejectKyc.js";
import { Notification } from "../Notification/notificationModal.js"; import { Notification } from "../Notification/notificationModal.js";
import { sendPushNotification } from "../../Utils/sendPushNotification.js"; import { sendPushNotification } from "../../Utils/sendPushNotification.js";
import {RDStock} from "../Stock/RdStockModel.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) => {
try { try {
@ -973,38 +973,38 @@ export const updateCourierStatusToDeliveredForPD = async (req, res) => {
if (!userId) { if (!userId) {
return res.status(400).json({ error: "User not found for the order" }); return res.status(400).json({ error: "User not found for the order" });
} }
// Check if PDStock exists for the user // Check if RDStock exists for the user
// let pdStock = await PDStock.findOne({ userId }); let rdStock = await RDStock.findOne({ userId });
// if (!pdStock) { if (!rdStock) {
// // If no stock record exists, create a new one // If no stock record exists, create a new one
// pdStock = new PDStock({ rdStock = new RDStock({
// userId, userId,
// products: [], // Initialize with empty products array products: [], // Initialize with empty products array
// }); });
// } }
// // Iterate over each item in the invoice // Iterate over each item in the invoice
// for (let item of invoice.items) { for (let item of invoice.items) {
// const { productId, processquantity } = item; const { productId, processquantity } = item;
// // Check if the product already exists in the PDStock for the user // Check if the product already exists in the PDStock for the user
// const existingProduct = pdStock.products.find( const existingProduct = rdStock.products.find(
// (p) => p.productid.toString() === productId.toString() (p) => p.productid.toString() === productId.toString()
// ); );
// if (existingProduct) { if (existingProduct) {
// // If the product exists, update the stock by adding the processquantity // If the product exists, update the stock by adding the processquantity
// existingProduct.Stock += processquantity; existingProduct.Stock += processquantity;
// } else { } else {
// // If the product doesn't exist, add a new entry for the product // If the product doesn't exist, add a new entry for the product
// pdStock.products.push({ rdStock.products.push({
// productid: productId, productid: productId,
// Stock: processquantity, Stock: processquantity,
// }); });
// } }
// } }
// Save the updated PDStock // Save the updated PDStock
// await pdStock.save(); await rdStock.save();
// Format the current date for display // Format the current date for display
const formattedDate = formatDate(new Date()); const formattedDate = formatDate(new Date());

View File

@ -200,3 +200,93 @@ export const getProductsAndStockByRD = async (req, res) => {
}); });
} }
}; };
export const getProductsAndStockForRD = async (req, res) => {
try {
const { userId } = req.user._id;
// Filtering criteria
const filter = {};
if (req.query.name) {
filter.name = {
$regex: new RegExp(req.query.name, "i"),
};
}
if (req.query.category) {
filter.category = mongoose.Types.ObjectId(req.query.category);
}
if (req.query.brand) {
filter.brand = mongoose.Types.ObjectId(req.query.brand);
}
// Fetch user's RDStock data and products concurrently
const [userStock, products] = await Promise.all([
RDStock.findOne({ userId: mongoose.Types.ObjectId(userId) }),
Product.aggregate([
{ $match: filter },
{
$lookup: {
from: "categorymodels",
localField: "category",
foreignField: "_id",
as: "categoryDetails",
},
},
{
$lookup: {
from: "brandmodels",
localField: "brand",
foreignField: "_id",
as: "brandDetails",
},
},
{
$project: {
category: { $arrayElemAt: ["$categoryDetails.categoryName", 0] },
brand: { $arrayElemAt: ["$brandDetails.brandName", 0] },
GST: 1,
HSN_Code: 1,
SKU: 1,
addedBy: 1,
createdAt: 1,
description: 1,
image: 1,
name: 1,
price: 1,
product_Status: 1,
updatedAt: 1,
},
},
]),
]);
// Create a stock map for easy lookup
const stockMap = {};
if (userStock && userStock.products) {
userStock.products.forEach((product) => {
stockMap[product.productid.toString()] = product.Stock;
});
}
// Combine products with their respective stock
const productsWithStock = products.map((product) => ({
...product,
stock: stockMap[product._id.toString()] || 0,
}));
// Get total count for pagination purposes
const total = await Product.countDocuments(filter);
return res.status(200).json({
success: true,
totalProducts: total,
products: productsWithStock,
});
} catch (error) {
console.error("Error fetching products with stock:", error);
return res.status(500).json({
success: false,
message: "Error fetching products and stock",
});
}
};

View File

@ -1,6 +1,11 @@
import express from "express"; import express from "express";
import { getProductsAndStockByPD ,getProductsAndStockByRD} from "./StockController.js"; import {
getProductsAndStockByPD,
getProductsAndStockByRD,
getProductsAndStockForRD,
} from "./StockController.js";
import { authorizeRoles, isAuthenticatedUser } from "../../middlewares/auth.js"; import { authorizeRoles, isAuthenticatedUser } from "../../middlewares/auth.js";
import {isAuthenticatedRD} from "../../middlewares/rdAuth.js";
const router = express.Router(); const router = express.Router();
router.get( router.get(
@ -15,4 +20,5 @@ router.get(
authorizeRoles("admin"), authorizeRoles("admin"),
getProductsAndStockByRD getProductsAndStockByRD
); );
router.get("/stock", isAuthenticatedRD, getProductsAndStockForRD);
export default router; export default router;