89 lines
2.2 KiB
TypeScript
89 lines
2.2 KiB
TypeScript
import { Injectable } from '@nestjs/common';
|
|
import { EntityManager, EntityRepository, FilterQuery } from '@mikro-orm/postgresql';
|
|
import { OrderItem } from '../entities/order-item.entity';
|
|
import { PaginatedResult } from 'src/common/interfaces/pagination.interface';
|
|
import { FindOrderItemsDto } from '../dto/find-order-items.dto';
|
|
|
|
class FindOrderItemsOpts extends FindOrderItemsDto {
|
|
userId?: string;
|
|
isPrintFormAdded?: boolean
|
|
};
|
|
|
|
|
|
@Injectable()
|
|
export class OrderItemRepository extends EntityRepository<OrderItem> {
|
|
constructor(readonly em: EntityManager) {
|
|
super(em, OrderItem);
|
|
}
|
|
|
|
async findAllPaginated(opts: FindOrderItemsOpts): Promise<PaginatedResult<OrderItem>> {
|
|
const {
|
|
page = 1,
|
|
limit = 10,
|
|
search,
|
|
orderBy = 'createdAt',
|
|
order = 'desc',
|
|
userId,
|
|
isPrintFormAdded
|
|
} = opts;
|
|
|
|
const offset = (page - 1) * limit;
|
|
|
|
const where: FilterQuery<OrderItem> = {};
|
|
|
|
|
|
|
|
if (userId) {
|
|
where.order = { user: { id: userId } };
|
|
}
|
|
|
|
if (isPrintFormAdded != undefined) {
|
|
if (isPrintFormAdded == true) {
|
|
where.printFormCreatedAt = { $not: null }
|
|
} else {
|
|
where.printFormCreatedAt = null
|
|
}
|
|
}
|
|
|
|
|
|
// Search by order number or user information
|
|
if (search) {
|
|
const searchPattern = `%${search}%`;
|
|
const searchConditions: any[] = [
|
|
{ user: { firstName: { $ilike: searchPattern } } },
|
|
{ user: { lastName: { $ilike: searchPattern } } },
|
|
{ user: { phone: { $ilike: searchPattern } } },
|
|
];
|
|
|
|
// If search is numeric, also search by orderNumber
|
|
const numericSearch = Number(search);
|
|
if (!isNaN(numericSearch) && isFinite(numericSearch)) {
|
|
searchConditions.push({ orderNumber: numericSearch });
|
|
}
|
|
|
|
where.$or = searchConditions;
|
|
}
|
|
|
|
// First, fetch orders without reviews
|
|
const [data, total] = await this.findAndCount(where, {
|
|
limit,
|
|
offset,
|
|
orderBy: { [orderBy]: order.toLowerCase() as 'asc' | 'desc' },
|
|
populate: ['designer', 'product'],
|
|
});
|
|
|
|
|
|
const totalPages = Math.ceil(total / limit);
|
|
|
|
return {
|
|
data,
|
|
meta: {
|
|
total,
|
|
page,
|
|
limit,
|
|
totalPages,
|
|
},
|
|
};
|
|
}
|
|
}
|