From ddbde6207fdd8a4414fdeb929f361fafea7d5a60 Mon Sep 17 00:00:00 2001 From: Roshan Paudel Date: Sun, 13 Oct 2024 11:06:40 +0545 Subject: [PATCH] =?UTF-8?q?=F0=9F=91=8C=20IMPROVE:=20added=20books=20get?= =?UTF-8?q?=20route?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/app/sales/product/product.controller.ts | 6 ++++++ src/app/sales/product/product.routes.ts | 1 + src/app/sales/product/product.service.ts | 22 +++++++++++++++++++++ 3 files changed, 29 insertions(+) diff --git a/src/app/sales/product/product.controller.ts b/src/app/sales/product/product.controller.ts index f648f4d..8820de7 100644 --- a/src/app/sales/product/product.controller.ts +++ b/src/app/sales/product/product.controller.ts @@ -13,4 +13,10 @@ export class ProductController { await this.service.addNewProduct(req.body, user); return res.json({ message: 'Product created successfully' }); }); + + getAllProducts = asyncWrapper(async (req, res) => { + const user = req.userId; + const data = await this.service.getAllProducts(user); + return res.json({ message: 'Products fetched successfully', data }); + }); } diff --git a/src/app/sales/product/product.routes.ts b/src/app/sales/product/product.routes.ts index d24f241..800baef 100644 --- a/src/app/sales/product/product.routes.ts +++ b/src/app/sales/product/product.routes.ts @@ -13,6 +13,7 @@ class ProductRouter { } mountRoutes() { + this.router.get('/', this.controller.getAllProducts); this.router.post('/', this.controller.addnewProduct); } } diff --git a/src/app/sales/product/product.service.ts b/src/app/sales/product/product.service.ts index 8276273..5ffebe0 100644 --- a/src/app/sales/product/product.service.ts +++ b/src/app/sales/product/product.service.ts @@ -3,10 +3,32 @@ import { productSchema, TProductSchema } from '../../../schema/product.schema'; import { BadRequestError } from '../../../utils/exceptions'; export class ProductService { + async getAllProducts(user: string) { + const products = await ProductModel.find({ user }); + const productsWithTotalQty = products.map((product) => { + const totalQty = product.batches.reduce( + (sum, batch) => sum + batch.qty, + 0, + ); + + // Return the product object with the additional totalQty field + return { + ...product.toObject(), // Convert the product document to a plain JS object + totalQty, + }; + }); + + return productsWithTotalQty; + } + async addNewProduct(payload: TProductSchema, user: string) { const { data, success } = productSchema.safeParse(payload); if (!success) throw new BadRequestError('Invalid payload format'); + const existingProduct = await ProductModel.findOne({ name: data.name }); + console.log('EXISTING PRODUCT', existingProduct); + if (existingProduct) throw new BadRequestError('Product exist already'); + const batches = [ { batchNo: 1,