feat: link deposits to bill payment

This commit is contained in:
2026-07-14 16:38:38 +08:00
parent eac336a54a
commit 598b4e8acd
12 changed files with 272 additions and 218 deletions

View File

@@ -1,6 +1,6 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, In, DataSource } from 'typeorm';
import { Repository, In, DataSource, EntityManager } from 'typeorm';
import { Bill } from '../entities/bill.entity';
import { BillItem } from '../entities/bill-item.entity';
import { RoomExpense } from '../entities/room-expense.entity';
@@ -28,26 +28,15 @@ export class BillsService {
* 核心计费引擎:按"人天数"加权分摊
*/
async generateBills(dto: GenerateBillsDto) {
const { periodStart, periodEnd } = dto;
const { periodStart, periodEnd } = this.resolveBillingPeriod(dto.billingMonth);
const pStart = new Date(periodStart);
const pEnd = new Date(periodEnd);
// 删除该周期已有的草稿账单
const existingDrafts = await this.billRepo.find({
where: { periodStart, periodEnd, status: 'draft' },
const existingBills = await this.billRepo.find({
where: { periodStart, periodEnd },
});
if (existingDrafts.length > 0) {
const draftIds = existingDrafts.map((b) => b.id);
await this.itemRepo
.createQueryBuilder()
.delete()
.where('billId IN (:...ids)', { ids: draftIds })
.execute();
await this.billRepo
.createQueryBuilder()
.delete()
.where('id IN (:...ids)', { ids: draftIds })
.execute();
if (existingBills.length > 0) {
throw new BadRequestException(`${dto.billingMonth} 月账单已生成,不能重复生成`);
}
// 获取账单周期内所有有费用的宿舍
@@ -208,7 +197,41 @@ export class BillsService {
bills.push(savedBill);
}
return { message: `成功生成 ${bills.length} 条账单`, count: bills.length, bills };
return {
message: `成功生成 ${dto.billingMonth}${bills.length} 条账单`,
count: bills.length,
periodStart,
periodEnd,
bills,
};
}
private resolveBillingPeriod(billingMonth: string) {
const matched = /^(\d{4})-(\d{2})$/.exec(billingMonth || '');
if (!matched) {
throw new BadRequestException('账单月份格式错误,请使用 YYYY-MM');
}
const year = Number(matched[1]);
const month = Number(matched[2]);
if (month < 1 || month > 12) {
throw new BadRequestException('账单月份格式错误,请使用 YYYY-MM');
}
const targetMonthStart = new Date(year, month - 1, 1);
const currentMonthStart = new Date();
currentMonthStart.setDate(1);
currentMonthStart.setHours(0, 0, 0, 0);
if (targetMonthStart >= currentMonthStart) {
throw new BadRequestException('只能生成已结束月份的账单');
}
const targetMonthEnd = new Date(year, month, 0);
const pad = (value: number) => String(value).padStart(2, '0');
return {
periodStart: `${year}-${pad(month)}-01`,
periodEnd: `${year}-${pad(month)}-${pad(targetMonthEnd.getDate())}`,
};
}
async findAll(query?: {
@@ -242,9 +265,9 @@ export class BillsService {
/**
* 给账单挂上"押金联动"信息:
* - availableDeposit: 当前学生处于已缴未退状态(paid)的押金总额
* - depositApplied: 本张账单可从押金抵扣的金额min(押金, 应付总额)
* - amountAfterDeposit: 抵扣押金后学生需另外支付的金额
* - availableDeposit: 学生当前实时可用押金余额,生成账单时不会冻结
* - depositSufficient: 草稿账单是否已有足够余额可确认
* - depositDeductedAmount: 已确认账单实际扣除的押金金额
*/
private async attachDepositInfo(bills: Bill[]): Promise<any[]> {
if (!bills || bills.length === 0) return bills;
@@ -253,7 +276,6 @@ export class BillsService {
const deposits = await this.depositRepo
.createQueryBuilder('d')
.where('d.studentId IN (:...ids)', { ids: studentIds })
.andWhere('d.status = :status', { status: 'paid' })
.getMany();
const depMap = new Map<number, number>();
for (const d of deposits) {
@@ -262,42 +284,83 @@ export class BillsService {
return bills.map((b) => {
const total = Number(b.totalAmount || 0);
const available = Number((depMap.get(b.studentId) || 0).toFixed(2));
const applied = Number(Math.min(available, total).toFixed(2));
const afterDeposit = Number(Math.max(0, total - applied).toFixed(2));
return Object.assign({}, b, {
availableDeposit: available,
depositApplied: applied,
amountAfterDeposit: afterDeposit,
depositSufficient: available >= total,
depositDeductedAmount: Number(b.depositDeductedAmount || 0),
});
});
}
async updateStatus(id: number, dto: UpdateBillStatusDto) {
const bill = await this.billRepo.findOne({ where: { id } });
if (!bill) throw new NotFoundException('账单不存在');
bill.status = dto.status;
return this.billRepo.save(bill);
if (dto.status !== 'paid') {
throw new BadRequestException('账单只能通过确认支付完成扣款');
}
return this.dataSource.transaction((manager) => this.payBill(manager, id));
}
async batchUpdateStatus(ids: number[], status: string) {
await this.billRepo
.createQueryBuilder()
.update()
.set({ status })
.where('id IN (:...ids)', { ids })
.execute();
return { message: `成功更新 ${ids.length} 条账单状态` };
if (status !== 'paid') {
throw new BadRequestException('账单只能通过确认支付完成扣款');
}
const uniqueIds = Array.from(new Set(ids));
await this.dataSource.transaction(async (manager) => {
for (const id of uniqueIds) await this.payBill(manager, id);
});
return { message: `成功确认 ${uniqueIds.length} 条账单并扣除押金` };
}
private async payBill(manager: EntityManager, id: number) {
const billRepo = manager.getRepository(Bill);
const depositRepo = manager.getRepository(Deposit);
const lock = this.supportsPessimisticLocks()
? ({ mode: 'pessimistic_write' } as const)
: undefined;
const bill = await billRepo.findOne({ where: { id }, ...(lock ? { lock } : {}) });
if (!bill) throw new NotFoundException(`账单 ${id} 不存在`);
if (bill.status === 'paid') return bill;
if (bill.status !== 'draft') throw new BadRequestException(`账单 ${id} 当前状态无法确认支付`);
const deposit = await depositRepo.findOne({
where: { studentId: bill.studentId },
...(lock ? { lock } : {}),
});
const available = Number(deposit?.amount || 0);
const required = Number(bill.totalAmount || 0);
if (!deposit || available < required) {
throw new BadRequestException(
`账单 ${id} 押金不足:需 ¥${required.toFixed(2)},当前可用 ¥${available.toFixed(2)},请先到押金管理收取押金`,
);
}
deposit.amount = Number((available - required).toFixed(2));
deposit.status = deposit.amount > 0 ? 'paid' : 'depleted';
bill.depositDeductedAmount = required;
bill.status = 'paid';
await depositRepo.save(deposit);
return billRepo.save(bill);
}
private supportsPessimisticLocks() {
return ['mysql', 'mariadb', 'postgres', 'cockroachdb', 'mssql', 'oracle'].includes(
String(this.dataSource.options.type),
);
}
async remove(id: number) {
const exists = await this.billRepo.findOne({ where: { id } });
if (!exists) throw new NotFoundException('账单不存在');
if (exists.status === 'paid') throw new BadRequestException('已支付账单不能删除');
await this.itemRepo.delete({ billId: id });
await this.billRepo.delete(id);
return { message: '账单已删除' };
}
async batchRemove(ids: number[]) {
const bills = await this.billRepo.find({ where: { id: In(ids) } });
if (bills.some((bill) => bill.status === 'paid')) {
throw new BadRequestException('已支付账单不能删除');
}
await this.itemRepo
.createQueryBuilder()
.delete()