const e = require("express"); const express = require("express"); const SellBuy = require("../mongoose/models/sellBuy"); const sellAndBuyRouter = new express.Router(); // Route to add a new product sellAndBuyRouter.post("/sellProduct", async (req, res) => { try { const { productName, costPrice } = req.body; // Validation if (!productName || productName.length < 4) { return res.status(400).send({ error: "product name should have minimum of four characters", }); } if (costPrice <= 0) { return res.status(400).send({ error: "cost price value cannot be zero or negative value", }); } const product = new SellBuy({ productName, costPrice }); await product.save(); res.status(201).send({ message: "Product Added" }); } catch (e) { res.status(400).send({ error: "Failed to save product" }); } }); // Route to update a product's sold price sellAndBuyRouter.patch("/sellProduct/:id", async (req, res) => { try { const { soldPrice } = req.body; if (soldPrice <= 0) { return res.status(400).send({ error: "sold price value cannot be zero or negative value", }); } const product = await SellBuy.findById(req.params.id); if (!product) { return res.status(400).send({ error: "Product not found" }); } product.soldPrice = soldPrice; await product.save(); res.status(200).send({ message: "Updated Successfully" }); } catch (e) { res.status(400).send({ error: "Failed to update product" }); } }); // Route to get all products or filtered/sorted data sellAndBuyRouter.get("/sellProduct", async (req, res) => { try { let query = {}; if (req.query.product) { query.productName = req.query.product; } let products = await SellBuy.find(query); if (req.query.sortBy) { switch (req.query.sortBy) { case "lowerCostPrice": products = products.sort((a, b) => a.costPrice - b.costPrice); break; case "higherCostPrice": products = products.sort((a, b) => b.costPrice - a.costPrice); break; case "lowerSoldPrice": products = products.sort((a, b) => (a.soldPrice || 0) - (b.soldPrice || 0)); break; case "higherSoldPrice": products = products.sort((a, b) => (b.soldPrice || 0) - (a.soldPrice || 0)); break; } } res.status(200).send(products); } catch (e) { res.status(400).send({ error: "Failed to fetch products" }); } }); // Route to delete a product sellAndBuyRouter.delete("/sellProduct/:id", async (req, res) => { try { const product = await SellBuy.findByIdAndDelete(req.params.id); if (!product) { return res.status(404).send({ error: "Product not found" }); } res.status(200).send({ message: "Deleted successfully" }); } catch (e) { res.status(400).send({ error: "Failed to delete product" }); } }); module.exports = sellAndBuyRouter;