import { FilterQuery } from "@mikro-orm/core"; import { EntityRepository } from "@mikro-orm/postgresql"; import { PaginationUtils } from "../../utils/providers/pagination.utils"; import { InvoicesSearchQueryDto } from "../DTO/invoices-search-query.dto"; import { Invoice } from "../entities/invoice.entity"; export class InvoicesRepository extends EntityRepository { // async getInvoicesForAdmin(queryDto: InvoicesSearchQueryDto, businessId: string) { const { limit, skip } = PaginationUtils(queryDto); const where: FilterQuery = { business: { id: businessId } }; if (queryDto.q) { where.$or = [ { company: { user: { firstName: { $ilike: `%${queryDto.q}%` } } } }, { company: { user: { lastName: { $ilike: `%${queryDto.q}%` } } } }, { company: { user: { email: { $ilike: `%${queryDto.q}%` } } } }, ]; } if (queryDto.status) { where.status = queryDto.status; } if (queryDto.companyId) { where.company = { id: queryDto.companyId }; } if (queryDto.billId) { where.bill = { id: queryDto.billId }; } if (queryDto.since || queryDto.to) { const dateConditions = []; if (queryDto.since) { const sinceDate = new Date(queryDto.since); dateConditions.push({ createdAt: { $gte: sinceDate } }, { dueDate: { $gte: sinceDate } }, { paidAt: { $gte: sinceDate } }); } if (queryDto.to) { const toDate = new Date(queryDto.to); dateConditions.push({ createdAt: { $lte: toDate } }, { dueDate: { $lte: toDate } }, { paidAt: { $lte: toDate } }); } if (queryDto.since && queryDto.to) { const sinceDate = new Date(queryDto.since); const toDate = new Date(queryDto.to); where.$and = [ { $or: [ { createdAt: { $gte: sinceDate, $lte: toDate } }, { dueDate: { $gte: sinceDate, $lte: toDate } }, { paidAt: { $gte: sinceDate, $lte: toDate } }, ], }, ]; } else { where.$or = dateConditions; } } return this.findAndCount(where, { populate: ["company", "items"], orderBy: { createdAt: "DESC" }, limit, offset: skip, }); } }