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
+21 -5
View File
@@ -1,19 +1,21 @@
import { Body, Controller, Delete, Get, Param, Post, Query, UseInterceptors } from "@nestjs/common";
import { ApiOperation } from "@nestjs/swagger";
import { FileInterceptor } from "@nest-lab/fastify-multer";
import { Body, Controller, Delete, Get, Param, Post, Query, UploadedFile, UseInterceptors } from "@nestjs/common";
import { ApiBody, ApiConsumes, ApiHeader, ApiOperation } from "@nestjs/swagger";
import { BillsService } from "./bills.service";
import { BillListQueryDto } from "./dto/bill-list-query.dto";
import { CreateChargeBillDto } from "./dto/create-charge-bill.dto";
import { CreateWaterBillDto } from "./dto/create-water-bill.dto";
import { AuthGuards } from "../../common/decorators/auth-guard.decorator";
import { CreateWaterBillDto, CreateWaterBillFromExcelDto } from "./dto/create-water-bill.dto";
// import { AuthGuards } from "../../common/decorators/auth-guard.decorator";
import { BusinessDec } from "../../common/decorators/business.decorator";
import { ParamDto } from "../../common/DTO/param.dto";
import { BusinessInterceptor } from "../../core/interceptors/business.interceptor";
import { Business } from "../businesses/entities/business.entity";
import { IFile } from "../utils/interfaces/IFile";
@Controller("bills")
@UseInterceptors(BusinessInterceptor)
@AuthGuards()
// @AuthGuards()
export class BillsController {
constructor(private readonly billsService: BillsService) {}
@@ -23,6 +25,19 @@ export class BillsController {
return this.billsService.createWaterBill(dto, business);
}
@ApiOperation({ summary: "Create water bill from excel file" })
@ApiConsumes("multipart/form-data")
@UseInterceptors(FileInterceptor("file"))
@ApiBody({ type: CreateWaterBillFromExcelDto })
@Post("water/excel")
createWaterBillByExcel(
@UploadedFile() file: IFile,
@Body() dto: CreateWaterBillFromExcelDto,
@BusinessDec() business: Business,
) {
return this.billsService.createWaterBillByExcel(file, dto, business);
}
@ApiOperation({ summary: "Create charge bill" })
@Post("charge")
createChargeBill(@Body() dto: CreateChargeBillDto, @BusinessDec() business: Business) {
@@ -31,6 +46,7 @@ export class BillsController {
@ApiOperation({ summary: "Get all bills with filters and pagination" })
@Get()
@ApiHeader({ name: "x-business-id" })
findAll(@Query() queryDto: BillListQueryDto, @BusinessDec("id") businessId: string) {
return this.billsService.findAll(queryDto, businessId);
}
+33 -1
View File
@@ -2,10 +2,13 @@ import { EntityManager } from "@mikro-orm/postgresql";
import { BadRequestException, Injectable } from "@nestjs/common";
import dayjs from "dayjs";
import Decimal from "decimal.js";
import { Workbook } from "exceljs";
import { IFile } from "../utils/interfaces/IFile";
import { BillListQueryDto } from "./dto/bill-list-query.dto";
import { CreateChargeBillDto } from "./dto/create-charge-bill.dto";
import { CreateWaterBillDto } from "./dto/create-water-bill.dto";
import { CreateWaterBillDto, CreateWaterBillFromExcelDto } from "./dto/create-water-bill.dto";
import { Bill } from "./entities/bill.entity";
import { BillType } from "./enums/bill-type.enum";
import { BillsRepository } from "./repositories/bill.repository";
@@ -81,6 +84,35 @@ export class BillsService {
}
}
async createWaterBillByExcel(file: IFile, dto: CreateWaterBillFromExcelDto, business: Business) {
const values = await this.parseWaterBillExcel(file.buffer);
if (values.length === 0) {
throw new BadRequestException("Excel file contains no valid data rows");
}
return this.createWaterBill({ ...dto, values }, business);
}
private async parseWaterBillExcel(buffer: Buffer): Promise<{ companyId: string; waterUsage: number }[]> {
const workbook = new Workbook();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
await workbook.xlsx.load(buffer as any);
const worksheet = workbook.worksheets[0];
if (!worksheet) {
return [];
}
const values: { companyId: string; waterUsage: number }[] = [];
worksheet.eachRow((row) => {
const companyIdRaw = row.getCell(1).value;
const waterUsageRaw = row.getCell(3).value;
const companyId = companyIdRaw != null ? String(companyIdRaw).trim() : "";
const waterUsage = typeof waterUsageRaw === "number" ? waterUsageRaw : Number(waterUsageRaw);
if (companyId && !Number.isNaN(waterUsage) && waterUsage >= 0) {
values.push({ companyId, waterUsage });
}
});
return values;
}
async createChargeBill(dto: CreateChargeBillDto, business: Business) {
const { chargeRate, dueDays } = dto;
const em = this.em.fork();
@@ -31,3 +31,15 @@ export class CreateWaterBillDto {
@ValidateNested({ each: true })
values: ValueDto[];
}
export class CreateWaterBillFromExcelDto {
@ApiProperty()
@Type(() => Number)
@IsInt()
waterRate: number;
@ApiProperty()
@Type(() => Number)
@IsInt()
dueDays: number;
}
+6 -1
View File
@@ -1,4 +1,4 @@
import { Cascade, Collection, Entity, EntityRepositoryType, Enum, ManyToOne, OneToMany } from "@mikro-orm/core";
import { Cascade, Collection, Entity, EntityRepositoryType, Enum, ManyToOne, OneToMany, Property } from "@mikro-orm/core";
import { BaseEntity } from "../../../common/entities/base.entity";
import { Business } from "../../businesses/entities/business.entity";
@@ -17,5 +17,10 @@ export class Bill extends BaseEntity {
@OneToMany(() => Invoice, (invoice) => invoice.bill, { cascade: [Cascade.PERSIST, Cascade.REMOVE], orphanRemoval: true })
invoices = new Collection<Invoice>(this);
/** Set by BillsRepository.getBillsList; not persisted. */
@Property({ persist: false })
invoiceCount?: number;
[EntityRepositoryType]?: BillsRepository;
}
@@ -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) {
query.andWhere('b.type', queryDto.type);
}
if (queryDto.since) {
query.andWhere('b.created_at', '>=', new Date(queryDto.since));
}
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) {
where.type = queryDto.type;
countQuery.andWhere('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) {
countQuery.andWhere('created_at', '>=', new Date(queryDto.since));
}
return this.findAndCount(where, {
populate: ["invoices"],
orderBy: { createdAt: "DESC" },
limit,
offset: skip,
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];
}
}