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 { constructor(@InjectModel(Invoice) private readonly invoiceModel: typeof Invoice) {} async createInvoice(userId: number, totalAmount: number): Promise { try { if (!userId) { throw new HttpException("User id not found!", HttpStatus.BAD_REQUEST); } const newInvoice = await this.invoiceModel.create({ userId, totalAmount }); return newInvoice; } catch (error) { if (error instanceof HttpException) { throw error; } 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, ); } } }