update codes
This commit is contained in:
@@ -0,0 +1,73 @@
|
|||||||
|
import {
|
||||||
|
IsOptional,
|
||||||
|
IsString,
|
||||||
|
IsNumber,
|
||||||
|
Min,
|
||||||
|
IsIn,
|
||||||
|
IsEnum,
|
||||||
|
IsDateString,
|
||||||
|
IsArray,
|
||||||
|
} from 'class-validator';
|
||||||
|
import { Type, Transform } from 'class-transformer';
|
||||||
|
import { ApiPropertyOptional } from '@nestjs/swagger';
|
||||||
|
import { RequestStatusEnum } from '../enum/request';
|
||||||
|
|
||||||
|
const sortOrderOptions = ['asc', 'desc'] as const;
|
||||||
|
type SortOrder = (typeof sortOrderOptions)[number];
|
||||||
|
|
||||||
|
export class FindRequestsDto {
|
||||||
|
@ApiPropertyOptional({ default: 1, minimum: 1 })
|
||||||
|
@IsOptional()
|
||||||
|
@Type(() => Number)
|
||||||
|
@IsNumber()
|
||||||
|
@Min(1)
|
||||||
|
page: number = 1;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ default: 10, minimum: 1 })
|
||||||
|
@IsOptional()
|
||||||
|
@Type(() => Number)
|
||||||
|
@IsNumber()
|
||||||
|
@Min(1)
|
||||||
|
limit: number = 10;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({
|
||||||
|
description: 'Filter by request statuses',
|
||||||
|
enum: RequestStatusEnum,
|
||||||
|
isArray: true,
|
||||||
|
})
|
||||||
|
@IsOptional()
|
||||||
|
@Transform(({ value }) => (Array.isArray(value) ? value : value?.split(',')))
|
||||||
|
@IsArray()
|
||||||
|
@IsEnum(RequestStatusEnum, { each: true })
|
||||||
|
statuses?: RequestStatusEnum[];
|
||||||
|
|
||||||
|
@ApiPropertyOptional({
|
||||||
|
description: 'Search by request number or user info',
|
||||||
|
})
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
search?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ format: 'date-time' })
|
||||||
|
@IsOptional()
|
||||||
|
@IsDateString()
|
||||||
|
from?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ format: 'date-time' })
|
||||||
|
@IsOptional()
|
||||||
|
@IsDateString()
|
||||||
|
to?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ default: 'createdAt' })
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
orderBy: string = 'createdAt';
|
||||||
|
|
||||||
|
@ApiPropertyOptional({
|
||||||
|
enum: sortOrderOptions,
|
||||||
|
default: 'desc',
|
||||||
|
})
|
||||||
|
@IsOptional()
|
||||||
|
@IsIn(sortOrderOptions)
|
||||||
|
order: SortOrder = 'desc';
|
||||||
|
}
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { EntityManager, EntityRepository } from '@mikro-orm/postgresql';
|
||||||
|
import { FilterQuery } from '@mikro-orm/core';
|
||||||
|
import { Request } from '../entities/request.entity';
|
||||||
|
import { PaginatedResult } from 'src/common/interfaces/pagination.interface';
|
||||||
|
import { FindRequestsDto } from '../dto/find-requests.dto';
|
||||||
|
import { RequestStatusEnum } from '../enum/request';
|
||||||
|
|
||||||
|
class FindRequestsOpts extends FindRequestsDto {
|
||||||
|
userId?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class RequestRepository extends EntityRepository<Request> {
|
||||||
|
constructor(readonly em: EntityManager) {
|
||||||
|
super(em, Request);
|
||||||
|
}
|
||||||
|
|
||||||
|
async findAllPaginated(opts: FindRequestsOpts): Promise<PaginatedResult<Request>> {
|
||||||
|
const {
|
||||||
|
page = 1,
|
||||||
|
limit = 10,
|
||||||
|
statuses,
|
||||||
|
search,
|
||||||
|
orderBy = 'createdAt',
|
||||||
|
order = 'desc',
|
||||||
|
userId,
|
||||||
|
from,
|
||||||
|
to,
|
||||||
|
} = opts;
|
||||||
|
|
||||||
|
const offset = (page - 1) * limit;
|
||||||
|
|
||||||
|
const where: FilterQuery<Request> = {};
|
||||||
|
|
||||||
|
if (userId) {
|
||||||
|
where.user = { id: userId };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (statuses) {
|
||||||
|
const normalizedStatuses = Array.isArray(statuses) ? statuses : [statuses];
|
||||||
|
const validStatuses = normalizedStatuses.filter((s): s is RequestStatusEnum => !!s);
|
||||||
|
|
||||||
|
if (validStatuses.length > 0) {
|
||||||
|
if (validStatuses.length === 1) {
|
||||||
|
where.status = validStatuses[0];
|
||||||
|
} else {
|
||||||
|
where.status = { $in: validStatuses };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (from || to) {
|
||||||
|
where.createdAt = {};
|
||||||
|
if (from) {
|
||||||
|
where.createdAt.$gte = new Date(from);
|
||||||
|
}
|
||||||
|
if (to) {
|
||||||
|
where.createdAt.$lte = new Date(to);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (search) {
|
||||||
|
const searchPattern = `%${search}%`;
|
||||||
|
const searchConditions: FilterQuery<Request>[] = [
|
||||||
|
{ user: { firstName: { $ilike: searchPattern } } },
|
||||||
|
{ user: { lastName: { $ilike: searchPattern } } },
|
||||||
|
{ user: { phone: { $ilike: searchPattern } } } as FilterQuery<Request>,
|
||||||
|
];
|
||||||
|
|
||||||
|
const numericSearch = Number(search);
|
||||||
|
if (!isNaN(numericSearch) && isFinite(numericSearch)) {
|
||||||
|
searchConditions.push({ requestNumber: numericSearch } as FilterQuery<Request>);
|
||||||
|
}
|
||||||
|
|
||||||
|
where.$or = searchConditions;
|
||||||
|
}
|
||||||
|
|
||||||
|
const [data, total] = await this.findAndCount(where, {
|
||||||
|
limit,
|
||||||
|
offset,
|
||||||
|
orderBy: { [orderBy]: order.toLowerCase() as 'asc' | 'desc' },
|
||||||
|
populate: ['items', 'items.product', 'user'],
|
||||||
|
});
|
||||||
|
|
||||||
|
const totalPages = Math.ceil(total / limit);
|
||||||
|
|
||||||
|
return {
|
||||||
|
data,
|
||||||
|
meta: {
|
||||||
|
total,
|
||||||
|
page,
|
||||||
|
limit,
|
||||||
|
totalPages,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,9 +1,10 @@
|
|||||||
import { Controller, Get, Post, Body, Patch, Param, Delete, UseGuards } from '@nestjs/common';
|
import { Controller, Get, Post, Body, Patch, Param, Delete, UseGuards, Query } from '@nestjs/common';
|
||||||
import { RequestService } from './request.service';
|
import { RequestService } from './request.service';
|
||||||
import { CreateRequestDto } from './dto/create-request.dto';
|
import { CreateRequestDto } from './dto/create-request.dto';
|
||||||
import { UpdateRequestDto } from './dto/update-request.dto';
|
import { UpdateRequestDto } from './dto/update-request.dto';
|
||||||
import { AuthGuard } from '../auth/guards/auth.guard';
|
import { AuthGuard } from '../auth/guards/auth.guard';
|
||||||
import { UserId } from 'src/common/decorators';
|
import { UserId } from 'src/common/decorators';
|
||||||
|
import { FindRequestsDto } from './dto/find-requests.dto';
|
||||||
|
|
||||||
@Controller()
|
@Controller()
|
||||||
export class RequestController {
|
export class RequestController {
|
||||||
@@ -17,25 +18,25 @@ export class RequestController {
|
|||||||
|
|
||||||
@Get('public/request')
|
@Get('public/request')
|
||||||
@UseGuards(AuthGuard)
|
@UseGuards(AuthGuard)
|
||||||
findAll() {
|
findAll(@Query() dto: FindRequestsDto, @UserId() userId: string) {
|
||||||
return this.requestService.findAll();
|
return this.requestService.findAll(userId, dto);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Get('public/request:id')
|
@Get('public/request/:id')
|
||||||
@UseGuards(AuthGuard)
|
@UseGuards(AuthGuard)
|
||||||
findOne(@Param('id') id: string) {
|
findOne(@Param('id') id: string, @UserId() userId: string) {
|
||||||
return this.requestService.findOne(+id);
|
return this.requestService.findOne(id, userId);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Patch('public/request:id')
|
@Patch('public/request/:id')
|
||||||
@UseGuards(AuthGuard)
|
@UseGuards(AuthGuard)
|
||||||
update(@Param('id') id: string, @Body() updateRequestDto: UpdateRequestDto) {
|
update(@Param('id') id: string, @Body() updateRequestDto: UpdateRequestDto, @UserId() userId: string) {
|
||||||
return this.requestService.update(+id, updateRequestDto);
|
return this.requestService.update(id, updateRequestDto, userId);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Delete('public/request:id')
|
@Delete('public/request/:id')
|
||||||
@UseGuards(AuthGuard)
|
@UseGuards(AuthGuard)
|
||||||
remove(@Param('id') id: string) {
|
remove(@Param('id') id: string, @UserId() userId: string) {
|
||||||
return this.requestService.remove(+id);
|
return this.requestService.remove(id, userId);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import { RequestService } from './request.service';
|
|||||||
import { RequestController } from './request.controller';
|
import { RequestController } from './request.controller';
|
||||||
import { Request } from './entities/request.entity';
|
import { Request } from './entities/request.entity';
|
||||||
import { RequestItem } from './entities/request-item.entity';
|
import { RequestItem } from './entities/request-item.entity';
|
||||||
|
import { RequestRepository } from './repositories/request.repository';
|
||||||
import { UserModule } from '../user/user.module';
|
import { UserModule } from '../user/user.module';
|
||||||
import { ProductModule } from '../product/product.module';
|
import { ProductModule } from '../product/product.module';
|
||||||
|
|
||||||
@@ -14,6 +15,6 @@ import { ProductModule } from '../product/product.module';
|
|||||||
ProductModule,
|
ProductModule,
|
||||||
],
|
],
|
||||||
controllers: [RequestController],
|
controllers: [RequestController],
|
||||||
providers: [RequestService],
|
providers: [RequestService, RequestRepository],
|
||||||
})
|
})
|
||||||
export class RequestModule {}
|
export class RequestModule {}
|
||||||
|
|||||||
@@ -1,17 +1,20 @@
|
|||||||
import { Injectable } from '@nestjs/common';
|
import { Injectable, NotFoundException, BadRequestException } from '@nestjs/common';
|
||||||
import { EntityManager } from '@mikro-orm/postgresql';
|
import { EntityManager } from '@mikro-orm/postgresql';
|
||||||
import { CreateRequestDto } from './dto/create-request.dto';
|
import { CreateRequestDto } from './dto/create-request.dto';
|
||||||
import { UpdateRequestDto } from './dto/update-request.dto';
|
import { UpdateRequestDto } from './dto/update-request.dto';
|
||||||
|
import { FindRequestsDto } from './dto/find-requests.dto';
|
||||||
import { Request } from './entities/request.entity';
|
import { Request } from './entities/request.entity';
|
||||||
import { RequestItem } from './entities/request-item.entity';
|
import { RequestItem } from './entities/request-item.entity';
|
||||||
import { RequestStatusEnum } from './enum/request';
|
import { RequestStatusEnum } from './enum/request';
|
||||||
import { UserService } from '../user/providers/user.service';
|
import { UserService } from '../user/providers/user.service';
|
||||||
import { ProductService } from '../product/providers/product.service';
|
import { ProductService } from '../product/providers/product.service';
|
||||||
|
import { RequestRepository } from './repositories/request.repository';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class RequestService {
|
export class RequestService {
|
||||||
constructor(
|
constructor(
|
||||||
private readonly em: EntityManager,
|
private readonly em: EntityManager,
|
||||||
|
private readonly requestRepository: RequestRepository,
|
||||||
private readonly userService: UserService,
|
private readonly userService: UserService,
|
||||||
private readonly productService: ProductService,
|
private readonly productService: ProductService,
|
||||||
) {}
|
) {}
|
||||||
@@ -46,19 +49,69 @@ export class RequestService {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
findAll() {
|
findAll(userId: string, dto: FindRequestsDto) {
|
||||||
return `This action returns all request`;
|
return this.requestRepository.findAllPaginated({ userId, ...dto });
|
||||||
}
|
}
|
||||||
|
|
||||||
findOne(id: number) {
|
async findOne(id: string, userId: string) {
|
||||||
return `This action returns a #${id} request`;
|
const request = await this.requestRepository.findOne(
|
||||||
|
{ id, user: { id: userId } },
|
||||||
|
{ populate: ['items', 'items.product', 'user'] },
|
||||||
|
);
|
||||||
|
if (!request) {
|
||||||
|
throw new NotFoundException('Request not found');
|
||||||
|
}
|
||||||
|
return request;
|
||||||
}
|
}
|
||||||
|
|
||||||
update(id: number, updateRequestDto: UpdateRequestDto) {
|
async update(id: string, updateRequestDto: UpdateRequestDto, userId: string) {
|
||||||
return `This action updates a #${id} request`;
|
const request = await this.requestRepository.findOne(
|
||||||
|
{ id, user: { id: userId } },
|
||||||
|
{ populate: ['items', 'items.product', 'user'] },
|
||||||
|
);
|
||||||
|
if (!request) {
|
||||||
|
throw new NotFoundException('Request not found');
|
||||||
|
}
|
||||||
|
|
||||||
|
const { items } = updateRequestDto;
|
||||||
|
if (items?.length) {
|
||||||
|
return this.em.transactional(async (em) => {
|
||||||
|
request.items.removeAll();
|
||||||
|
await em.flush();
|
||||||
|
|
||||||
|
for (const item of items) {
|
||||||
|
const product = await this.productService.findOneOrFail(item.productId);
|
||||||
|
const requestItem = em.create(RequestItem, {
|
||||||
|
request,
|
||||||
|
product,
|
||||||
|
quantity: item.quantity,
|
||||||
|
attributes: item.attributes,
|
||||||
|
description: item.description,
|
||||||
|
attachments: item.attachments,
|
||||||
|
});
|
||||||
|
request.items.add(requestItem);
|
||||||
|
}
|
||||||
|
|
||||||
|
await em.flush();
|
||||||
|
return request;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return request;
|
||||||
}
|
}
|
||||||
|
|
||||||
remove(id: number) {
|
async remove(id: string, userId: string) {
|
||||||
return `This action removes a #${id} request`;
|
const request = await this.requestRepository.findOne(
|
||||||
|
{ id, user: { id: userId } },
|
||||||
|
);
|
||||||
|
if (!request) {
|
||||||
|
throw new NotFoundException('Request not found');
|
||||||
|
}
|
||||||
|
if (request.status !== RequestStatusEnum.PENDING) {
|
||||||
|
throw new BadRequestException('Only pending requests can be deleted');
|
||||||
|
}
|
||||||
|
request.deletedAt = new Date();
|
||||||
|
await this.em.flush();
|
||||||
|
return request;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user