refactor: the user setting and change to be cateogry based
This commit is contained in:
@@ -11,6 +11,9 @@ import { InvoiceStatus } from "../enums/invoice-status.enum";
|
||||
|
||||
@Entity()
|
||||
export class Invoice extends BaseEntity {
|
||||
@Column({ type: "int", generated: "identity", insert: false })
|
||||
numericId: number;
|
||||
|
||||
@ManyToOne(() => User, (user) => user.invoices, { nullable: true, onDelete: "RESTRICT" })
|
||||
user: User;
|
||||
|
||||
|
||||
@@ -10,24 +10,22 @@ import { Pagination } from "../../common/decorators/pagination.decorator";
|
||||
import { PermissionsDec } from "../../common/decorators/permission.decorator";
|
||||
import { UserDec } from "../../common/decorators/user.decorator";
|
||||
import { ParamDto } from "../../common/DTO/param.dto";
|
||||
import { RequestOtpDto } from "../auth/DTO/request-otp.dto";
|
||||
import { VerifyOtpDto } from "../auth/DTO/verify-otp.dto";
|
||||
import { VerifyOtpWithUserId } from "../auth/DTO/verify-otp.dto";
|
||||
import { PermissionEnum } from "../users/enums/permission.enum";
|
||||
|
||||
@Controller("invoices")
|
||||
@AuthGuards()
|
||||
export class InvoicesController {
|
||||
constructor(private readonly invoiceService: InvoicesService) {}
|
||||
|
||||
@ApiOperation({ summary: "create an invoice ==> admin route" })
|
||||
@PermissionsDec(PermissionEnum.INVOICES)
|
||||
@AuthGuards()
|
||||
@Post()
|
||||
createInvoice(@Body() createDto: CreateInvoiceDto) {
|
||||
return this.invoiceService.createInvoiceAdmin(createDto);
|
||||
}
|
||||
|
||||
@ApiOperation({ summary: "get all invoices ==> admin route" })
|
||||
@AuthGuards()
|
||||
@PermissionsDec(PermissionEnum.INVOICES)
|
||||
@Pagination()
|
||||
@Get()
|
||||
@@ -36,7 +34,6 @@ export class InvoicesController {
|
||||
}
|
||||
|
||||
@ApiOperation({ summary: "get all user invoices" })
|
||||
@AuthGuards()
|
||||
@Pagination()
|
||||
@Get("user")
|
||||
getUserInvoices(@Query() queryDto: UserInvoicesSearchQueryDto, @UserDec("id") userId: string) {
|
||||
@@ -44,42 +41,36 @@ export class InvoicesController {
|
||||
}
|
||||
|
||||
@ApiOperation({ summary: "get single invoice by Id " })
|
||||
@AuthGuards()
|
||||
@Get(":id")
|
||||
getInvoiceById(@Param() paramDto: ParamDto, @UserDec("isAdmin") isAdmin: boolean, @UserDec("id") userId: string) {
|
||||
return this.invoiceService.getInvoiceById(paramDto.id, isAdmin, userId);
|
||||
}
|
||||
|
||||
@ApiOperation({ summary: "approve request invoice by user" })
|
||||
@AuthGuards()
|
||||
@Post(":id/approve/request")
|
||||
approveRequestInvoiceByUser(@Param() paramDto: ParamDto, @UserDec("id") userId: string, @Body() updateDto: RequestOtpDto) {
|
||||
return this.invoiceService.approveRequest(paramDto.id, userId, updateDto);
|
||||
approveRequestInvoiceByUser(@Param() paramDto: ParamDto, @UserDec("id") userId: string) {
|
||||
return this.invoiceService.approveInvoiceRequest(paramDto.id, userId);
|
||||
}
|
||||
|
||||
@ApiOperation({ summary: "approve invoice by user" })
|
||||
@AuthGuards()
|
||||
@Patch(":id/approve")
|
||||
approveInvoiceByUser(@Param() paramDto: ParamDto, @UserDec("id") userId: string, @Body() verifyOtpDto: VerifyOtpDto) {
|
||||
approveInvoiceByUser(@Param() paramDto: ParamDto, @UserDec("id") userId: string, @Body() verifyOtpDto: VerifyOtpWithUserId) {
|
||||
return this.invoiceService.approveInvoiceByUser(paramDto.id, userId, verifyOtpDto);
|
||||
}
|
||||
|
||||
@ApiOperation({ summary: "apply discount on invoice by user" })
|
||||
@AuthGuards()
|
||||
@Post(":id/apply-discount")
|
||||
async applyDiscount(@Param() paramDto: ParamDto, @Body() applyDiscountDto: ApplyDiscountDto, @UserDec("id") userId: string) {
|
||||
return this.invoiceService.applyDiscount(paramDto.id, applyDiscountDto, userId);
|
||||
}
|
||||
|
||||
@ApiOperation({ summary: "cancel discount by user" })
|
||||
@AuthGuards()
|
||||
@Post(":id/cancel-discount")
|
||||
cancelDiscount(@Param() paramDto: ParamDto, @UserDec("id") userId: string) {
|
||||
return this.invoiceService.cancelDiscount(paramDto.id, userId);
|
||||
}
|
||||
|
||||
@ApiOperation({ summary: "pay invoice by user" })
|
||||
@AuthGuards()
|
||||
@Post(":id/pay")
|
||||
async payInvoice(@Param() paramDto: ParamDto, @UserDec("id") userId: string) {
|
||||
return this.invoiceService.payInvoice(paramDto.id, userId);
|
||||
|
||||
@@ -5,9 +5,8 @@ import dayjs from "dayjs";
|
||||
import Decimal from "decimal.js";
|
||||
import { Between, DataSource, QueryRunner } from "typeorm";
|
||||
|
||||
import { AuthMessage, DiscountMessage, InvoiceMessage, UserMessage, WalletMessage } from "../../../common/enums/message.enum";
|
||||
import { RequestOtpDto } from "../../auth/DTO/request-otp.dto";
|
||||
import { VerifyOtpDto } from "../../auth/DTO/verify-otp.dto";
|
||||
import { AuthMessage, DiscountMessage, InvoiceMessage, WalletMessage } from "../../../common/enums/message.enum";
|
||||
import { VerifyOtpWithUserId } from "../../auth/DTO/verify-otp.dto";
|
||||
import { DiscountRepository } from "../../discounts/repositories/discount.repository";
|
||||
import { UsageDiscountRepository } from "../../discounts/repositories/usage-discount.repository";
|
||||
import { SubscriptionPlan } from "../../subscriptions/entities/subscription.entity";
|
||||
@@ -22,7 +21,6 @@ import { CreateInvoiceDto } from "../DTO/create-invoice.dto";
|
||||
import { InvoicesSearchQueryDto, UserInvoicesSearchQueryDto } from "../DTO/invoices-search-query.dto";
|
||||
import { Invoice } from "../entities/invoice.entity";
|
||||
import { InvoiceStatus } from "../enums/invoice-status.enum";
|
||||
// import { InvoiceItemsRepository } from "../repositories/invoice-items.repository";
|
||||
import { InvoicesRepository } from "../repositories/invoices.repository";
|
||||
|
||||
@Injectable()
|
||||
@@ -38,7 +36,6 @@ export class InvoicesService {
|
||||
private readonly otpService: OTPService,
|
||||
private readonly smsService: SmsService,
|
||||
private readonly dataSource: DataSource,
|
||||
// private readonly invoiceItemsRepository: InvoiceItemsRepository,
|
||||
) {}
|
||||
|
||||
///********************************** */
|
||||
@@ -80,12 +77,10 @@ export class InvoicesService {
|
||||
|
||||
//********************************** */
|
||||
|
||||
async approveRequest(invoiceId: string, userId: string, requestOtpDto: RequestOtpDto) {
|
||||
const { phone } = requestOtpDto;
|
||||
const user = await this.usersService.findOneById(userId);
|
||||
if (!user) throw new BadRequestException(UserMessage.USER_NOT_FOUND);
|
||||
async approveInvoiceRequest(invoiceId: string, userId: string) {
|
||||
const { user } = await this.usersService.findOneById(userId);
|
||||
|
||||
const invoice = await this.invoiceRepository.findOneBy({ id: invoiceId, user: { id: userId } });
|
||||
const invoice = await this.invoiceRepository.findOne({ where: { id: invoiceId, user: { id: userId } }, relations: { items: true } });
|
||||
if (!invoice) throw new BadRequestException(InvoiceMessage.NOT_FOUND_BY_ID);
|
||||
|
||||
if (invoice.status === InvoiceStatus.APPROVED) throw new BadRequestException(InvoiceMessage.ALREADY_APPROVED);
|
||||
@@ -94,7 +89,7 @@ export class InvoicesService {
|
||||
|
||||
if (invoice.status !== InvoiceStatus.PENDING) throw new BadRequestException(InvoiceMessage.INVOICE_CAN_NOT_APPROVED);
|
||||
|
||||
const existCode = await this.otpService.checkExistOtp(phone, "LOGIN");
|
||||
const existCode = await this.otpService.checkExistOtp(user.phone, "INVOICE_VERIFY");
|
||||
if (existCode) {
|
||||
return {
|
||||
message: AuthMessage.OTP_ALREADY_SENT,
|
||||
@@ -102,10 +97,11 @@ export class InvoicesService {
|
||||
};
|
||||
}
|
||||
|
||||
const otpCode = await this.otpService.generateAndSetInCache(phone, "LOGIN");
|
||||
const otpCode = await this.otpService.generateAndSetInCache(user.phone, "INVOICE_VERIFY");
|
||||
const items = invoice.items.map((item) => item.name).join(", ");
|
||||
//
|
||||
await this.smsService.sendSmsVerifyCode(phone, otpCode);
|
||||
this.logger.debug(`OTP sent to ${phone}: ${otpCode}`);
|
||||
await this.smsService.sendInvoiceVerifyCode(user.phone, otpCode, invoice.numericId, new Decimal(invoice.totalPrice).toNumber(), items);
|
||||
this.logger.debug(`OTP sent to ${user.phone}: ${otpCode}`);
|
||||
|
||||
return {
|
||||
message: AuthMessage.OTP_SENT,
|
||||
@@ -115,15 +111,18 @@ export class InvoicesService {
|
||||
|
||||
//********************************** */
|
||||
|
||||
async approveInvoiceByUser(invoiceId: string, userId: string, verifyOtpDto: VerifyOtpDto) {
|
||||
const { code, phone } = verifyOtpDto;
|
||||
|
||||
const user = await this.checkUserVerifyCredentialWithPhone(phone, code, userId);
|
||||
if (!user) throw new BadRequestException(InvoiceMessage.INVOICE_CAN_NOT_APPROVED);
|
||||
async approveInvoiceByUser(invoiceId: string, userId: string, verifyOtpDto: VerifyOtpWithUserId) {
|
||||
const { code } = verifyOtpDto;
|
||||
|
||||
const invoice = await this.invoiceRepository.findOneBy({ id: invoiceId, user: { id: userId } });
|
||||
if (!invoice) throw new BadRequestException(InvoiceMessage.NOT_FOUND_BY_ID);
|
||||
|
||||
const { user } = await this.usersService.findOneById(userId);
|
||||
|
||||
const isValid = await this.otpService.verifyOtp(user.phone, code, "INVOICE_VERIFY");
|
||||
if (!isValid) throw new BadRequestException(AuthMessage.INVALID_OTP);
|
||||
|
||||
if (invoice.status === InvoiceStatus.REJECTED) throw new BadRequestException(InvoiceMessage.INVOICE_IS_REJECTED);
|
||||
if (invoice.status === InvoiceStatus.APPROVED) throw new BadRequestException(InvoiceMessage.ALREADY_APPROVED);
|
||||
if (invoice.status === InvoiceStatus.PAID) throw new BadRequestException(InvoiceMessage.INVOICE_ALREADY_PAID);
|
||||
if (dayjs().isAfter(invoice.dueDate)) throw new BadRequestException(InvoiceMessage.INVOICE_IS_OVERDUE);
|
||||
@@ -407,36 +406,4 @@ export class InvoicesService {
|
||||
});
|
||||
return !!usage;
|
||||
}
|
||||
|
||||
//*********************************** */
|
||||
|
||||
private async checkUserVerifyCredentialWithPhone(phone: string, otpCode: string, userId: string) {
|
||||
//TODO: Change key from LOGIN to something else
|
||||
const isValid = await this.otpService.verifyOtp(phone, otpCode, "LOGIN");
|
||||
if (!isValid) throw new BadRequestException(AuthMessage.INVALID_OTP);
|
||||
|
||||
await this.otpService.delOtpFormCache(phone, "LOGIN");
|
||||
|
||||
const { user } = await this.usersService.findOneById(userId);
|
||||
if (!user) throw new BadRequestException(UserMessage.USER_NOT_FOUND);
|
||||
|
||||
return user;
|
||||
}
|
||||
|
||||
//*********************************** */
|
||||
|
||||
// async calculateFinalPrice(invoiceId: string): Promise<Decimal> {
|
||||
// const invoice = await this.invoiceRepository.findOneBy({ id: invoiceId });
|
||||
// if (!invoice) throw new BadRequestException(InvoiceMessage.NOT_FOUND_BY_ID);
|
||||
|
||||
// let discountValue = new Decimal(0);
|
||||
// if (invoice.discount) {
|
||||
// if (invoice.discount.calculationType === "PERCENTAGE") {
|
||||
// discountValue = invoice.totalPrice.mul(invoice.discount.amount).div(100);
|
||||
// } else if (invoice.discount.calculationType === "FIXED") {
|
||||
// discountValue = new Decimal(invoice.discount.amount);
|
||||
// }
|
||||
// }
|
||||
// return invoice.totalPrice.minus(discountValue);
|
||||
// }
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user