chore: approve invoice, reports for admin dashboard

This commit is contained in:
Matin
2025-02-22 16:04:26 +03:30
parent e711ffd3ee
commit 3b0120d338
12 changed files with 448 additions and 8 deletions
+13 -2
View File
@@ -10,6 +10,8 @@ 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 { PermissionEnum } from "../users/enums/permission.enum";
@Controller("invoices")
@@ -58,11 +60,20 @@ export class InvoicesController {
/**************************************** */
@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);
}
/**************************************** */
@ApiOperation({ summary: "approve invoice by user" })
@AuthGuards()
@Patch(":id/approve")
approveInvoiceByUser(@Param() paramDto: ParamDto, @UserDec("id") userId: string) {
return this.invoiceService.approveInvoiceByUser(paramDto.id, userId);
approveInvoiceByUser(@Param() paramDto: ParamDto, @UserDec("id") userId: string, @Body() verifyOtpDto: VerifyOtpDto) {
return this.invoiceService.approveInvoiceByUser(paramDto.id, userId, verifyOtpDto);
}
/**************************************** */
+2 -1
View File
@@ -11,10 +11,11 @@ import { UsageDiscount } from "../discounts/entities/usage-discount.entity";
import { DiscountRepository } from "../discounts/repositories/discount.repository";
import { UsageDiscountRepository } from "../discounts/repositories/usage-discount.repository";
import { UsersModule } from "../users/users.module";
import { UtilsModule } from "../utils/utils.module";
import { WalletsModule } from "../wallets/wallets.module";
@Module({
imports: [TypeOrmModule.forFeature([Invoice, InvoiceItem, Discount, UsageDiscount]), UsersModule, WalletsModule],
imports: [TypeOrmModule.forFeature([Invoice, InvoiceItem, Discount, UsageDiscount]), UsersModule, WalletsModule, UtilsModule],
providers: [InvoicesService, InvoicesRepository, DiscountRepository, UsageDiscountRepository],
controllers: [InvoicesController],
exports: [InvoicesService],
@@ -1,16 +1,20 @@
import { BadRequestException, Injectable } from "@nestjs/common";
import { BadRequestException, Injectable, Logger } from "@nestjs/common";
// eslint-disable-next-line import/no-named-as-default
import dayjs from "dayjs";
// eslint-disable-next-line import/no-named-as-default
import Decimal from "decimal.js";
import { DataSource, QueryRunner } from "typeorm";
import { Between, DataSource, QueryRunner } from "typeorm";
import { DiscountMessage, InvoiceMessage, WalletMessage } from "../../../common/enums/message.enum";
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 { DiscountRepository } from "../../discounts/repositories/discount.repository";
import { UsageDiscountRepository } from "../../discounts/repositories/usage-discount.repository";
import { SubscriptionPlan } from "../../subscriptions/entities/subscription.entity";
import { UsersService } from "../../users/providers/users.service";
import { OTPService } from "../../utils/providers/otp.service";
import { PaginationUtils } from "../../utils/providers/pagination.utils";
import { SmsService } from "../../utils/providers/sms.service";
import { Wallet } from "../../wallets/entities/wallet.entity";
import { WalletsService } from "../../wallets/providers/wallets.service";
import { ApplyDiscountDto } from "../DTO/apply-discount-invoice.dto";
@@ -23,12 +27,16 @@ import { InvoicesRepository } from "../repositories/invoices.repository";
@Injectable()
export class InvoicesService {
private readonly logger = new Logger(InvoicesService.name);
constructor(
private readonly invoiceRepository: InvoicesRepository,
private readonly discountRepository: DiscountRepository,
private readonly usageDiscountRepository: UsageDiscountRepository,
private readonly usersService: UsersService,
private readonly walletsService: WalletsService,
private readonly otpService: OTPService,
private readonly smsService: SmsService,
private readonly dataSource: DataSource,
// private readonly invoiceItemsRepository: InvoiceItemsRepository,
) {}
@@ -69,9 +77,50 @@ export class InvoicesService {
invoice,
};
}
///********************************** */
async approveInvoiceByUser(invoiceId: string, userId: string) {
//********************************** */
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);
const invoice = await this.invoiceRepository.findOneBy({ id: invoiceId, user: { id: userId } });
if (!invoice) throw new BadRequestException(InvoiceMessage.NOT_FOUND_BY_ID);
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);
if (invoice.status !== InvoiceStatus.PENDING) throw new BadRequestException(InvoiceMessage.INVOICE_CAN_NOT_APPROVED);
const existCode = await this.otpService.checkExistOtp(phone, "LOGIN");
if (existCode) {
return {
message: AuthMessage.OTP_ALREADY_SENT,
ttlSecond: existCode,
};
}
const otpCode = await this.otpService.generateAndSetInCache(phone, "LOGIN");
//
await this.smsService.sendSmsVerifyCode(phone, otpCode);
this.logger.debug(`OTP sent to ${phone}: ${otpCode}`);
return {
message: AuthMessage.OTP_SENT,
otpCode,
};
}
//********************************** */
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);
const invoice = await this.invoiceRepository.findOneBy({ id: invoiceId, user: { id: userId } });
if (!invoice) throw new BadRequestException(InvoiceMessage.NOT_FOUND_BY_ID);
@@ -309,6 +358,8 @@ export class InvoicesService {
};
}
//*********************************** */
async cancelDiscount(invoiceId: string, userId: string) {
// Find the invoice by ID and ensure it is in a PENDING status
const invoice = await this.invoiceRepository.findOneBy({ id: invoiceId, status: InvoiceStatus.PENDING });
@@ -351,6 +402,19 @@ export class InvoicesService {
};
}
//*********************************** */
async getInvoicesCount() {
const count = await this.invoiceRepository.count({
where: {
createdAt: Between(new Date(new Date().setHours(0, 0, 0, 0)), new Date(new Date().setHours(23, 59, 59, 999))),
},
});
return count;
}
//*********************************** */
private async hasUserUsedDiscount(userId: string, discountId: string): Promise<boolean> {
const usage = await this.usageDiscountRepository.findOne({
where: {
@@ -365,6 +429,23 @@ 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);