chore: discount module
This commit is contained in:
@@ -0,0 +1,13 @@
|
||||
import { IsNotEmpty, IsString } from "class-validator";
|
||||
|
||||
import { DiscountMessage } from "../../../common/enums/message.enum";
|
||||
|
||||
export class ApplyDiscountDto {
|
||||
@IsString({ message: DiscountMessage.INVOICE_ID_STRING })
|
||||
@IsNotEmpty({ message: DiscountMessage.INVOICE_ID_REQUIRED })
|
||||
invoiceId: string;
|
||||
|
||||
@IsString({ message: DiscountMessage.DISCOUNT_CODE_STRING })
|
||||
@IsNotEmpty({ message: DiscountMessage.DISCOUNT_CODE_REQUIRED })
|
||||
discountCode: string;
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import { Column, Entity, ManyToOne, OneToMany } from "typeorm";
|
||||
import { InvoiceItem } from "./invoice-item.entity";
|
||||
import { BaseEntity } from "../../../common/entities/base.entity";
|
||||
import { DecimalTransformer } from "../../../common/transformers/decimal.transformer";
|
||||
import { Discount } from "../../discounts/entities/discount.entity";
|
||||
import { User } from "../../users/entities/user.entity";
|
||||
import { InvoiceStatus } from "../enums/invoice-status.enum";
|
||||
|
||||
@@ -28,9 +29,14 @@ export class Invoice extends BaseEntity {
|
||||
@Column({ type: "int", default: 0 })
|
||||
tax: number;
|
||||
|
||||
//---------------------------------------------
|
||||
|
||||
@OneToMany(() => InvoiceItem, (invoiceItem) => invoiceItem.invoice, { cascade: true })
|
||||
items: InvoiceItem[];
|
||||
|
||||
@ManyToOne(() => Discount, { nullable: true, onDelete: "SET NULL" })
|
||||
discount: Discount;
|
||||
|
||||
get isOverdue(): boolean {
|
||||
return this.status === InvoiceStatus.PENDING && new Date() > this.dueDate;
|
||||
}
|
||||
|
||||
@@ -6,10 +6,12 @@ import { Invoice } from "./entities/invoice.entity";
|
||||
import { InvoicesController } from "./invoices.controller";
|
||||
import { InvoicesService } from "./providers/invoices.service";
|
||||
import { InvoicesRepository } from "./repositories/invoices.repository";
|
||||
import { Discount } from "../discounts/entities/discount.entity";
|
||||
import { DiscountRepository } from "../discounts/repositories/discount.repository";
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([Invoice, InvoiceItem])],
|
||||
providers: [InvoicesService, InvoicesRepository],
|
||||
imports: [TypeOrmModule.forFeature([Invoice, InvoiceItem, Discount])],
|
||||
providers: [InvoicesService, InvoicesRepository, DiscountRepository],
|
||||
controllers: [InvoicesController],
|
||||
exports: [InvoicesService],
|
||||
})
|
||||
|
||||
@@ -4,9 +4,11 @@ import Decimal from "decimal.js";
|
||||
import { QueryRunner } from "typeorm";
|
||||
|
||||
import { InvoiceMessage } from "../../../common/enums/message.enum";
|
||||
import { DiscountRepository } from "../../discounts/repositories/discount.repository";
|
||||
import { SubscriptionPlan } from "../../subscriptions/entities/subscription.entity";
|
||||
import { RoleEnum } from "../../users/enums/role.enum";
|
||||
import { PaginationUtils } from "../../utils/providers/pagination.utils";
|
||||
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";
|
||||
@@ -18,9 +20,12 @@ import { InvoicesRepository } from "../repositories/invoices.repository";
|
||||
export class InvoicesService {
|
||||
constructor(
|
||||
private readonly invoiceRepository: InvoicesRepository,
|
||||
private readonly discountRepository: DiscountRepository,
|
||||
// private readonly invoiceItemsRepository: InvoiceItemsRepository,
|
||||
) {}
|
||||
|
||||
///********************************** */
|
||||
|
||||
async createInvoiceAdmin(createDto: CreateInvoiceDto) {
|
||||
//
|
||||
const invoiceItems = createDto.items.map((item) => {
|
||||
@@ -55,7 +60,9 @@ export class InvoicesService {
|
||||
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 },
|
||||
@@ -117,7 +124,9 @@ export class InvoicesService {
|
||||
paginate: true,
|
||||
};
|
||||
}
|
||||
|
||||
//*********************************** */
|
||||
|
||||
async getInvoiceById(invoiceId: string, role: RoleEnum, userId: string) {
|
||||
let invoice: Invoice | null;
|
||||
|
||||
@@ -139,7 +148,9 @@ export class InvoicesService {
|
||||
invoice,
|
||||
};
|
||||
}
|
||||
|
||||
//*********************************** */
|
||||
|
||||
async getUserInvoices(queryDto: UserInvoicesSearchQueryDto, userId: string) {
|
||||
const { limit, skip } = PaginationUtils(queryDto);
|
||||
|
||||
@@ -165,4 +176,56 @@ export class InvoicesService {
|
||||
paginate: true,
|
||||
};
|
||||
}
|
||||
|
||||
//*********************************** */
|
||||
|
||||
async applyDiscount(invoiceId: string, applyDiscountDto: ApplyDiscountDto) {
|
||||
const invoice = await this.invoiceRepository.findOneBy({ id: invoiceId });
|
||||
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(`Discount with code ${applyDiscountDto.discountCode} not found or inactive`);
|
||||
}
|
||||
|
||||
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("This discount is not applicable to any subscription plan in the invoice.");
|
||||
}
|
||||
}
|
||||
|
||||
if (discount.users && discount.users.length > 0) {
|
||||
if (!invoice.user || !discount.users.some((user) => user.id === invoice.user.id)) {
|
||||
throw new BadRequestException("This discount is not applicable for this user.");
|
||||
}
|
||||
}
|
||||
|
||||
invoice.discount = discount;
|
||||
await this.invoiceRepository.save(invoice);
|
||||
|
||||
return { invoice };
|
||||
}
|
||||
|
||||
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