chore: complete the the invoice module - not tested
This commit is contained in:
@@ -0,0 +1,46 @@
|
||||
import { ApiProperty } from "@nestjs/swagger";
|
||||
import { Type } from "class-transformer";
|
||||
import { ArrayMinSize, IsInt, IsNotEmpty, IsOptional, IsString, IsUUID, Length, ValidateNested } from "class-validator";
|
||||
|
||||
import { InvoiceMessage } from "../../../common/enums/message.enum";
|
||||
|
||||
export class InvoiceItemDto {
|
||||
@IsNotEmpty({ message: InvoiceMessage.NAME_REQUIRED })
|
||||
@IsString({ message: InvoiceMessage.NAME_MUST_BE_A_STRING })
|
||||
@Length(1, 150, { message: InvoiceMessage.NAME_LENGTH })
|
||||
@ApiProperty({ type: String, description: "Item name" })
|
||||
name: string;
|
||||
|
||||
@IsNotEmpty({ message: InvoiceMessage.COUNT_REQUIRED })
|
||||
@IsInt({ message: InvoiceMessage.COUNT_MUST_BE_A_INT })
|
||||
@ApiProperty({ type: Number, description: "Item count", example: 2 })
|
||||
count: number;
|
||||
|
||||
@IsNotEmpty({ message: InvoiceMessage.UNIT_PRICE_REQUIRED })
|
||||
@IsInt({ message: InvoiceMessage.UNIT_PRICE_MUST_BE_A_INT })
|
||||
@ApiProperty({ description: "Item unit price", example: 100_000 })
|
||||
unitPrice: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsNotEmpty({ message: InvoiceMessage.DISCOUNT_REQUIRED })
|
||||
@IsInt({ message: InvoiceMessage.DISCOUNT_MUST_BE_A_INT })
|
||||
@ApiProperty({ description: "Item discount", example: 10 })
|
||||
discount: number;
|
||||
}
|
||||
|
||||
export class CreateInvoiceDto {
|
||||
@IsNotEmpty({ message: InvoiceMessage.USER_ID_REQUIRED })
|
||||
@IsUUID("4", { message: InvoiceMessage.USER_ID_SHOULD_BE_A_UUID })
|
||||
@ApiProperty({ description: "User id", example: "123e4567-e89b-12d3-a456-426614174000" })
|
||||
userId: string;
|
||||
|
||||
@ApiProperty({
|
||||
type: [InvoiceItemDto],
|
||||
description: "Invoice items",
|
||||
example: [{ name: "item1", count: 2, unitPrice: 100_000, discount: 10 }],
|
||||
})
|
||||
@ValidateNested({ each: true })
|
||||
@ArrayMinSize(1)
|
||||
@Type(() => InvoiceItemDto)
|
||||
items: InvoiceItemDto[];
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import { IsEnum, IsOptional, IsString, IsUUID } from "class-validator";
|
||||
|
||||
import { PaginationDto } from "../../../common/DTO/pagination.dto";
|
||||
import { InvoiceMessage, ServiceMessage, UserMessage } from "../../../common/enums/message.enum";
|
||||
import { InvoiceStatus } from "../enums/invoice-status.enum";
|
||||
|
||||
export class InvoicesSearchQueryDto extends PaginationDto {
|
||||
@IsOptional()
|
||||
@IsString({ message: InvoiceMessage.SEARCH_QUERY_MUST_BE_A_STRING })
|
||||
@ApiPropertyOptional({ description: "search query", example: "search query" })
|
||||
q: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsUUID("4", { message: ServiceMessage.SERVICE_ID_SHOULD_BE_A_UUID })
|
||||
@ApiPropertyOptional({ description: "service id", example: "123e4567-e89b-12d3-a456-426614174000" })
|
||||
serviceId: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsUUID("4", { message: UserMessage.USER_ID_SHOULD_BE_A_UUID })
|
||||
@ApiPropertyOptional({ description: "user id", example: "123e4567-e89b-12d3-a456-426614174000" })
|
||||
userId: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsEnum(InvoiceStatus)
|
||||
@ApiPropertyOptional({ enum: InvoiceStatus, description: "invoice status", example: InvoiceStatus.PAID })
|
||||
status: InvoiceStatus;
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
// eslint-disable-next-line import/no-named-as-default
|
||||
import Decimal from "decimal.js";
|
||||
import { Column, Entity, ManyToOne } from "typeorm";
|
||||
|
||||
import { Invoice } from "./invoice.entity";
|
||||
import { BaseEntity } from "../../../common/entities/base.entity";
|
||||
import { DecimalTransformer } from "../../../common/transformers/decimal.transformer";
|
||||
import { SubscriptionPlan } from "../../subscriptions/entities/subscription.entity";
|
||||
|
||||
@Entity()
|
||||
export class InvoiceItem extends BaseEntity {
|
||||
@ManyToOne(() => Invoice, (invoice) => invoice.items, { onDelete: "CASCADE" })
|
||||
invoice: Invoice;
|
||||
|
||||
@Column({ type: "varchar", length: 150, nullable: false })
|
||||
name: string;
|
||||
|
||||
@Column({ type: "int", nullable: false })
|
||||
count: number;
|
||||
|
||||
@Column({ type: "decimal", precision: 16, scale: 2, nullable: false, transformer: new DecimalTransformer() })
|
||||
unitPrice: Decimal;
|
||||
|
||||
@Column({ type: "int", nullable: false })
|
||||
discount: number;
|
||||
|
||||
@Column({ type: "decimal", precision: 16, scale: 2, nullable: false, transformer: new DecimalTransformer() })
|
||||
totalPrice: Decimal;
|
||||
|
||||
@ManyToOne(() => SubscriptionPlan, { nullable: true, onDelete: "RESTRICT" })
|
||||
subscriptionPlan: SubscriptionPlan | null;
|
||||
}
|
||||
@@ -1,7 +1,10 @@
|
||||
import { Column, Entity, ManyToOne } from "typeorm";
|
||||
// eslint-disable-next-line import/no-named-as-default
|
||||
import Decimal from "decimal.js";
|
||||
import { Column, Entity, ManyToOne, OneToMany } from "typeorm";
|
||||
|
||||
import { InvoiceItem } from "./invoice-item.entity";
|
||||
import { BaseEntity } from "../../../common/entities/base.entity";
|
||||
import { SubscriptionPlan } from "../../subscriptions/entities/subscription.entity";
|
||||
import { DecimalTransformer } from "../../../common/transformers/decimal.transformer";
|
||||
import { User } from "../../users/entities/user.entity";
|
||||
import { InvoiceStatus } from "../enums/invoice-status.enum";
|
||||
|
||||
@@ -10,15 +13,25 @@ export class Invoice extends BaseEntity {
|
||||
@ManyToOne(() => User, (user) => user.invoices, { nullable: true, onDelete: "RESTRICT" })
|
||||
user: User;
|
||||
|
||||
@ManyToOne(() => SubscriptionPlan, { nullable: true, onDelete: "SET NULL" })
|
||||
subscriptionPlan?: SubscriptionPlan;
|
||||
|
||||
@Column({ type: "decimal", precision: 10, scale: 2, nullable: false })
|
||||
amount: number;
|
||||
@Column({ type: "decimal", precision: 16, scale: 2, nullable: false, transformer: new DecimalTransformer() })
|
||||
totalPrice: Decimal;
|
||||
|
||||
@Column({ type: "enum", enum: InvoiceStatus, default: InvoiceStatus.PENDING })
|
||||
status: InvoiceStatus;
|
||||
|
||||
@Column({ type: "timestamp", nullable: false })
|
||||
dueDate: Date;
|
||||
|
||||
@Column({ type: "timestamp", nullable: true })
|
||||
paidAt?: Date;
|
||||
paidAt: Date | null;
|
||||
|
||||
@Column({ type: "int", default: 0 })
|
||||
tax: number;
|
||||
|
||||
@OneToMany(() => InvoiceItem, (invoiceItem) => invoiceItem.invoice, { cascade: true })
|
||||
items: InvoiceItem[];
|
||||
|
||||
get isOverdue(): boolean {
|
||||
return this.status === InvoiceStatus.PENDING && new Date() > this.dueDate;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
export enum InvoiceStatus {
|
||||
PENDING = "PENDING",
|
||||
PAID = "PAID",
|
||||
CANCELED = "CANCELED",
|
||||
EXPIRED = "EXPIRED",
|
||||
CANCELLED = "CANCELLED",
|
||||
}
|
||||
|
||||
@@ -1,4 +1,32 @@
|
||||
import { Controller } from "@nestjs/common";
|
||||
import { Body, Controller, Get, Post, Query } from "@nestjs/common";
|
||||
import { ApiOperation } from "@nestjs/swagger";
|
||||
|
||||
import { CreateInvoiceDto } from "./DTO/create-invoice.dto";
|
||||
import { InvoicesSearchQueryDto } from "./DTO/invoices-search-query.dto";
|
||||
import { InvoicesService } from "./providers/invoices.service";
|
||||
import { AuthGuards } from "../../common/decorators/auth-guard.decorator";
|
||||
import { Pagination } from "../../common/decorators/pagination.decorator";
|
||||
import { Roles } from "../../common/decorators/roles.decorator";
|
||||
import { RoleEnum } from "../users/enums/role.enum";
|
||||
|
||||
@Controller("invoices")
|
||||
export class InvoicesController {}
|
||||
export class InvoicesController {
|
||||
constructor(private readonly invoiceService: InvoicesService) {}
|
||||
|
||||
@ApiOperation({ summary: "create an invoice ==> admin route" })
|
||||
@AuthGuards()
|
||||
@Roles(RoleEnum.ADMIN)
|
||||
@Post()
|
||||
createInvoice(@Body() createDto: CreateInvoiceDto) {
|
||||
return this.invoiceService.createInvoiceAdmin(createDto);
|
||||
}
|
||||
|
||||
@ApiOperation({ summary: "get all invoices ==> admin route" })
|
||||
@AuthGuards()
|
||||
@Pagination()
|
||||
@Roles(RoleEnum.ADMIN)
|
||||
@Get()
|
||||
getInvoices(@Query() queryDto: InvoicesSearchQueryDto) {
|
||||
return this.invoiceService.getInvoices(queryDto);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
import { Module } from "@nestjs/common";
|
||||
import { TypeOrmModule } from "@nestjs/typeorm";
|
||||
|
||||
import { InvoiceItem } from "./entities/invoice-item.entity";
|
||||
import { Invoice } from "./entities/invoice.entity";
|
||||
import { InvoicesController } from "./invoices.controller";
|
||||
import { InvoicesService } from "./providers/invoices.service";
|
||||
import { InvoicesRepository } from "./repositories/invoices.repository";
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([Invoice])],
|
||||
imports: [TypeOrmModule.forFeature([Invoice, InvoiceItem])],
|
||||
providers: [InvoicesService, InvoicesRepository],
|
||||
controllers: [InvoicesController],
|
||||
exports: [InvoicesService],
|
||||
|
||||
@@ -1,4 +1,117 @@
|
||||
import { Injectable } from "@nestjs/common";
|
||||
// eslint-disable-next-line import/no-named-as-default
|
||||
import Decimal from "decimal.js";
|
||||
import { QueryRunner } from "typeorm";
|
||||
|
||||
import { InvoiceMessage } from "../../../common/enums/message.enum";
|
||||
import { SubscriptionPlan } from "../../subscriptions/entities/subscription.entity";
|
||||
import { PaginationUtils } from "../../utils/providers/pagination.utils";
|
||||
import { CreateInvoiceDto } from "../DTO/create-invoice.dto";
|
||||
import { InvoicesSearchQueryDto } 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 {}
|
||||
export class InvoicesService {
|
||||
constructor(
|
||||
private readonly invoiceRepository: InvoicesRepository,
|
||||
// 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,
|
||||
items: invoiceItems,
|
||||
tax: tax.toNumber(),
|
||||
dueDate,
|
||||
});
|
||||
//
|
||||
await this.invoiceRepository.save(invoice);
|
||||
//TODO: notify user
|
||||
|
||||
return {
|
||||
message: InvoiceMessage.CREATED,
|
||||
invoice,
|
||||
};
|
||||
}
|
||||
///********************************** */
|
||||
async createInvoiceForSubscription(userId: string, plan: SubscriptionPlan, dueDate: Date, queryRunner: QueryRunner) {
|
||||
const invoiceItems = [{ name: plan.name, count: 1, unitPrice: plan.price, discount: 0, subscriptionPlan: plan }];
|
||||
|
||||
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 { limit, skip } = PaginationUtils(queryDto);
|
||||
|
||||
const queryBuilder = this.invoiceRepository.createQueryBuilder("invoice");
|
||||
|
||||
queryBuilder
|
||||
.leftJoinAndSelect("invoice.user", "user")
|
||||
.leftJoinAndSelect("invoice.items", "items")
|
||||
.leftJoinAndSelect("items.subscriptionPlan", "subscriptionPlan");
|
||||
|
||||
if (queryDto.q) {
|
||||
queryBuilder
|
||||
.orWhere("user.firstName ILIKE :search", { search: `%${queryDto.q}%` })
|
||||
.orWhere("user.lastName ILIKE :search", { search: `%${queryDto.q}%` })
|
||||
.orWhere("user.email ILIKE :search", { search: `%${queryDto.q}%` });
|
||||
}
|
||||
|
||||
if (queryDto.status) {
|
||||
queryBuilder.andWhere("invoice.status = :status", { status: queryDto.status });
|
||||
}
|
||||
|
||||
if (queryDto.userId) {
|
||||
queryBuilder.andWhere("invoice.user.id = :userId", { userId: queryDto.userId });
|
||||
}
|
||||
|
||||
if (queryDto.serviceId) {
|
||||
queryBuilder.andWhere("subscriptionPlan.serviceId = :serviceId", { serviceId: queryDto.serviceId });
|
||||
}
|
||||
|
||||
queryBuilder.orderBy("createdAt", "DESC");
|
||||
queryBuilder.skip(skip);
|
||||
queryBuilder.take(limit);
|
||||
|
||||
const [invoices, count] = await queryBuilder.getManyAndCount();
|
||||
|
||||
return {
|
||||
invoices,
|
||||
count,
|
||||
paginate: true,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
import { Injectable } from "@nestjs/common";
|
||||
import { InjectRepository } from "@nestjs/typeorm";
|
||||
import { Repository } from "typeorm";
|
||||
|
||||
import { InvoiceItem } from "../entities/invoice-item.entity";
|
||||
|
||||
@Injectable()
|
||||
export class InvoiceItemsRepository extends Repository<InvoiceItem> {
|
||||
constructor(@InjectRepository(InvoiceItem) invoiceItemsRepository: Repository<InvoiceItem>) {
|
||||
super(invoiceItemsRepository.target, invoiceItemsRepository.manager, invoiceItemsRepository.queryRunner);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user