update codes
This commit is contained in:
@@ -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,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user