You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
52 lines
1.5 KiB
52 lines
1.5 KiB
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<Invoice> { |
|
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<Invoice[]> { |
|
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, |
|
); |
|
} |
|
} |
|
}
|
|
|