design request module
This commit is contained in:
@@ -12,6 +12,7 @@ import { BusinessModule } from './modules/business/business.module';
|
||||
import { CatalogueModule } from './modules/catalogue/catalogue.module';
|
||||
import { HttpModule } from '@nestjs/axios';
|
||||
import { IconsModule } from './modules/icons/icons.module';
|
||||
import { DesignRequestModule } from './modules/design-request/design-request.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
@@ -32,6 +33,7 @@ import { IconsModule } from './modules/icons/icons.module';
|
||||
CatalogueModule,
|
||||
HttpModule.register({ global: true, timeout: 10000, headers: { "Content-Type": "application/json" } }),
|
||||
IconsModule,
|
||||
DesignRequestModule,
|
||||
],
|
||||
controllers: [],
|
||||
providers: [],
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import { Controller, Get, Post, Body, Patch, Param, Query, UseGuards } from '@nestjs/common';
|
||||
import { DesignRequestService } from './design-request.service';
|
||||
import { CreateDesignRequestDto } from './dto/create-design-request.dto';
|
||||
import { AdminAuthGuard } from '../auth/guards/adminAuth.guard';
|
||||
import { BusinessId } from 'src/common/decorators';
|
||||
import { SuperAdminAuthGuard } from '../auth/guards/superAdminAuth.guard';
|
||||
import { FinishDesignRequestDto } from './dto/finish-design-request.dto';
|
||||
import { FindDesignRequestsDto } from './dto/find-design-requests.dto';
|
||||
import { MarkDesignRequestPaidDto } from './dto/mark-design-request-paid.dto';
|
||||
|
||||
@Controller()
|
||||
export class DesignRequestController {
|
||||
constructor(private readonly designRequestService: DesignRequestService) { }
|
||||
|
||||
|
||||
@Get('admin/design-request')
|
||||
@UseGuards(AdminAuthGuard)
|
||||
findAll(@Query() queryDto: FindDesignRequestsDto, @BusinessId() businessId: string) {
|
||||
return this.designRequestService.findAll(businessId, queryDto);
|
||||
}
|
||||
|
||||
@Get('admin/design-request/:id')
|
||||
@UseGuards(AdminAuthGuard)
|
||||
findOne(@Param('id') id: string, @BusinessId() businessId: string) {
|
||||
return this.designRequestService.findOne(id, businessId);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Post('admin/design-request/initiate')
|
||||
@UseGuards(AdminAuthGuard)
|
||||
createDesignRequest(@Body() dto: CreateDesignRequestDto, @BusinessId() businessId: string) {
|
||||
return this.designRequestService.createDesignRequest(dto, businessId);
|
||||
}
|
||||
|
||||
// =============== super admin endpoints =============
|
||||
|
||||
@Get('super-admin/design-request/list')
|
||||
@UseGuards(SuperAdminAuthGuard)
|
||||
findAllAsSuperAdmin(@Query() queryDto: FindDesignRequestsDto) {
|
||||
return this.designRequestService.findAllAsSuperAdmin(queryDto);
|
||||
}
|
||||
|
||||
@Post('super-admin/design-request/finish')
|
||||
@UseGuards(SuperAdminAuthGuard)
|
||||
finishDesignRequest(@Body() dto: FinishDesignRequestDto) {
|
||||
return this.designRequestService.finishDesignRequest(dto);
|
||||
}
|
||||
|
||||
@Patch('super-admin/design-request/:id/paid')
|
||||
@UseGuards(SuperAdminAuthGuard)
|
||||
markAsPaid(@Param('id') id: string, @Body() dto: MarkDesignRequestPaidDto) {
|
||||
return this.designRequestService.markAsPaid(id, dto);
|
||||
}
|
||||
|
||||
// =============== end =============
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { MikroOrmModule } from '@mikro-orm/nestjs';
|
||||
import { DesignRequestService } from './design-request.service';
|
||||
import { DesignRequestController } from './design-request.controller';
|
||||
import { DesignRequest } from './entities/design-request.entity';
|
||||
import { BusinessModule } from '../business/business.module';
|
||||
import { JwtModule } from '@nestjs/jwt';
|
||||
|
||||
@Module({
|
||||
imports: [MikroOrmModule.forFeature([DesignRequest]), BusinessModule,JwtModule],
|
||||
controllers: [DesignRequestController],
|
||||
providers: [DesignRequestService],
|
||||
})
|
||||
export class DesignRequestModule {}
|
||||
@@ -0,0 +1,162 @@
|
||||
import { Inject, Injectable, Logger, NotFoundException } from '@nestjs/common';
|
||||
import { CreateDesignRequestDto } from './dto/create-design-request.dto';
|
||||
import { UpdateDesignRequestDto } from './dto/update-design-request.dto';
|
||||
import { FinishDesignRequestDto } from './dto/finish-design-request.dto';
|
||||
import { MarkDesignRequestPaidDto } from './dto/mark-design-request-paid.dto';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { HttpService } from '@nestjs/axios';
|
||||
import { AxiosError } from 'axios';
|
||||
import { catchError, firstValueFrom, throwError } from 'rxjs';
|
||||
import { EntityManager } from '@mikro-orm/postgresql';
|
||||
import { BusinessService } from '../business/business.service';
|
||||
import { CreateExternalInvoiceDto } from '../catalogue/dto/create-invoice.dto';
|
||||
import { DesignRequest } from './entities/design-request.entity';
|
||||
import { DesignRequestRepository } from './repositories/design-request.repository';
|
||||
import { FindDesignRequestsDto } from './dto/find-design-requests.dto';
|
||||
|
||||
@Injectable()
|
||||
export class DesignRequestService {
|
||||
private readonly logger = new Logger(DesignRequestService.name);
|
||||
|
||||
constructor(
|
||||
private readonly em: EntityManager,
|
||||
private readonly designRequestRepository: DesignRequestRepository,
|
||||
private readonly businessService: BusinessService,
|
||||
private readonly httpService: HttpService,
|
||||
@Inject(ConfigService)
|
||||
private readonly configService: ConfigService,
|
||||
) {}
|
||||
|
||||
private getDesignUnitPrice(count: number): number {
|
||||
if (count < 10) {
|
||||
return +this.configService.getOrThrow<number>('DESIGN_PRICE_UNDER_10');
|
||||
}
|
||||
if (count <= 30) {
|
||||
return +this.configService.getOrThrow<number>('DESIGN_PRICE_10_TO_30');
|
||||
}
|
||||
return +this.configService.getOrThrow<number>('DESIGN_PRICE_ABOVE_30');
|
||||
}
|
||||
|
||||
async createDesignRequest(dto: CreateDesignRequestDto, businessId: string) {
|
||||
const { title, count, desc, expectedDate, attachments } = dto;
|
||||
|
||||
const business = await this.businessService.findByIdOrFail(businessId);
|
||||
|
||||
const danakApiUrl = this.configService.getOrThrow('DANAK_API_URL');
|
||||
const xApiKey = this.configService.getOrThrow('EXTERNAL_API_KEYS');
|
||||
const unitPrice = this.getDesignUnitPrice(count);
|
||||
|
||||
const params: CreateExternalInvoiceDto = {
|
||||
danakSubscriptionId: business.danakSubscriptionId,
|
||||
businessId,
|
||||
items: [
|
||||
{
|
||||
name: 'purchase_design',
|
||||
count,
|
||||
unitPrice,
|
||||
discount: 0,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
let invoiceData: { id: string };
|
||||
|
||||
try {
|
||||
const { data } = await firstValueFrom(
|
||||
this.httpService
|
||||
.post(`${danakApiUrl}/invoices/external/create`, params, {
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-API-Key': xApiKey,
|
||||
},
|
||||
})
|
||||
.pipe(
|
||||
catchError((err: AxiosError) => {
|
||||
this.logger.error(`Failed to create invoice: ${err.message}`, err.stack);
|
||||
return throwError(() => err);
|
||||
}),
|
||||
),
|
||||
);
|
||||
invoiceData = data;
|
||||
} catch (error: unknown) {
|
||||
this.logger.error(
|
||||
`Error create invoice: ${error instanceof Error ? error.message : 'Unknown error'}`,
|
||||
);
|
||||
throw error;
|
||||
}
|
||||
|
||||
const designRequest = this.em.create(DesignRequest, {
|
||||
title,
|
||||
count,
|
||||
desc,
|
||||
expectedDate: expectedDate ? new Date(expectedDate) : undefined,
|
||||
attachments: attachments ?? [],
|
||||
invoiceId: invoiceData.id,
|
||||
business,
|
||||
});
|
||||
|
||||
await this.em.persistAndFlush(designRequest);
|
||||
|
||||
return designRequest;
|
||||
}
|
||||
|
||||
async finishDesignRequest(dto: FinishDesignRequestDto) {
|
||||
const { businessId, invoiceId } = dto;
|
||||
|
||||
await this.businessService.findByIdOrFail(businessId);
|
||||
|
||||
const designRequest = await this.em.findOne(DesignRequest, { invoiceId });
|
||||
if (!designRequest) {
|
||||
throw new NotFoundException('design request not found');
|
||||
}
|
||||
|
||||
designRequest.paidAt = new Date();
|
||||
await this.em.flush();
|
||||
|
||||
return designRequest;
|
||||
}
|
||||
|
||||
async markAsPaid(id: string, dto: MarkDesignRequestPaidDto = {}) {
|
||||
const designRequest = await this.em.findOne(DesignRequest, { id });
|
||||
if (!designRequest) {
|
||||
throw new NotFoundException('design request not found');
|
||||
}
|
||||
|
||||
designRequest.paidAt = dto.paidAt ? new Date(dto.paidAt) : new Date();
|
||||
await this.em.flush();
|
||||
|
||||
return designRequest;
|
||||
}
|
||||
|
||||
async findAll(businessId: string, dto: FindDesignRequestsDto) {
|
||||
await this.businessService.findByIdOrFail(businessId);
|
||||
|
||||
return this.designRequestRepository.findAllPaginated(dto, businessId);
|
||||
}
|
||||
|
||||
findAllAsSuperAdmin(dto: FindDesignRequestsDto) {
|
||||
return this.designRequestRepository.findAllPaginated(dto);
|
||||
}
|
||||
|
||||
async findOne(id: string, businessId: string) {
|
||||
await this.businessService.findByIdOrFail(businessId);
|
||||
|
||||
const designRequest = await this.em.findOne(DesignRequest, {
|
||||
id,
|
||||
business: { id: businessId },
|
||||
});
|
||||
if (!designRequest) {
|
||||
throw new NotFoundException('design request not found');
|
||||
}
|
||||
|
||||
return designRequest;
|
||||
}
|
||||
|
||||
update(id: number, updateDesignRequestDto: UpdateDesignRequestDto) {
|
||||
return `This action updates a #${id} designRequest`;
|
||||
}
|
||||
|
||||
remove(id: number) {
|
||||
return `This action removes a #${id} designRequest`;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { IsArray, IsDateString, IsInt, IsNotEmpty, IsOptional, IsString, Min } from 'class-validator';
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
|
||||
export class CreateDesignRequestDto {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@ApiProperty()
|
||||
title: string;
|
||||
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
@ApiProperty()
|
||||
count: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@ApiPropertyOptional()
|
||||
desc?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsDateString()
|
||||
@ApiPropertyOptional()
|
||||
expectedDate?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
@IsString({ each: true })
|
||||
@ApiPropertyOptional({ type: [String] })
|
||||
attachments?: string[];
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { IsOptional, IsNumber, IsString, IsIn } from 'class-validator';
|
||||
import { ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { Type } from 'class-transformer';
|
||||
|
||||
export class FindDesignRequestsDto {
|
||||
@IsOptional()
|
||||
@IsNumber()
|
||||
@Type(() => Number)
|
||||
@ApiPropertyOptional({ example: 1 })
|
||||
page?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsNumber()
|
||||
@Type(() => Number)
|
||||
@ApiPropertyOptional({ example: 10 })
|
||||
limit?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@ApiPropertyOptional({ example: 'createdAt' })
|
||||
orderBy?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsIn(['asc', 'desc'])
|
||||
@ApiPropertyOptional({ example: 'desc' })
|
||||
order?: 'asc' | 'desc';
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
|
||||
import { IsInt, IsNotEmpty, IsString } from 'class-validator';
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
|
||||
export class FinishDesignRequestDto {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@ApiProperty()
|
||||
businessId: string;
|
||||
|
||||
@IsString()
|
||||
@ApiProperty()
|
||||
invoiceId: string;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { IsDateString, IsOptional } from 'class-validator';
|
||||
import { ApiPropertyOptional } from '@nestjs/swagger';
|
||||
|
||||
export class MarkDesignRequestPaidDto {
|
||||
@IsOptional()
|
||||
@IsDateString()
|
||||
@ApiPropertyOptional({ example: '2026-06-07T12:00:00.000Z' })
|
||||
paidAt?: string;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
import { PartialType } from '@nestjs/swagger';
|
||||
import { CreateDesignRequestDto } from './create-design-request.dto';
|
||||
|
||||
export class UpdateDesignRequestDto extends PartialType(CreateDesignRequestDto) {}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { Entity, EntityRepositoryType, Index, ManyToOne, Property } from '@mikro-orm/core';
|
||||
import { BaseEntity } from '../../../common/entities/base.entity';
|
||||
import { Business } from '../../business/entities/business.entity';
|
||||
import { DesignRequestRepository } from '../repositories/design-request.repository';
|
||||
|
||||
@Entity({ tableName: 'design_requests', repository: () => DesignRequestRepository })
|
||||
@Index({ properties: ['invoiceId'] })
|
||||
@Index({ properties: ['business.id'] })
|
||||
export class DesignRequest extends BaseEntity {
|
||||
@Property({ type: 'varchar', length: 255, nullable: false })
|
||||
title!: string;
|
||||
|
||||
@Property({ type: 'integer', nullable: false, default: 1 })
|
||||
count!: number;
|
||||
|
||||
@Property({ type: 'text', nullable: true })
|
||||
desc?: string;
|
||||
|
||||
@Property({ type: 'timestamptz', nullable: true })
|
||||
expectedDate?: Date;
|
||||
|
||||
@Property({ type: 'json', default: [] })
|
||||
attachments: string[] = [];
|
||||
|
||||
@Property({ type: 'uuid', nullable: false })
|
||||
invoiceId!: string;
|
||||
|
||||
@Property({ type: 'timestamptz', nullable: true })
|
||||
paidAt?: Date;
|
||||
|
||||
@ManyToOne(() => Business, { deleteRule: 'restrict' })
|
||||
business!: Business;
|
||||
|
||||
[EntityRepositoryType]?: DesignRequestRepository;
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { EntityRepository, FilterQuery } from '@mikro-orm/postgresql';
|
||||
import { PaginatedResult } from 'src/common/interfaces/pagination.interface';
|
||||
import { FindDesignRequestsDto } from '../dto/find-design-requests.dto';
|
||||
import { DesignRequest } from '../entities/design-request.entity';
|
||||
|
||||
export class DesignRequestRepository extends EntityRepository<DesignRequest> {
|
||||
async findAllPaginated(
|
||||
opts: FindDesignRequestsDto = {},
|
||||
businessId?: string,
|
||||
): Promise<PaginatedResult<DesignRequest>> {
|
||||
const { page = 1, limit = 10, orderBy = 'createdAt', order = 'desc' } = opts;
|
||||
|
||||
const offset = (page - 1) * limit;
|
||||
|
||||
const where: FilterQuery<DesignRequest> = businessId
|
||||
? { business: { id: businessId } }
|
||||
: {};
|
||||
|
||||
const [data, total] = await this.findAndCount(where, {
|
||||
limit,
|
||||
offset,
|
||||
orderBy: { [orderBy]: order.toLowerCase() as 'asc' | 'desc' },
|
||||
populate: businessId ? [] : ['business'],
|
||||
});
|
||||
|
||||
const totalPages = Math.ceil(total / limit);
|
||||
|
||||
return {
|
||||
data,
|
||||
meta: {
|
||||
total,
|
||||
page,
|
||||
limit,
|
||||
totalPages,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user