chore: discount module
This commit is contained in:
@@ -37,8 +37,15 @@ export class CreateDiscountDto {
|
||||
|
||||
@ApiPropertyOptional({ description: "لیست آیدیهای خدمات", type: [String], example: ["f47ac10b-58cc-4372-a567-0e02b2c3d479"] })
|
||||
@IsOptional()
|
||||
@IsArray({ message: DiscountMessage.SERVICES_INVALID })
|
||||
@ArrayUnique({ message: DiscountMessage.SERVICES_DUPLICATE })
|
||||
@IsArray({ message: DiscountMessage.SERVICES_INVALID })
|
||||
@IsUUID("4", { each: true, message: DiscountMessage.SERVICES_UUID_INVALID })
|
||||
services?: string[];
|
||||
subscriptionPlanIds?: string[];
|
||||
|
||||
@ApiPropertyOptional({ description: "لیست آیدیهای کاربران", type: [String], example: ["f47ac10b-58cc-4372-a567-0e02b2c3d479"] })
|
||||
@IsOptional()
|
||||
@ArrayUnique({ message: DiscountMessage.USER_DUPLICATE })
|
||||
@IsArray({ message: DiscountMessage.USER_INVALID })
|
||||
@IsUUID("4", { each: true, message: DiscountMessage.USER_UUID_INVALID })
|
||||
userIds?: string[];
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import { CreateDiscountDto } from "./DTO/create-discount.dto";
|
||||
import { DiscountService } from "./providers/discounts.service";
|
||||
import { AuthGuards } from "../../common/decorators/auth-guard.decorator";
|
||||
import { Roles } from "../../common/decorators/roles.decorator";
|
||||
import { UserDec } from "../../common/decorators/user.decorator";
|
||||
import { ParamDto } from "../../common/DTO/param.dto";
|
||||
import { RoleEnum } from "../users/enums/role.enum";
|
||||
|
||||
@@ -43,6 +44,14 @@ export class DiscountController {
|
||||
|
||||
//************************************ */
|
||||
|
||||
@ApiOperation({ summary: "Retrieve a discounts by userID" })
|
||||
@Get("/user-discounts")
|
||||
async findDiscountsByUsers(@UserDec("id") userId: string) {
|
||||
return this.discountService.findDiscountsByUser(userId);
|
||||
}
|
||||
|
||||
//************************************ */
|
||||
|
||||
@ApiOperation({ summary: "Toggle active/deactive discount" })
|
||||
@Roles(RoleEnum.ADMIN)
|
||||
@Patch(":id/toggle")
|
||||
|
||||
@@ -5,10 +5,11 @@ import { DiscountController } from "./discounts.controller";
|
||||
import { Discount } from "./entities/discount.entity";
|
||||
import { DiscountService } from "./providers/discounts.service";
|
||||
import { DiscountRepository } from "./repositories/discount.repository";
|
||||
import { DanakServicesModule } from "../danak-services/danak-services.module";
|
||||
import { SubscriptionsModule } from "../subscriptions/subscriptions.module";
|
||||
import { UsersModule } from "../users/users.module";
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([Discount]), DanakServicesModule],
|
||||
imports: [TypeOrmModule.forFeature([Discount]), SubscriptionsModule, UsersModule],
|
||||
providers: [DiscountService, DiscountRepository],
|
||||
controllers: [DiscountController],
|
||||
})
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
// eslint-disable-next-line import/no-named-as-default
|
||||
import Decimal from "decimal.js";
|
||||
import { Column, Entity, ManyToOne } from "typeorm";
|
||||
import { Column, Entity, JoinTable, ManyToMany } from "typeorm";
|
||||
|
||||
import { BaseEntity } from "../../../common/entities/base.entity";
|
||||
import { DecimalTransformer } from "../../../common/transformers/decimal.transformer";
|
||||
import { SubscriptionPlan } from "../../subscriptions/entities/subscription.entity";
|
||||
import { User } from "../../users/entities/user.entity";
|
||||
import { DiscountCalculationType, DiscountType } from "../enums/discount-type.enum";
|
||||
|
||||
@Entity()
|
||||
@@ -33,6 +34,11 @@ export class Discount extends BaseEntity {
|
||||
@Column({ type: "timestamptz" })
|
||||
endDate: Date;
|
||||
|
||||
@ManyToOne(() => SubscriptionPlan, { nullable: true, onDelete: "SET NULL" })
|
||||
subscriptionPlan: SubscriptionPlan;
|
||||
@ManyToMany(() => SubscriptionPlan, (subscriptionPlan) => subscriptionPlan.discounts, { nullable: true })
|
||||
@JoinTable()
|
||||
subscriptionPlans: SubscriptionPlan[];
|
||||
|
||||
@ManyToMany(() => User, (user) => user.discounts, { nullable: true })
|
||||
@JoinTable()
|
||||
users: User[];
|
||||
}
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import { randomBytes } from "node:crypto";
|
||||
|
||||
import { BadRequestException, Injectable } from "@nestjs/common";
|
||||
import { BadRequestException, Injectable, NotFoundException } from "@nestjs/common";
|
||||
import { In } from "typeorm";
|
||||
|
||||
import { CommonMessage, DiscountMessage } from "../../../common/enums/message.enum";
|
||||
// import { DanakServicesService } from "../../danak-services/providers/danak-services.service";
|
||||
import { CommonMessage, DiscountMessage, SubscriptionMessage, UserMessage } from "../../../common/enums/message.enum";
|
||||
import { SubscriptionsPlanRepository } from "../../subscriptions/repositories/subscriptions.repository";
|
||||
import { UserRepository } from "../../users/repositories/users.repository";
|
||||
import { CreateDiscountDto } from "../DTO/create-discount.dto";
|
||||
import { DiscountRepository } from "../repositories/discount.repository";
|
||||
|
||||
@@ -11,13 +13,14 @@ import { DiscountRepository } from "../repositories/discount.repository";
|
||||
export class DiscountService {
|
||||
constructor(
|
||||
private readonly discountRepository: DiscountRepository,
|
||||
// private readonly danakServicesService: DanakServicesService,
|
||||
private readonly subscriptionPlanRepository: SubscriptionsPlanRepository,
|
||||
private readonly userRepository: UserRepository,
|
||||
) {}
|
||||
|
||||
/******************************************** */
|
||||
|
||||
async create(createDiscountDto: CreateDiscountDto) {
|
||||
const { services, ...discountData } = createDiscountDto;
|
||||
const { subscriptionPlanIds, ...discountData } = createDiscountDto;
|
||||
|
||||
const code = await this.generateUniqueCouponCode();
|
||||
|
||||
@@ -26,10 +29,28 @@ export class DiscountService {
|
||||
code,
|
||||
});
|
||||
|
||||
if (services && services.length) {
|
||||
// const foundServices = await this.danakServicesService.findServicesByIds(services);
|
||||
// discount.services = foundServices;
|
||||
if (createDiscountDto.subscriptionPlanIds && createDiscountDto.subscriptionPlanIds.length) {
|
||||
const subscriptionPlans = await this.subscriptionPlanRepository.find({
|
||||
where: { id: In(createDiscountDto.subscriptionPlanIds) },
|
||||
});
|
||||
|
||||
if (subscriptionPlans.length !== createDiscountDto.subscriptionPlanIds.length) {
|
||||
throw new NotFoundException(SubscriptionMessage.NOT_FOUND);
|
||||
}
|
||||
|
||||
discount.subscriptionPlans = subscriptionPlans;
|
||||
}
|
||||
|
||||
if (createDiscountDto.userIds) {
|
||||
const users = await this.userRepository.find({ where: { id: In(createDiscountDto.userIds) } });
|
||||
|
||||
if (users.length !== createDiscountDto.userIds.length) {
|
||||
throw new NotFoundException(UserMessage.USER_NOT_FOUND);
|
||||
}
|
||||
|
||||
discount.users = users;
|
||||
}
|
||||
|
||||
await this.discountRepository.save(discount);
|
||||
|
||||
return {
|
||||
@@ -40,9 +61,39 @@ export class DiscountService {
|
||||
|
||||
/******************************************** */
|
||||
|
||||
async findByCode(code: string) {
|
||||
const discount = await this.discountRepository.findOne({
|
||||
where: { code, isActive: true },
|
||||
relations: ["subscriptionPlans"],
|
||||
});
|
||||
if (!discount) {
|
||||
throw new NotFoundException(DiscountMessage.NOT_FOUND);
|
||||
}
|
||||
return { discount };
|
||||
}
|
||||
|
||||
/******************************************** */
|
||||
|
||||
async findDiscountsByUser(userId: string) {
|
||||
const user = await this.userRepository.findOneBy({
|
||||
id: userId,
|
||||
});
|
||||
if (!user) throw new BadRequestException(UserMessage.USER_NOT_FOUND);
|
||||
|
||||
const discounts = await this.discountRepository.find({
|
||||
where: {
|
||||
users: { id: user.id },
|
||||
},
|
||||
});
|
||||
|
||||
return { discounts };
|
||||
}
|
||||
|
||||
/******************************************** */
|
||||
|
||||
async findAll() {
|
||||
const services = await this.discountRepository.find({ relations: ["services"] });
|
||||
return { services };
|
||||
const discounts = await this.discountRepository.find({ relations: ["subscriptionPlans"] });
|
||||
return { discounts };
|
||||
}
|
||||
|
||||
/******************************************** */
|
||||
@@ -50,7 +101,7 @@ export class DiscountService {
|
||||
async findOne(id: string) {
|
||||
const discount = await this.discountRepository.findOne({
|
||||
where: { id },
|
||||
relations: ["services"],
|
||||
relations: ["subscriptionPlans"],
|
||||
});
|
||||
if (!discount) throw new BadRequestException(DiscountMessage.NOT_FOUND);
|
||||
return { discount };
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
// eslint-disable-next-line import/no-named-as-default
|
||||
import Decimal from "decimal.js";
|
||||
import { Column, Entity, Index, ManyToOne } from "typeorm";
|
||||
import { Column, Entity, Index, ManyToMany, ManyToOne } from "typeorm";
|
||||
|
||||
import { BaseEntity } from "../../../common/entities/base.entity";
|
||||
import { DecimalTransformer } from "../../../common/transformers/decimal.transformer";
|
||||
import { DanakService } from "../../danak-services/entities/danak-service.entity";
|
||||
import { Discount } from "../../discounts/entities/discount.entity";
|
||||
|
||||
@Entity()
|
||||
@Index(["service", "name"], { unique: true })
|
||||
@@ -23,4 +24,7 @@ export class SubscriptionPlan extends BaseEntity {
|
||||
|
||||
@ManyToOne(() => DanakService, (danakService) => danakService.subscriptionPlans, { nullable: false, onDelete: "CASCADE" })
|
||||
service: DanakService;
|
||||
|
||||
@ManyToMany(() => Discount, (discount) => discount.subscriptionPlans)
|
||||
discounts: Discount[];
|
||||
}
|
||||
|
||||
@@ -22,6 +22,6 @@ import { WalletsModule } from "../wallets/wallets.module";
|
||||
],
|
||||
providers: [SubscriptionsService, SubscriptionsPlanRepository, UserSubscriptionsRepository],
|
||||
controllers: [SubscriptionsController],
|
||||
exports: [SubscriptionsService],
|
||||
exports: [SubscriptionsService, TypeOrmModule, SubscriptionsPlanRepository],
|
||||
})
|
||||
export class SubscriptionsModule {}
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import { ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import { IsNotEmpty, IsOptional, IsString, IsUUID } from "class-validator";
|
||||
|
||||
import { FinancialMessage } from "../../../common/enums/message.enum";
|
||||
|
||||
export class CreateFinancialDto {
|
||||
@ApiPropertyOptional({ description: "Economic code" })
|
||||
@IsOptional()
|
||||
@IsString({ message: FinancialMessage.ECONOMIC_CODE_INVALID })
|
||||
economicCode?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: "Registration ID" })
|
||||
@IsOptional()
|
||||
@IsString({ message: FinancialMessage.REGISTRATION_ID_INVALID })
|
||||
registrationId?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: "number" })
|
||||
@IsOptional()
|
||||
@IsString({ message: FinancialMessage.FIXED_PHONE_INVALID })
|
||||
number?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: "number" })
|
||||
@IsOptional()
|
||||
@IsString({ message: FinancialMessage.NATIONAL_ID_INVALID })
|
||||
nationalId?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: "User id", example: "123e4567-e89b-12d3-a456-426614174000" })
|
||||
@IsOptional()
|
||||
@IsNotEmpty({ message: FinancialMessage.USER_ID_REQUIRED })
|
||||
@IsUUID("4", { message: FinancialMessage.USER_ID_SHOULD_BE_A_UUID })
|
||||
userId: string;
|
||||
}
|
||||
+6
-5
@@ -1,13 +1,14 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import { ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import { IsEnum, IsNotEmpty, IsOptional, IsString, IsUUID } from "class-validator";
|
||||
|
||||
import { FinancialMessage } from "../../../common/enums/message.enum";
|
||||
import { FinancialType } from "../enums/financial-type.enum";
|
||||
import { GenderType } from "../enums/gender-type.enum";
|
||||
|
||||
export class CreateFinancialDto {
|
||||
@ApiProperty({ enum: FinancialType, description: "Financial information type: REAL or LEGAL" })
|
||||
@IsEnum(FinancialType, { message: FinancialMessage.FINANCIAL_TYPE_INVALID })
|
||||
type: FinancialType;
|
||||
@ApiPropertyOptional({ enum: GenderType, description: "Gender type" })
|
||||
@IsOptional()
|
||||
@IsEnum(GenderType, { message: FinancialMessage.GENDER_TYPE_INVALID })
|
||||
gender?: GenderType;
|
||||
|
||||
@ApiPropertyOptional({ description: "Economic code" })
|
||||
@IsOptional()
|
||||
@@ -0,0 +1,24 @@
|
||||
import { Column, Entity, JoinColumn, OneToOne, Unique } from "typeorm";
|
||||
|
||||
import { User } from "./user.entity";
|
||||
import { BaseEntity } from "../../../common/entities/base.entity";
|
||||
|
||||
@Unique(["user"])
|
||||
@Entity()
|
||||
export class LegalUser extends BaseEntity {
|
||||
@Column({ nullable: true })
|
||||
economicCode: string;
|
||||
|
||||
@Column({ nullable: true })
|
||||
registrationId: string;
|
||||
|
||||
@Column({ nullable: true })
|
||||
nationalId: string;
|
||||
|
||||
@Column({ nullable: true })
|
||||
number: string;
|
||||
|
||||
@OneToOne(() => User, (user) => user.legalUser, { onDelete: "CASCADE" })
|
||||
@JoinColumn()
|
||||
user: User;
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { Column, Entity, JoinColumn, OneToOne, Unique } from "typeorm";
|
||||
|
||||
import { User } from "./user.entity";
|
||||
import { BaseEntity } from "../../../common/entities/base.entity";
|
||||
import { GenderType } from "../enums/gender-type.enum";
|
||||
|
||||
@Unique(["user"])
|
||||
@Entity()
|
||||
export class RealUser extends BaseEntity {
|
||||
@Column({
|
||||
type: "enum",
|
||||
enum: GenderType,
|
||||
nullable: true,
|
||||
})
|
||||
gender: GenderType;
|
||||
|
||||
@Column({ nullable: true })
|
||||
fatherName: string;
|
||||
|
||||
@Column({ nullable: true })
|
||||
nationality: string;
|
||||
|
||||
@OneToOne(() => User, (user) => user.realUser, { onDelete: "CASCADE" })
|
||||
@JoinColumn()
|
||||
user: User;
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
import { Column, Entity, ManyToOne, Unique } from "typeorm";
|
||||
|
||||
import { User } from "./user.entity";
|
||||
import { BaseEntity } from "../../../common/entities/base.entity";
|
||||
import { FinancialType } from "../enums/financial-type.enum";
|
||||
|
||||
@Unique(["user", "type"])
|
||||
@Entity()
|
||||
export class UserFinancial extends BaseEntity {
|
||||
@Column({
|
||||
type: "enum",
|
||||
enum: FinancialType,
|
||||
default: FinancialType.REAL,
|
||||
})
|
||||
type: FinancialType;
|
||||
|
||||
@Column({ nullable: true })
|
||||
economicCode: string;
|
||||
|
||||
@Column({ nullable: true })
|
||||
registrationId: string;
|
||||
|
||||
@Column({ nullable: true })
|
||||
nationalId: string;
|
||||
|
||||
@Column({ nullable: true })
|
||||
number: string;
|
||||
|
||||
@ManyToOne(() => User, (user) => user.userFinancials)
|
||||
user: User;
|
||||
}
|
||||
@@ -1,12 +1,14 @@
|
||||
import { Exclude } from "class-transformer";
|
||||
import { Column, Entity, ManyToMany, ManyToOne, OneToMany, OneToOne } from "typeorm";
|
||||
|
||||
import { LegalUser } from "./legal-user.entity";
|
||||
import { RealUser } from "./real-user.entity";
|
||||
import { Role } from "./role.entity";
|
||||
import { UserFinancial } from "./user-financial.entity";
|
||||
import { UserGroup } from "./user-group.entity";
|
||||
import { BaseEntity } from "../../../common/entities/base.entity";
|
||||
import { UserAnnouncement } from "../../announcements/entities/user-announcement.entity";
|
||||
import { Criticism } from "../../criticisms/entities/criticism.entity";
|
||||
import { Discount } from "../../discounts/entities/discount.entity";
|
||||
import { Invoice } from "../../invoices/entities/invoice.entity";
|
||||
import { LearningProgress } from "../../learnings/entities/learning-progress.entity";
|
||||
import { Notification } from "../../notifications/entities/notification.entity";
|
||||
@@ -84,8 +86,14 @@ export class User extends BaseEntity {
|
||||
@OneToMany(() => LearningProgress, (learningProgress) => learningProgress.learning)
|
||||
learningProgress: LearningProgress[];
|
||||
|
||||
@OneToMany(() => UserFinancial, (userFinancial) => userFinancial.user)
|
||||
userFinancials: UserFinancial[];
|
||||
@ManyToMany(() => Discount, (discount) => discount.subscriptionPlans)
|
||||
discounts: Discount[];
|
||||
|
||||
@OneToOne(() => RealUser, (realUser) => realUser.user, { cascade: true, nullable: true })
|
||||
realUser: RealUser;
|
||||
|
||||
@OneToOne(() => LegalUser, (legalUser) => legalUser.user, { cascade: true, nullable: true })
|
||||
legalUser: LegalUser;
|
||||
}
|
||||
|
||||
// @ManyToMany(() => DanakService, (danakService) => danakService.users)
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
export enum GenderType {
|
||||
MALE = "male",
|
||||
FEMALE = "female",
|
||||
}
|
||||
@@ -2,13 +2,13 @@ import { BadRequestException, Injectable } from "@nestjs/common";
|
||||
import slugify from "slugify";
|
||||
import { In, Not, QueryRunner } from "typeorm";
|
||||
|
||||
import { CommonMessage, FinancialMessage, UserMessage } from "../../../common/enums/message.enum";
|
||||
import { CommonMessage, UserMessage } from "../../../common/enums/message.enum";
|
||||
import { CompleteRegistrationDto } from "../../auth/DTO/complete-register.dto";
|
||||
import { UserSettingsService } from "../../settings/providers/user-settings.service";
|
||||
import { PaginationUtils } from "../../utils/providers/pagination.utils";
|
||||
import { WalletsService } from "../../wallets/providers/wallets.service";
|
||||
import { CheckValidityDTO } from "../DTO/check-validity.dto";
|
||||
import { CreateFinancialDto } from "../DTO/create-user-financial.dto";
|
||||
// import { CreateFinancialDto } from "../DTO/create-legal-user.dto";
|
||||
import { SearchAdminsDto } from "../DTO/search-admins.dto";
|
||||
import { SearchCustomersDto } from "../DTO/search-customers.dto";
|
||||
import { UpdateProfileDto } from "../DTO/update-profile.dto";
|
||||
@@ -17,7 +17,8 @@ import { Role } from "../entities/role.entity";
|
||||
import { User } from "../entities/user.entity";
|
||||
import { RoleEnum } from "../enums/role.enum";
|
||||
import { ValidityType } from "../enums/validity-type.enum";
|
||||
import { UserFinancialRepository } from "../repositories/user-financial.repository";
|
||||
// import { LegalUserRepository } from "../repositories/legal-user.repository";
|
||||
// import { RealUserRepository } from "../repositories/real-user.repository";
|
||||
import { UserGroupRepository } from "../repositories/user-group.repository";
|
||||
import { UserRepository } from "../repositories/users.repository";
|
||||
|
||||
@@ -41,8 +42,9 @@ export class UsersService {
|
||||
private readonly userRepository: UserRepository,
|
||||
private readonly userGroupRepository: UserGroupRepository,
|
||||
private readonly userSettingsService: UserSettingsService,
|
||||
private readonly userFinancialRepository: UserFinancialRepository,
|
||||
private readonly walletsService: WalletsService,
|
||||
// private readonly realUserRepository: RealUserRepository,
|
||||
// private readonly legalUserRepository: LegalUserRepository,
|
||||
) {}
|
||||
|
||||
/************************************************************ */
|
||||
@@ -247,7 +249,8 @@ export class UsersService {
|
||||
if (queryDto.q) {
|
||||
queryBuilder
|
||||
.orWhere("user.firstName ILIKE :search", { search: `%${queryDto.q}%` })
|
||||
.orWhere("user.lastName ILIKE :search", { search: `%${queryDto.q}%` });
|
||||
.orWhere("user.lastName ILIKE :search", { search: `%${queryDto.q}%` })
|
||||
.orWhere("user.userName ILIKE :search", { search: `%${queryDto.q}%` });
|
||||
}
|
||||
|
||||
const [customers, count] = await queryBuilder.skip(skip).take(limit).getManyAndCount();
|
||||
@@ -273,58 +276,58 @@ export class UsersService {
|
||||
|
||||
/************************************************************ */
|
||||
|
||||
async createUserFinancial(createDto: CreateFinancialDto, user: User) {
|
||||
const userExist = await this.userRepository.findOneBy({
|
||||
id: user.role.name === RoleEnum.USER ? user.id : createDto.userId,
|
||||
});
|
||||
// async createRealUserData(createDto: CreateFinancialDto, user: User) {
|
||||
// const userExist = await this.userRepository.findOneBy({
|
||||
// id: user.role.name === RoleEnum.USER ? user.id : createDto.userId,
|
||||
// });
|
||||
|
||||
if (!userExist) throw new BadRequestException(UserMessage.USER_NOT_FOUND);
|
||||
// if (!userExist) throw new BadRequestException(UserMessage.USER_NOT_FOUND);
|
||||
|
||||
const existingFinancial = await this.userFinancialRepository.findOne({
|
||||
where: { user: { id: userExist.id }, type: createDto.type },
|
||||
});
|
||||
console.log(existingFinancial);
|
||||
// const existingFinancial = await this.userFinancialRepository.findOne({
|
||||
// where: { user: { id: userExist.id }, type: createDto.type },
|
||||
// });
|
||||
// console.log(existingFinancial);
|
||||
|
||||
if (existingFinancial) throw new BadRequestException(FinancialMessage.FINANCIAL_INFO_ALREADY_EXISTS);
|
||||
// if (existingFinancial) throw new BadRequestException(FinancialMessage.FINANCIAL_INFO_ALREADY_EXISTS);
|
||||
|
||||
const userFinancial = this.userFinancialRepository.create({
|
||||
...createDto,
|
||||
user: userExist,
|
||||
});
|
||||
// const userFinancial = this.userFinancialRepository.create({
|
||||
// ...createDto,
|
||||
// user: userExist,
|
||||
// });
|
||||
|
||||
await this.userFinancialRepository.save(userFinancial);
|
||||
// await this.userFinancialRepository.save(userFinancial);
|
||||
|
||||
return {
|
||||
message: CommonMessage.CREATED,
|
||||
userFinancial,
|
||||
};
|
||||
}
|
||||
// return {
|
||||
// message: CommonMessage.CREATED,
|
||||
// userFinancial,
|
||||
// };
|
||||
// }
|
||||
|
||||
/************************************************************ */
|
||||
// /************************************************************ */
|
||||
|
||||
async updateUserFinancial(updateDto: CreateFinancialDto, user: User, userFinancialId: string) {
|
||||
const userExist = await this.userRepository.findOneBy({
|
||||
id: user.role.name === RoleEnum.USER ? user.id : updateDto.userId,
|
||||
});
|
||||
// async updateUserFinancial(updateDto: CreateFinancialDto, user: User, userFinancialId: string) {
|
||||
// const userExist = await this.userRepository.findOneBy({
|
||||
// id: user.role.name === RoleEnum.USER ? user.id : updateDto.userId,
|
||||
// });
|
||||
|
||||
if (!userExist) throw new BadRequestException(UserMessage.USER_NOT_FOUND);
|
||||
// if (!userExist) throw new BadRequestException(UserMessage.USER_NOT_FOUND);
|
||||
|
||||
const existingFinancial = await this.userFinancialRepository.findOne({
|
||||
where: { id: userFinancialId, user: { id: userExist.id }, type: updateDto.type },
|
||||
});
|
||||
// const existingFinancial = await this.userFinancialRepository.findOne({
|
||||
// where: { id: userFinancialId, user: { id: userExist.id }, type: updateDto.type },
|
||||
// });
|
||||
|
||||
if (!existingFinancial) throw new BadRequestException(FinancialMessage.FINANCIAL_INFO_NOT_FOUND);
|
||||
// if (!existingFinancial) throw new BadRequestException(FinancialMessage.FINANCIAL_INFO_NOT_FOUND);
|
||||
|
||||
await this.userFinancialRepository.save({
|
||||
...existingFinancial,
|
||||
updateDto,
|
||||
});
|
||||
// await this.userFinancialRepository.save({
|
||||
// ...existingFinancial,
|
||||
// updateDto,
|
||||
// });
|
||||
|
||||
return {
|
||||
message: CommonMessage.UPDATE_SUCCESS,
|
||||
userFinancial: existingFinancial,
|
||||
};
|
||||
}
|
||||
// return {
|
||||
// message: CommonMessage.UPDATE_SUCCESS,
|
||||
// userFinancial: existingFinancial,
|
||||
// };
|
||||
// }
|
||||
|
||||
/************************************************************ */
|
||||
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
import { Injectable } from "@nestjs/common";
|
||||
import { InjectRepository } from "@nestjs/typeorm";
|
||||
import { Repository } from "typeorm";
|
||||
|
||||
import { LegalUser } from "../entities/legal-user.entity";
|
||||
|
||||
@Injectable()
|
||||
export class LegalUserRepository extends Repository<LegalUser> {
|
||||
constructor(@InjectRepository(LegalUser) LegalUserRepository: Repository<LegalUser>) {
|
||||
super(LegalUserRepository.target, LegalUserRepository.manager, LegalUserRepository.queryRunner);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { Injectable } from "@nestjs/common";
|
||||
import { InjectRepository } from "@nestjs/typeorm";
|
||||
import { Repository } from "typeorm";
|
||||
|
||||
import { RealUser } from "../entities/real-user.entity";
|
||||
|
||||
@Injectable()
|
||||
export class RealUserRepository extends Repository<RealUser> {
|
||||
constructor(@InjectRepository(RealUser) realUserRepository: Repository<RealUser>) {
|
||||
super(realUserRepository.target, realUserRepository.manager, realUserRepository.queryRunner);
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
import { Injectable } from "@nestjs/common";
|
||||
import { InjectRepository } from "@nestjs/typeorm";
|
||||
import { Repository } from "typeorm";
|
||||
|
||||
import { UserFinancial } from "../entities/user-financial.entity";
|
||||
|
||||
@Injectable()
|
||||
export class UserFinancialRepository extends Repository<UserFinancial> {
|
||||
constructor(@InjectRepository(UserFinancial) userFinancialRepository: Repository<UserFinancial>) {
|
||||
super(userFinancialRepository.target, userFinancialRepository.manager, userFinancialRepository.queryRunner);
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,7 @@
|
||||
import { Body, Controller, Get, HttpCode, HttpStatus, Param, Patch, Post, Query } from "@nestjs/common";
|
||||
import { Body, Controller, Get, HttpCode, HttpStatus, Patch, Post, Query } from "@nestjs/common";
|
||||
import { ApiOperation, ApiTags } from "@nestjs/swagger";
|
||||
|
||||
import { CheckValidityDTO } from "./DTO/check-validity.dto";
|
||||
import { CreateFinancialDto } from "./DTO/create-user-financial.dto";
|
||||
import { SearchAdminsDto } from "./DTO/search-admins.dto";
|
||||
import { SearchCustomersDto } from "./DTO/search-customers.dto";
|
||||
import { UpdateProfileDto } from "./DTO/update-profile.dto";
|
||||
@@ -13,7 +12,6 @@ import { UsersService } from "./providers/users.service";
|
||||
import { AuthGuards } from "../../common/decorators/auth-guard.decorator";
|
||||
import { Roles } from "../../common/decorators/roles.decorator";
|
||||
import { UserDec } from "../../common/decorators/user.decorator";
|
||||
import { ParamDto } from "../../common/DTO/param.dto";
|
||||
|
||||
@Controller("users")
|
||||
@ApiTags("users")
|
||||
@@ -91,23 +89,23 @@ export class UsersController {
|
||||
|
||||
/************************************************************ */
|
||||
|
||||
@AuthGuards()
|
||||
@ApiOperation({ summary: "Create user financial" })
|
||||
@HttpCode(HttpStatus.CREATED)
|
||||
@Post("user-financial")
|
||||
createUserFinancial(@Body() createDto: CreateFinancialDto, @UserDec() user: User) {
|
||||
return this.usersService.createUserFinancial(createDto, user);
|
||||
}
|
||||
// @AuthGuards()
|
||||
// @ApiOperation({ summary: "Create user financial" })
|
||||
// @HttpCode(HttpStatus.CREATED)
|
||||
// @Post("user-financial")
|
||||
// createUserFinancial(@Body() createDto: CreateFinancialDto, @UserDec() user: User) {
|
||||
// return this.usersService.createUserFinancial(createDto, user);
|
||||
// }
|
||||
|
||||
/************************************************************ */
|
||||
|
||||
@AuthGuards()
|
||||
@ApiOperation({ summary: "update user financial" })
|
||||
@HttpCode(HttpStatus.CREATED)
|
||||
@Patch("user-financial/:id/update")
|
||||
updateUserFinancial(@Body() updateDto: CreateFinancialDto, @UserDec() user: User, @Param() paramDto: ParamDto) {
|
||||
return this.usersService.updateUserFinancial(updateDto, user, paramDto.id);
|
||||
}
|
||||
// @AuthGuards()
|
||||
// @ApiOperation({ summary: "update user financial" })
|
||||
// @HttpCode(HttpStatus.CREATED)
|
||||
// @Patch("user-financial/:id/update")
|
||||
// updateUserFinancial(@Body() updateDto: CreateFinancialDto, @UserDec() user: User, @Param() paramDto: ParamDto) {
|
||||
// return this.usersService.updateUserFinancial(updateDto, user, paramDto.id);
|
||||
// }
|
||||
|
||||
/************************************************************ */
|
||||
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import { Module } from "@nestjs/common";
|
||||
import { TypeOrmModule } from "@nestjs/typeorm";
|
||||
|
||||
import { LegalUser } from "./entities/legal-user.entity";
|
||||
import { Role } from "./entities/role.entity";
|
||||
import { UserGroup } from "./entities/user-group.entity";
|
||||
import { User } from "./entities/user.entity";
|
||||
import { UsersService } from "./providers/users.service";
|
||||
import { LegalUserRepository } from "./repositories/legal-user.repository";
|
||||
import { RoleRepository } from "./repositories/roles.repository";
|
||||
import { UserGroupRepository } from "./repositories/user-group.repository";
|
||||
import { UserRepository } from "./repositories/users.repository";
|
||||
@@ -13,21 +15,22 @@ import { UserSetting } from "../settings/entities/user-setting.entity";
|
||||
import { UserSettingsService } from "../settings/providers/user-settings.service";
|
||||
import { UserSettingsRepository } from "../settings/repositories/user-settings.repository";
|
||||
import { WalletsModule } from "../wallets/wallets.module";
|
||||
import { UserFinancial } from "./entities/user-financial.entity";
|
||||
import { UserFinancialRepository } from "./repositories/user-financial.repository";
|
||||
import { RealUser } from "./entities/real-user.entity";
|
||||
import { RealUserRepository } from "./repositories/real-user.repository";
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([User, Role, UserGroup, UserSetting, UserFinancial]), WalletsModule],
|
||||
imports: [TypeOrmModule.forFeature([User, Role, UserGroup, UserSetting, RealUser, LegalUser]), WalletsModule],
|
||||
providers: [
|
||||
UsersService,
|
||||
UserRepository,
|
||||
RoleRepository,
|
||||
UserGroupRepository,
|
||||
UserSettingsRepository,
|
||||
UserFinancialRepository,
|
||||
UserSettingsService,
|
||||
RealUserRepository,
|
||||
LegalUserRepository,
|
||||
],
|
||||
controllers: [UsersController],
|
||||
exports: [UsersService],
|
||||
exports: [UsersService, TypeOrmModule, UserRepository],
|
||||
})
|
||||
export class UsersModule {}
|
||||
|
||||
Reference in New Issue
Block a user