fix: bill

This commit is contained in:
2026-02-17 11:08:22 +03:30
parent 2cac3a4925
commit 00404c38d2
5 changed files with 126 additions and 29 deletions
@@ -1,4 +1,3 @@
import { FilterQuery } from "@mikro-orm/core";
import { EntityRepository } from "@mikro-orm/postgresql";
import { PaginationUtils } from "../../utils/providers/pagination.utils";
@@ -6,32 +5,65 @@ import { BillListQueryDto } from "../dto/bill-list-query.dto";
import { Bill } from "../entities/bill.entity";
export class BillsRepository extends EntityRepository<Bill> {
async getBillsList(queryDto: BillListQueryDto, businessId: string) {
const { limit, skip } = PaginationUtils(queryDto);
const where: FilterQuery<Bill> = {
business: { id: businessId },
};
const knex = this.em.getKnex();
const query = knex
.select('b.*')
.select(knex.raw('COUNT(i.id) as invoice_count'))
.from('bill as b')
.leftJoin('invoice as i', 'i.bill_id', 'b.id')
.where('b.business_id', businessId)
.groupBy('b.id')
.orderBy('b.created_at', 'desc')
.limit(limit)
.offset(skip);
// Add filters
if (queryDto.type) {
where.type = queryDto.type;
query.andWhere('b.type', queryDto.type);
}
if (queryDto.since || queryDto.to) {
where.createdAt = {};
if (queryDto.since) {
(where.createdAt as Record<string, unknown>).$gte = new Date(queryDto.since);
}
if (queryDto.to) {
(where.createdAt as Record<string, unknown>).$lte = new Date(queryDto.to);
}
if (queryDto.since) {
query.andWhere('b.created_at', '>=', new Date(queryDto.since));
}
return this.findAndCount(where, {
populate: ["invoices"],
orderBy: { createdAt: "DESC" },
limit,
offset: skip,
if (queryDto.to) {
query.andWhere('b.created_at', '<=', new Date(queryDto.to));
}
// Execute the query
const results = await query;
// Get total count for pagination
const countQuery = knex('bill')
.count('* as total')
.where('business_id', businessId);
if (queryDto.type) {
countQuery.andWhere('type', queryDto.type);
}
if (queryDto.since) {
countQuery.andWhere('created_at', '>=', new Date(queryDto.since));
}
if (queryDto.to) {
countQuery.andWhere('created_at', '<=', new Date(queryDto.to));
}
const totalResult = await countQuery;
const total = Number(totalResult[0].total);
// Map results back to Bill entities (invoice_count from knex may be string/bigint)
const bills = results.map((row) => {
const bill = this.em.map(Bill, row);
bill.invoiceCount = Number(row.invoice_count ?? 0);
return bill;
});
return [bills, total];
}
}