create and update openinginventory of PD and RD will fixed

This commit is contained in:
Sibunnayak 2024-11-06 22:18:12 +05:30
parent 769ed76eed
commit fdf7b433d9

View File

@ -626,6 +626,86 @@ export const getProductsAndStockByRD = async (req, res) => {
}; };
// PD inventory // PD inventory
// export const createOrUpdateInventory = async (req, res) => {
// const userId = req.body.userId ? req.body.userId : req.user._id;
// console.log(userId);
// try {
// const { products } = req.body; // products: [{ SKU, openingInventory }]
// console.log(products);
// // Fetch all products in the system (get _id, SKU, and name)
// const allProducts = await Product.find({}, "_id SKU name");
// // Find existing stock data for the user
// let stock = await PDStock.findOne({ userId });
// // If no products found in the request, return an error
// 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.SKU === productInSystem.SKU
// );
// 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 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);
@ -644,9 +724,9 @@ export const createOrUpdateInventory = async (req, res) => {
return res.status(400).json({ message: "No products provided." }); return res.status(400).json({ message: "No products provided." });
} }
const updatedProducts = []; const updatedProductsMap = new Map();
// Loop through the requested products and process them // Create a map of all requested updates for easy access by SKU
for (const reqProduct of products) { for (const reqProduct of products) {
const { SKU, openingInventory } = reqProduct; const { SKU, openingInventory } = reqProduct;
@ -661,41 +741,50 @@ export const createOrUpdateInventory = async (req, res) => {
continue; continue;
} }
// Find the product in existing PDStock (if any) // Prepare updated product data to be used later
const existingProductInStock = stock?.products.find( updatedProductsMap.set(SKU, {
(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, productid: productInSystem._id,
SKU: productInSystem.SKU, SKU: productInSystem.SKU,
productName: productInSystem.name, productName: productInSystem.name,
openingInventory: openingInventory || 0, openingInventory: openingInventory || 0,
Stock: openingInventory || 0, Stock: openingInventory || 0,
}; });
updatedProducts.push(newProductInStock);
} }
}
// console.log(updatedProducts);
if (stock) { if (stock) {
// Update existing stock entry // Create a map of existing products by SKU for easy lookup
stock.products = updatedProducts; const existingProductsMap = new Map();
stock.products.forEach((product) => {
existingProductsMap.set(product.SKU, product);
});
// Update only the products that need to be updated
const mergedProducts = stock.products.map((product) => {
if (updatedProductsMap.has(product.SKU)) {
// Update existing product with new values
const updatedProduct = updatedProductsMap.get(product.SKU);
return { ...product, ...updatedProduct };
}
return product; // Keep unchanged product as-is
});
// Add any new products that were not previously in stock
updatedProductsMap.forEach((updatedProduct, SKU) => {
if (!existingProductsMap.has(SKU)) {
mergedProducts.push(updatedProduct);
}
});
// Save the merged products list to the stock
stock.products = mergedProducts;
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 new stock entry if none exists
const newStock = new PDStock({ userId, products: updatedProducts }); const newStock = new PDStock({ userId, products: Array.from(updatedProductsMap.values()) });
await newStock.save(); await newStock.save();
return res return res
.status(201) .status(201)
@ -770,22 +859,102 @@ export const getStockPD = async (req, res) => {
}; };
// RD inventory // 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 createOrUpdateInventoryForRD = async (req, res) => { export const createOrUpdateInventoryForRD = 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("res came here "); // console.log(userId);
try { try {
const { products } = req.body; const { products } = req.body; // products: [{ SKU, openingInventory }]
// console.log(products);
// Fetch all products in the system (get _id, SKU, and name)
const allProducts = await Product.find({}, "_id SKU name"); const allProducts = await Product.find({}, "_id SKU name");
// Find existing stock data for the user
let stock = await RDStock.findOne({ userId }); let stock = await RDStock.findOne({ userId });
// If no products found in the request, return an error
if (!products || products.length === 0) { if (!products || products.length === 0) {
return res.status(400).json({ message: "No products provided." }); return res.status(400).json({ message: "No products provided." });
} }
const updatedProducts = []; const updatedProductsMap = new Map();
// Loop through the requested products and process them // Create a map of all requested updates for easy access by SKU
for (const reqProduct of products) { for (const reqProduct of products) {
const { SKU, openingInventory } = reqProduct; const { SKU, openingInventory } = reqProduct;
@ -800,41 +969,50 @@ export const createOrUpdateInventoryForRD = async (req, res) => {
continue; continue;
} }
// Find the product in existing PDStock (if any) // Prepare updated product data to be used later
const existingProductInStock = stock?.products.find( updatedProductsMap.set(SKU, {
(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, productid: productInSystem._id,
SKU: productInSystem.SKU, SKU: productInSystem.SKU,
productName: productInSystem.name, productName: productInSystem.name,
openingInventory: openingInventory || 0, openingInventory: openingInventory || 0,
Stock: openingInventory || 0, Stock: openingInventory || 0,
}; });
updatedProducts.push(newProductInStock);
} }
}
// console.log(updatedProducts);
if (stock) { if (stock) {
// Update existing stock entry // Create a map of existing products by SKU for easy lookup
stock.products = updatedProducts; const existingProductsMap = new Map();
stock.products.forEach((product) => {
existingProductsMap.set(product.SKU, product);
});
// Update only the products that need to be updated
const mergedProducts = stock.products.map((product) => {
if (updatedProductsMap.has(product.SKU)) {
// Update existing product with new values
const updatedProduct = updatedProductsMap.get(product.SKU);
return { ...product, ...updatedProduct };
}
return product; // Keep unchanged product as-is
});
// Add any new products that were not previously in stock
updatedProductsMap.forEach((updatedProduct, SKU) => {
if (!existingProductsMap.has(SKU)) {
mergedProducts.push(updatedProduct);
}
});
// Save the merged products list to the stock
stock.products = mergedProducts;
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 new stock entry if none exists
const newStock = new RDStock({ userId, products: updatedProducts }); const newStock = new RDStock({ userId, products: Array.from(updatedProductsMap.values()) });
await newStock.save(); await newStock.save();
return res return res
.status(201) .status(201)