From be0f01bc1a5d9991804318804ec072a18902998a Mon Sep 17 00:00:00 2001 From: nicekid1 <86746988+nicekid1@users.noreply.github.com> Date: Wed, 1 Jan 2025 09:21:48 +0330 Subject: [PATCH] Add functionality to retrieve invoices by user in invoice module --- src/invoice/invoice.controller.ts | 20 ++++++++++++-------- src/invoice/invoice.service.ts | 26 ++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 8 deletions(-) diff --git a/src/invoice/invoice.controller.ts b/src/invoice/invoice.controller.ts index 868211a..5a3bf6b 100644 --- a/src/invoice/invoice.controller.ts +++ b/src/invoice/invoice.controller.ts @@ -1,13 +1,17 @@ -import { Controller, Get, Post, Body, Patch, Param, Delete } from '@nestjs/common'; -import { InvoiceService } from './invoice.service'; -import { Invoice } from './entities/invoice.entity'; +import { Controller, Get, Post, Body, Patch, Param, Delete } from "@nestjs/common"; +import { InvoiceService } from "./invoice.service"; +import { Invoice } from "./entities/invoice.entity"; -@Controller('invoice') +@Controller("invoice") export class InvoiceController { constructor(private readonly invoiceService: InvoiceService) {} - @Post('create') - async createInvoice(@Body() body:{userId:number, totalAmount:number}):Promise{ - const { userId, totalAmount} = body - return this.invoiceService.createInvoice(userId, totalAmount) + @Post("create") + async createInvoice(@Body() body: { userId: number; totalAmount: number }): Promise { + const { userId, totalAmount } = body; + return this.invoiceService.createInvoice(userId, totalAmount); + } + @Get(":userId") + async getInvoices(@Param("userId") userId: number): Promise { + return this.invoiceService.getInvoicesByUser(userId); } } diff --git a/src/invoice/invoice.service.ts b/src/invoice/invoice.service.ts index 46f72e8..e871aab 100644 --- a/src/invoice/invoice.service.ts +++ b/src/invoice/invoice.service.ts @@ -1,6 +1,7 @@ import { HttpException, HttpStatus, Injectable } from "@nestjs/common"; import { InjectModel } from "@nestjs/sequelize"; import { Invoice } from "./entities/invoice.entity"; +import { where } from "sequelize"; @Injectable() export class InvoiceService { @@ -23,4 +24,29 @@ export class InvoiceService { throw new HttpException("An error occurred while creating the invoice.", HttpStatus.INTERNAL_SERVER_ERROR); } } + async getInvoicesByUser(userId: number): Promise { + try { + if (!userId) { + throw new HttpException('User ID is required.', HttpStatus.BAD_REQUEST); + } + + const invoices = await this.invoiceModel.findAll({ + where: { userId }, + }); + + if (!invoices || invoices.length === 0) { + throw new HttpException('No invoices found for this user.', HttpStatus.NOT_FOUND); + } + + return invoices; + } catch (error) { + if (error instanceof HttpException) { + throw error; + } + throw new HttpException( + 'An error occurred while retrieving invoices.', + HttpStatus.INTERNAL_SERVER_ERROR, + ); + } + } }