This commit is contained in:
2026-02-18 23:58:03 +03:30
parent 6b2aeddedd
commit 5cc9211e49
9 changed files with 443 additions and 33 deletions
@@ -0,0 +1,88 @@
import { Injectable } from '@nestjs/common';
import { EntityManager, EntityRepository } from '@mikro-orm/postgresql';
import { FilterQuery } from '@mikro-orm/core';
import { Invoice } from '../entities/invoice.entity';
import { PaginatedResult } from 'src/common/interfaces/pagination.interface';
import { FindInvoicesDto } from '../dto/find-invoices.dto';
interface FindInvoicesOpts extends FindInvoicesDto {
userId?: string;
}
@Injectable()
export class InvoiceRepository extends EntityRepository<Invoice> {
constructor(readonly em: EntityManager) {
super(em, Invoice);
}
async findAllPaginated(opts: FindInvoicesOpts): Promise<PaginatedResult<Invoice>> {
const {
page = 1,
limit = 10,
search,
orderBy = 'createdAt',
order = 'desc',
userId,
from,
to,
enableTax,
} = opts;
const offset = (page - 1) * limit;
const where: FilterQuery<Invoice> = {};
if (userId) {
where.user = { id: userId };
}
if (typeof enableTax === 'boolean') {
where.enableTax = enableTax;
}
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<Invoice>[] = [
{ user: { firstName: { $ilike: searchPattern } } } as FilterQuery<Invoice>,
{ user: { lastName: { $ilike: searchPattern } } } as FilterQuery<Invoice>,
{ user: { phone: { $ilike: searchPattern } } } as FilterQuery<Invoice>,
];
const numericSearch = Number(search);
if (!isNaN(numericSearch) && isFinite(numericSearch)) {
searchConditions.push({ invoiceNumber: numericSearch } as FilterQuery<Invoice>);
}
where.$or = searchConditions;
}
const [data, total] = await this.findAndCount(where, {
limit,
offset,
orderBy: { [orderBy]: order.toLowerCase() as 'asc' | 'desc' },
populate: ['user', 'request', 'items', 'items.product'],
});
const totalPages = Math.ceil(total / limit);
return {
data,
meta: {
total,
page,
limit,
totalPages,
},
};
}
}