diff --git a/app.js b/app.js index df86780..6f12e23 100644 --- a/app.js +++ b/app.js @@ -202,6 +202,8 @@ import RDOrderRoute from "./resources/RD_Ordes/rdOrderRoutes.js" import TaskRoute from "./resources/Task/TaskRoute.js"; // visit RD and PD import VisitRDandPDRoute from "./resources/VisitRD&PD/VisitRD&PDRoute.js"; +//Stock +import Stock from "./resources/Stock/PdStockRoute.js"; app.use("/api/v1", user); //Product @@ -293,7 +295,8 @@ app.use("/api", VisitRDandPDRoute); //short urls // app.use("/api/shorturl", ShortUrlRouter); //Support - +//Stock +app.use("/api", Stock); // Email CMS // app.use("/api", RegisterEmail); export default app; diff --git a/resources/PD_Orders/pdOrderController.js b/resources/PD_Orders/pdOrderController.js index 1626dc8..93b93a6 100644 --- a/resources/PD_Orders/pdOrderController.js +++ b/resources/PD_Orders/pdOrderController.js @@ -2,7 +2,7 @@ import mongoose from "mongoose"; import { PdOrder } from "./pdOrderModal.js"; import sendEmail from "../../Utils/sendEmail.js"; import { Invoice } from "./invoiceModel.js"; - +import { PDStock } from "../Stock/PdStockModel.js"; // Controller for placing an order export const createOrder = async (req, res) => { try { @@ -1067,7 +1067,6 @@ export const updateCourierStatusToDelivered = async (req, res) => { select: "email", }, }); - if (!invoice) { return res.status(404).json({ error: "Invoice not found" }); } @@ -1088,7 +1087,44 @@ export const updateCourierStatusToDelivered = async (req, res) => { order.status = "delivered"; await order.save(); } + // Get the userId from the order's addedBy + const userId = order?.addedBy?._id; + if (!userId) { + return res.status(400).json({ error: "User not found for the order" }); + } + // Check if PDStock exists for the user + let pdStock = await PDStock.findOne({ userId }); + + if (!pdStock) { + // If no stock record exists, create a new one + pdStock = new PDStock({ + userId, + products: [], // Initialize with empty products array + }); + } + // Iterate over each item in the invoice + for (let item of invoice.items) { + const { productId, processquantity } = item; + + // Check if the product already exists in the PDStock for the user + const existingProduct = pdStock.products.find( + (p) => p.productid.toString() === productId.toString() + ); + + if (existingProduct) { + // If the product exists, update the stock by adding the processquantity + existingProduct.Stock += processquantity; + } else { + // If the product doesn't exist, add a new entry for the product + pdStock.products.push({ + productid: productId, + Stock: processquantity, + }); + } + } + // Save the updated PDStock + await pdStock.save(); // Format the current date for display const formattedDate = formatDate(new Date()); diff --git a/resources/Stock/PdStockController.js b/resources/Stock/PdStockController.js new file mode 100644 index 0000000..0aebe55 --- /dev/null +++ b/resources/Stock/PdStockController.js @@ -0,0 +1,103 @@ +import mongoose from "mongoose"; +import { PDStock } from "./PdStockModel.js"; +import { Product } from "../Products/ProductModel.js"; + +export const getProductsAndStockByUser = async (req, res) => { + try { + const { userId } = req.params; + + // Pagination parameters + const PAGE_SIZE = parseInt(req.query.show) || 10; + const page = parseInt(req.query.page) || 1; + const skip = (page - 1) * PAGE_SIZE; + + // 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 PDStock data and products concurrently + const [userStock, products] = await Promise.all([ + PDStock.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, + }, + }, + { $skip: skip }, + { $limit: PAGE_SIZE }, + ]), + ]); + + // 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, + totalPages: Math.ceil(total / PAGE_SIZE), + currentPage: page, + 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", + }); + } +}; + diff --git a/resources/Stock/PdStockModel.js b/resources/Stock/PdStockModel.js new file mode 100644 index 0000000..689c73e --- /dev/null +++ b/resources/Stock/PdStockModel.js @@ -0,0 +1,26 @@ +import mongoose from 'mongoose'; + +// Define Product record schema +const ProductRecordSchema = new mongoose.Schema({ + productid: { + type: mongoose.Schema.Types.ObjectId, + ref: 'Product', + required: true, + }, + Stock: { + type: Number, + default: 0, + }, +}); + +// Define main Stock schema +const StockSchema = new mongoose.Schema({ + userId: { + type: mongoose.Schema.Types.ObjectId, + refPath: 'User', + required: true, + }, + products: [ProductRecordSchema], +}, { timestamps: true, versionKey: false }); + +export const PDStock = mongoose.model('PDStock', StockSchema); diff --git a/resources/Stock/PdStockRoute.js b/resources/Stock/PdStockRoute.js new file mode 100644 index 0000000..d49a778 --- /dev/null +++ b/resources/Stock/PdStockRoute.js @@ -0,0 +1,12 @@ +import express from "express"; +import { getProductsAndStockByUser } from "./PdStockController.js"; +import { authorizeRoles, isAuthenticatedUser } from "../../middlewares/auth.js"; +const router = express.Router(); + +router.get( + "/pd/stock/:userId", + isAuthenticatedUser, + authorizeRoles("admin"), + getProductsAndStockByUser +); +export default router;