feat: restore credit limits and harden SMS sending

This commit is contained in:
hectorzhao
2026-07-14 18:46:35 +08:00
parent 3e3b7a9d1a
commit c1a17699db
23 changed files with 796 additions and 56 deletions
+8 -1
View File
@@ -1,4 +1,4 @@
import { Body, Controller, Get, Post } from '@nestjs/common';
import { Body, Controller, Get, Param, Post } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { TenantId } from '../common/tenant-id.decorator';
import { RequireRecentAuthentication } from '../auth/require-recent-authentication.decorator';
@@ -10,6 +10,7 @@ import {
CreateSmsBillingRecordDto,
CreateTenantAccountDto,
EstimateSmsCostDto,
UpdateCreditLimitDto,
} from './billing.service';
@ApiTags('billing')
@@ -27,6 +28,12 @@ export class BillingController {
return this.billing.createAccount(body);
}
@Post('accounts/:tenantId/credit-limit')
@RequireRecentAuthentication()
updateCreditLimit(@Param('tenantId') tenantId: string, @Body() body: UpdateCreditLimitDto) {
return this.billing.updateCreditLimit(tenantId, body);
}
@Get('recharges')
listRechargeOrders(@TenantId() tenantId?: string) {
return this.billing.listRechargeOrders(tenantId);
+20 -4
View File
@@ -1,7 +1,7 @@
import { BillingService } from './billing.service';
function createPrismaMock() {
const accountState = { tenantId: 'tenant-1', balanceCents: 1000 };
const accountState = { id: 'account-1', tenantId: 'tenant-1', balanceCents: 1000, creditCents: 0 };
return {
accountState,
tenantAccount: {
@@ -9,7 +9,8 @@ function createPrismaMock() {
create: jest.fn(),
upsert: jest.fn().mockImplementation(() => Promise.resolve({ ...accountState })),
update: jest.fn().mockImplementation(({ data }) => {
accountState.balanceCents = data.balanceCents;
if (data.balanceCents !== undefined) accountState.balanceCents = data.balanceCents;
if (data.creditCents !== undefined) accountState.creditCents = data.creditCents;
return Promise.resolve({ ...accountState });
}),
},
@@ -62,7 +63,7 @@ describe('BillingService', () => {
);
});
it('checks only the cash balance before sending', async () => {
it('allows sending only when cash balance plus credit is greater than zero', async () => {
const prisma = createPrismaMock();
const service = new BillingService(prisma as never);
@@ -70,8 +71,23 @@ describe('BillingService', () => {
expect.objectContaining({ availableAmount: 1000, canSend: true }),
);
await expect(service.checkAccount({ tenantId: 'tenant-1', amountCents: 1001 })).resolves.toEqual(
expect.objectContaining({ canSend: false }),
expect.objectContaining({ availableAmount: 1000, canSend: true }),
);
await service.updateCreditLimit('tenant-1', { creditCents: -1000, operatorId: 'admin-1' });
await expect(service.checkAccount({ tenantId: 'tenant-1', amountCents: 1 })).resolves.toEqual(
expect.objectContaining({ availableAmount: 0, balanceCents: 1000, creditCents: -1000, canSend: false }),
);
await service.updateCreditLimit('tenant-1', { creditCents: 500, operatorId: 'admin-1' });
await expect(service.checkAccount({ tenantId: 'tenant-1', amountCents: 999999 })).resolves.toEqual(
expect.objectContaining({ availableAmount: 1500, creditCents: 500, canSend: true }),
);
await expect(service.updateCreditLimit('tenant-1', { creditCents: 1.5 })).rejects.toThrow('授信额度必须为整数金额');
expect(prisma.operationLog.create).toHaveBeenCalledWith({
data: expect.objectContaining({
action: 'billing.credit_limit_updated',
detail: expect.objectContaining({ previousCreditCents: 0, creditCents: -1000 }),
}),
});
});
it('creates cash recharge orders and account transactions without plans', async () => {
+45 -4
View File
@@ -1,13 +1,20 @@
import { Injectable } from '@nestjs/common';
import { BadRequestException, Injectable } from '@nestjs/common';
import { Prisma } from '@prisma/client';
import { PrismaService } from '../prisma/prisma.service';
export interface CreateTenantAccountDto {
tenantId: string;
balanceCents?: number;
creditCents?: number;
status?: string;
}
export interface UpdateCreditLimitDto {
creditCents: number;
operatorId?: string;
remark?: string;
}
export interface CreateAccountTransactionDto {
tenantId: string;
transactionType: string;
@@ -80,14 +87,40 @@ export class BillingService {
}
createAccount(data: CreateTenantAccountDto) {
assertCreditAmount(data.creditCents ?? 0);
const createData: Prisma.TenantAccountUncheckedCreateInput = {
tenantId: data.tenantId,
balanceCents: data.balanceCents ?? 0,
creditCents: data.creditCents ?? 0,
status: data.status ?? 'active',
};
return this.prisma.tenantAccount.create({ data: createData });
}
async updateCreditLimit(tenantId: string, data: UpdateCreditLimitDto) {
assertCreditAmount(data.creditCents);
const account = await this.getAccountOrCreate(tenantId);
const updated = await this.prisma.tenantAccount.update({
where: { tenantId },
data: { creditCents: data.creditCents },
});
await this.prisma.operationLog.create({
data: {
tenantId,
userId: data.operatorId,
action: 'billing.credit_limit_updated',
resource: 'tenant_account',
resourceId: account.id,
detail: {
previousCreditCents: account.creditCents,
creditCents: data.creditCents,
remark: data.remark,
} as Prisma.InputJsonValue,
},
});
return updated;
}
listRechargeOrders(tenantId?: string) {
return this.prisma.rechargeOrder.findMany({
where: tenantId ? { tenantId } : undefined,
@@ -195,12 +228,14 @@ export class BillingService {
async checkAccount(data: BillingActionDto) {
const account = await this.getAccountOrCreate(data.tenantId);
const requiredAmount = data.amountCents ?? 0;
const availableAmount = account.balanceCents;
const availableAmount = account.balanceCents + account.creditCents;
return {
tenantId: data.tenantId,
requiredAmount,
availableAmount,
canSend: availableAmount >= requiredAmount,
balanceCents: account.balanceCents,
creditCents: account.creditCents,
canSend: availableAmount > 0,
};
}
@@ -296,7 +331,7 @@ export class BillingService {
return this.prisma.tenantAccount.upsert({
where: { tenantId },
update: {},
create: { tenantId, balanceCents: 0, status: 'active' },
create: { tenantId, balanceCents: 0, creditCents: 0, status: 'active' },
});
}
@@ -324,6 +359,12 @@ export class BillingService {
}
}
function assertCreditAmount(creditCents: number) {
if (!Number.isInteger(creditCents)) {
throw new BadRequestException('授信额度必须为整数金额(分)');
}
}
function estimateBillingUnits(content: string) {
const length = [...content].length;
if (length <= 70) {