443 lines
16 KiB
TypeScript
Executable File
443 lines
16 KiB
TypeScript
Executable File
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 { 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 { 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";
|
|
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()
|
|
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,
|
|
) {}
|
|
|
|
///********************************** */
|
|
|
|
async createInvoiceAdmin(createDto: CreateInvoiceDto) {
|
|
//
|
|
const invoiceItems = createDto.items.map((item) => {
|
|
return {
|
|
name: item.name,
|
|
count: item.count,
|
|
unitPrice: item.unitPrice,
|
|
discount: item.discount || 0,
|
|
totalPrice: item.unitPrice * item.count - (item.unitPrice * item.count * item.discount) / 100,
|
|
};
|
|
});
|
|
//
|
|
const totalPrice = invoiceItems.reduce((sum, item) => new Decimal(item.totalPrice).add(sum), new Decimal(0));
|
|
const tax = totalPrice.mul(0.1);
|
|
//
|
|
const dueDate = new Date();
|
|
dueDate.setDate(dueDate.getDate() + 5);
|
|
//
|
|
const invoice = this.invoiceRepository.create({
|
|
user: { id: createDto.userId },
|
|
totalPrice: totalPrice.toNumber(),
|
|
items: invoiceItems,
|
|
tax: tax.toNumber(),
|
|
dueDate,
|
|
});
|
|
//
|
|
await this.invoiceRepository.save(invoice);
|
|
//TODO: notify user
|
|
|
|
return {
|
|
message: InvoiceMessage.CREATED,
|
|
invoice,
|
|
};
|
|
}
|
|
|
|
//********************************** */
|
|
|
|
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);
|
|
|
|
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);
|
|
|
|
invoice.status = InvoiceStatus.APPROVED;
|
|
|
|
await this.invoiceRepository.save(invoice);
|
|
|
|
return {
|
|
message: InvoiceMessage.APPROVED,
|
|
invoice,
|
|
};
|
|
}
|
|
///********************************** */
|
|
|
|
async createInvoiceForSubscription(userId: string, plan: SubscriptionPlan, dueDate: Date, queryRunner: QueryRunner) {
|
|
const invoiceItems = [
|
|
{ name: plan.service.name, count: 1, unitPrice: plan.price, discount: 0, subscriptionPlan: plan, totalPrice: plan.price },
|
|
];
|
|
const invoice = queryRunner.manager.create(Invoice, {
|
|
totalPrice: plan.price,
|
|
user: { id: userId },
|
|
status: InvoiceStatus.PAID,
|
|
paidAt: new Date(),
|
|
dueDate,
|
|
items: invoiceItems,
|
|
});
|
|
//
|
|
await queryRunner.manager.save(Invoice, invoice);
|
|
return invoice;
|
|
}
|
|
|
|
///********************************** */
|
|
|
|
async getInvoices(queryDto: InvoicesSearchQueryDto) {
|
|
const [invoices, count] = await this.invoiceRepository.getInvoicesForAdmin(queryDto);
|
|
|
|
const usersWithInvoices = await this.invoiceRepository
|
|
.createQueryBuilder("invoice")
|
|
.leftJoinAndSelect("invoice.user", "user")
|
|
.select(["user.id", "user.firstName", "user.lastName", "user.email"])
|
|
.distinctOn(["user.id"])
|
|
.getMany();
|
|
|
|
return {
|
|
users: usersWithInvoices.map((inv) => inv.user),
|
|
invoices,
|
|
count,
|
|
paginate: true,
|
|
};
|
|
}
|
|
|
|
//*********************************** */
|
|
async getInvoiceById(invoiceId: string, isAdmin: boolean, userId: string) {
|
|
let invoice: Invoice | null;
|
|
|
|
if (isAdmin) {
|
|
invoice = await this.invoiceRepository.findOne({
|
|
where: { id: invoiceId },
|
|
relations: { items: { subscriptionPlan: true }, user: true },
|
|
});
|
|
} else {
|
|
invoice = await this.invoiceRepository.findOne({
|
|
where: { id: invoiceId, user: { id: userId } },
|
|
relations: { items: { subscriptionPlan: true } },
|
|
});
|
|
}
|
|
|
|
if (!invoice) throw new BadRequestException(InvoiceMessage.NOT_FOUND_BY_ID);
|
|
|
|
return {
|
|
invoice,
|
|
};
|
|
}
|
|
|
|
//*********************************** */
|
|
|
|
async getUserInvoices(queryDto: UserInvoicesSearchQueryDto, userId: string) {
|
|
const { limit, skip } = PaginationUtils(queryDto);
|
|
|
|
const queryBuilder = this.invoiceRepository.createQueryBuilder("invoice");
|
|
|
|
queryBuilder
|
|
.andWhere("invoice.user.id = :userId", { userId: userId })
|
|
.leftJoinAndSelect("invoice.items", "items")
|
|
.leftJoinAndSelect("items.subscriptionPlan", "subscriptionPlan", "subscriptionPlan.id IS NOT NULL")
|
|
.leftJoinAndSelect("subscriptionPlan.service", "service", "subscriptionPlan.id IS NOT NULL");
|
|
|
|
if (queryDto.status) {
|
|
queryBuilder.andWhere("invoice.status = :status", { status: queryDto.status });
|
|
}
|
|
|
|
queryBuilder.orderBy("invoice.createdAt", "DESC").skip(skip).take(limit);
|
|
|
|
const [invoices, count] = await queryBuilder.getManyAndCount();
|
|
|
|
return {
|
|
invoices,
|
|
count,
|
|
paginate: true,
|
|
};
|
|
}
|
|
|
|
//*********************************** */
|
|
|
|
async payInvoice(invoiceId: string, userId: string) {
|
|
const queryRunner = this.dataSource.createQueryRunner();
|
|
await queryRunner.connect();
|
|
await queryRunner.startTransaction();
|
|
try {
|
|
const user = await this.usersService.findOneByIdWithQueryRunner(userId, queryRunner);
|
|
|
|
const invoice = await this.getPendingInvoiceByIdWithQueryRunner(invoiceId, user.id, queryRunner);
|
|
|
|
if (invoice.status === InvoiceStatus.REJECTED) throw new BadRequestException(InvoiceMessage.INVOICE_IS_REJECTED);
|
|
if (invoice.status === InvoiceStatus.EXPIRED) throw new BadRequestException(InvoiceMessage.INVOICE_IS_OVERDUE);
|
|
if (invoice.status === InvoiceStatus.PAID) throw new BadRequestException(InvoiceMessage.INVOICE_ALREADY_PAID);
|
|
if (invoice.status !== InvoiceStatus.APPROVED) throw new BadRequestException(InvoiceMessage.INVOICE_CAN_NOT_PAID);
|
|
|
|
const userWallet = await this.walletsService.getWalletByUserId(user.id, queryRunner);
|
|
|
|
if (new Decimal(userWallet.balance).lessThan(invoice.totalPrice)) throw new BadRequestException(WalletMessage.INSUFFICIENT_BALANCE);
|
|
|
|
userWallet.balance = new Decimal(userWallet.balance).sub(invoice.totalPrice);
|
|
|
|
await queryRunner.manager.save(Wallet, userWallet);
|
|
|
|
await this.walletsService.createInvoiceTransaction(invoice.totalPrice, userWallet.id, queryRunner);
|
|
|
|
invoice.status = InvoiceStatus.PAID;
|
|
invoice.paidAt = new Date();
|
|
|
|
await queryRunner.manager.save(Invoice, invoice);
|
|
console.log(invoice);
|
|
await queryRunner.commitTransaction();
|
|
return {
|
|
message: InvoiceMessage.INVOICE_PAID,
|
|
invoice,
|
|
};
|
|
} catch (error) {
|
|
await queryRunner.rollbackTransaction();
|
|
throw error;
|
|
} finally {
|
|
await queryRunner.release();
|
|
}
|
|
}
|
|
|
|
//*********************************** */
|
|
|
|
async getPendingInvoiceByIdWithQueryRunner(invoiceId: string, userId: string, queryRunner: QueryRunner) {
|
|
const invoice = await queryRunner.manager.findOneBy(Invoice, { user: { id: userId }, status: InvoiceStatus.PENDING, id: invoiceId });
|
|
if (!invoice) throw new BadRequestException(InvoiceMessage.NOT_FOUND_BY_ID);
|
|
return invoice;
|
|
}
|
|
|
|
//*********************************** */
|
|
|
|
async applyDiscount(invoiceId: string, applyDiscountDto: ApplyDiscountDto, userId: string) {
|
|
const invoice = await this.invoiceRepository.findOneBy({ id: invoiceId, status: InvoiceStatus.PENDING });
|
|
if (!invoice) throw new BadRequestException(InvoiceMessage.NOT_FOUND_BY_ID);
|
|
|
|
const discount = await this.discountRepository.findOne({
|
|
where: { code: applyDiscountDto.discountCode, isActive: true },
|
|
relations: ["subscriptionPlans", "users"],
|
|
});
|
|
if (!discount) {
|
|
throw new BadRequestException(DiscountMessage.NOT_FOUND);
|
|
}
|
|
|
|
const hasUsedDiscount = await this.hasUserUsedDiscount(userId, discount.id);
|
|
if (hasUsedDiscount) throw new BadRequestException(DiscountMessage.ALREADY_USED);
|
|
|
|
if (discount.subscriptionPlans && discount.subscriptionPlans.length > 0) {
|
|
const isApplicable = invoice.items.some((item) => {
|
|
const subscriptionPlan = item.subscriptionPlan;
|
|
if (!subscriptionPlan) return false;
|
|
return discount.subscriptionPlans.some((plan) => plan.id === subscriptionPlan.id);
|
|
});
|
|
if (!isApplicable) {
|
|
throw new BadRequestException(DiscountMessage.CAN_NOT_APPLICABLE);
|
|
}
|
|
}
|
|
|
|
if (discount.users && discount.users.length > 0) {
|
|
if (!discount.users.some((user) => user.id === userId)) {
|
|
throw new BadRequestException(DiscountMessage.CAN_NOT_APPLICABLE);
|
|
}
|
|
}
|
|
|
|
const discountAmount =
|
|
discount.calculationType === "PERCENTAGE"
|
|
? new Decimal(invoice.totalPrice).mul(discount.amount).div(100)
|
|
: new Decimal(discount.amount);
|
|
|
|
invoice.totalPrice = new Decimal(invoice.totalPrice).minus(discountAmount);
|
|
await this.invoiceRepository.save(invoice);
|
|
|
|
const usageDiscount = this.usageDiscountRepository.create({
|
|
discount,
|
|
users: [{ id: userId }],
|
|
usageDate: new Date(),
|
|
});
|
|
|
|
await this.usageDiscountRepository.save(usageDiscount);
|
|
|
|
return {
|
|
message: InvoiceMessage.DISCOUNT_APPLIED,
|
|
invoice,
|
|
};
|
|
}
|
|
|
|
//*********************************** */
|
|
|
|
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 });
|
|
if (!invoice) throw new BadRequestException(InvoiceMessage.NOT_FOUND_BY_ID);
|
|
|
|
// Find the usage discount associated with the user and invoice
|
|
const usage = await this.usageDiscountRepository.findOne({
|
|
where: {
|
|
users: { id: userId },
|
|
discount: { invoice: { id: invoice.id } },
|
|
},
|
|
relations: {
|
|
discount: true,
|
|
users: true,
|
|
},
|
|
});
|
|
console.log(usage);
|
|
if (!usage) throw new BadRequestException(DiscountMessage.NOT_FOUND);
|
|
|
|
// Find the discount associated with the usage
|
|
const discount = await this.discountRepository.findOneBy({ id: usage.discount.id });
|
|
if (!discount) throw new BadRequestException(DiscountMessage.NOT_FOUND);
|
|
|
|
// Calculate the discount amount to be removed from the invoice
|
|
const discountAmount =
|
|
discount.calculationType === "PERCENTAGE"
|
|
? new Decimal(invoice.totalPrice).mul(discount.amount).div(100)
|
|
: new Decimal(discount.amount);
|
|
|
|
// Update the invoice's total price by adding the discount amount (effectively removing the discount)
|
|
invoice.totalPrice = new Decimal(invoice.totalPrice).add(discountAmount);
|
|
await this.invoiceRepository.save(invoice);
|
|
|
|
// Delete the usage discount record
|
|
await this.usageDiscountRepository.delete(usage.id);
|
|
|
|
return {
|
|
message: InvoiceMessage.DISCOUNT_CANCELLED,
|
|
invoice,
|
|
};
|
|
}
|
|
|
|
//*********************************** */
|
|
|
|
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: {
|
|
users: {
|
|
id: userId,
|
|
},
|
|
discount: {
|
|
id: discountId,
|
|
},
|
|
},
|
|
});
|
|
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);
|
|
// }
|
|
}
|