Compare commits
No commits in common. "c279b8d7deb2744e95f64413005e22f5e4ae50a0" and "2ade217606aa91b56ba4fb833af385e75cd3e03d" have entirely different histories.
c279b8d7de
...
2ade217606
@ -1,45 +1,26 @@
|
|||||||
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,
|
||||||
},
|
},
|
||||||
Stock: {
|
Stock: {
|
||||||
type: Number,
|
type: Number,
|
||||||
default: 0,
|
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
|
// 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,
|
refPath: 'RetailDistributor',
|
||||||
refPath: "RetailDistributor",
|
required: true,
|
||||||
required: true,
|
|
||||||
unique: true,
|
|
||||||
},
|
|
||||||
products: [ProductRecordSchema],
|
|
||||||
},
|
},
|
||||||
{ timestamps: true, versionKey: false }
|
products: [ProductRecordSchema],
|
||||||
);
|
}, { timestamps: true, versionKey: false });
|
||||||
|
|
||||||
export const RDStock = mongoose.model("RDStock", StockSchema);
|
export const RDStock = mongoose.model('RDStock', StockSchema);
|
||||||
|
@ -421,7 +421,68 @@ export const getProductsAndStockByRD = async (req, res) => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// PD inventory
|
// 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 });
|
||||||
|
// }
|
||||||
|
// };
|
||||||
export const createOrUpdateInventory = async (req, res) => {
|
export const createOrUpdateInventory = async (req, res) => {
|
||||||
const userId = req.body.userId ? req.body.userId : req.user._id;
|
const userId = req.body.userId ? req.body.userId : req.user._id;
|
||||||
// console.log(userId);
|
// console.log(userId);
|
||||||
@ -564,145 +625,6 @@ export const getStockPD = async (req, res) => {
|
|||||||
res.status(500).json({ message: "Server error", error });
|
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) => {
|
export const getAllUsersWithStock = async (req, res) => {
|
||||||
try {
|
try {
|
||||||
// Destructure query parameters for pagination and filtering
|
// Destructure query parameters for pagination and filtering
|
||||||
|
@ -1,12 +1,10 @@
|
|||||||
import express from "express";
|
import express from "express";
|
||||||
import {
|
import {
|
||||||
createOrUpdateInventory,
|
createOrUpdateInventory,
|
||||||
createOrUpdateInventoryForRD,
|
|
||||||
getAllUsersWithStock,
|
getAllUsersWithStock,
|
||||||
getProductsAndStockByPD,
|
getProductsAndStockByPD,
|
||||||
getProductsAndStockByRD,
|
getProductsAndStockByRD,
|
||||||
getStockPD,
|
getStockPD,
|
||||||
getStockRD,
|
|
||||||
uploadOpeningInventory,
|
uploadOpeningInventory,
|
||||||
} from "./StockController.js";
|
} from "./StockController.js";
|
||||||
import { authorizeRoles, isAuthenticatedUser } from "../../middlewares/auth.js";
|
import { authorizeRoles, isAuthenticatedUser } from "../../middlewares/auth.js";
|
||||||
@ -23,9 +21,6 @@ router.post(
|
|||||||
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, createOrUpdateInventory);
|
||||||
|
|
||||||
router.get("/rd/stock", isAuthenticatedRD, getStockRD);
|
|
||||||
router.put("/rd/stock-update", isAuthenticatedRD, createOrUpdateInventoryForRD);
|
|
||||||
router.get(
|
router.get(
|
||||||
"/rd/stock/:userId",
|
"/rd/stock/:userId",
|
||||||
isAuthenticatedUser,
|
isAuthenticatedUser,
|
||||||
|
Loading…
Reference in New Issue
Block a user