feat: 充值订单审计与重新申请,优化赛事展示和余额刷新

- 新增 deposit_order_audit_logs 表,记录提交/审批/拒绝/撤销/重提全链路
- 管理端充值单页增加审计历史;玩家端充值历史支持时间线与重新申请
- 已拒绝订单可原单号重提;撤销入账使用 PLAYER_DEPOSIT_REVERSAL 并加强幂等
- 结算后清除热门标记,允许归档已结算赛事,完善今日赛事时区窗口
- 足球页今日/早盘独立折叠;资料与余额在进入钱包/个人页及下注后自动刷新
- 补充投注玩法、结算返水规则文档;新增 smoke/settlement CLI 脚本

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-06-15 14:52:05 +08:00
parent 73a94e6be3
commit afb5c5437e
55 changed files with 3050 additions and 160 deletions

View File

@@ -7,9 +7,13 @@ describe('DepositService', () => {
$queryRaw: jest.fn(),
depositOrder: {
findUnique: jest.fn(),
findFirst: jest.fn(),
update: jest.fn(),
delete: jest.fn(),
},
paymentMethod: {
findUnique: jest.fn(),
},
bet: {
findMany: jest.fn(),
},
@@ -19,6 +23,9 @@ describe('DepositService', () => {
agentProfile: {
findUnique: jest.fn(),
},
depositOrderAuditLog: {
create: jest.fn(),
},
};
const prisma = {
...tx,
@@ -65,6 +72,7 @@ describe('DepositService', () => {
reviewedAt: null,
screenshotUrl: '/uploads/a.png',
});
tx.depositOrderAuditLog.create.mockResolvedValue({ id: 501n });
tx.user.findFirst.mockResolvedValue({ parentId: 3n });
tx.agentProfile.findUnique.mockResolvedValue({
creditLimit: new Decimal(1000),
@@ -89,7 +97,7 @@ describe('DepositService', () => {
remark: 'Bank receipt checked',
referenceId: 'DEP-1',
transactionType: 'PLAYER_DEPOSIT',
businessKey: 'deposit:DEP-1:approve',
businessKey: 'deposit:DEP-1:approve:501',
tx,
}),
);
@@ -98,6 +106,54 @@ describe('DepositService', () => {
expect(credit.recalculateUsedCredit).toHaveBeenNthCalledWith(2, 3n, tx);
});
it('uses a fresh business key when re-approving after revoke', async () => {
const reviewedAt = new Date('2026-06-15T14:08:48.000Z');
tx.depositOrder.findUnique.mockResolvedValue({
id: 1n,
orderNo: 'DEP-1',
playerId: 7n,
amount: new Decimal(2),
approvedAmount: null,
status: 'PENDING',
reviewedAt: null,
screenshotUrl: '/uploads/a.png',
});
tx.depositOrderAuditLog.create.mockResolvedValueOnce({ id: 601n });
await service.approveDepositOrder(1n, 2n, 2, 'Second approval');
expect(funds.deposit).toHaveBeenCalledWith(
expect.objectContaining({
amount: new Decimal(2),
businessKey: 'deposit:DEP-1:approve:601',
}),
);
});
it('uses approval cycle key when revoking a funded deposit for re-review', async () => {
const reviewedAt = new Date('2026-06-15T14:08:48.000Z');
tx.depositOrder.findUnique.mockResolvedValue({
id: 1n,
orderNo: 'DEP-1',
playerId: 7n,
amount: new Decimal(21),
approvedAmount: new Decimal(21),
status: 'APPROVED',
reviewedAt,
screenshotUrl: '/uploads/a.png',
});
tx.depositOrderAuditLog.create.mockResolvedValue({ id: 701n });
await service.reopenDepositOrderForReview(1n, 2n);
expect(funds.withdraw).toHaveBeenCalledWith(
expect.objectContaining({
amount: new Decimal(21),
businessKey: `deposit:DEP-1:reopen-reverse:${reviewedAt.getTime()}`,
}),
);
});
it('blocks approved deposit revoke when bets exist after approval', async () => {
tx.bet.findMany.mockResolvedValue([{ id: 99n }]);
@@ -116,4 +172,106 @@ describe('DepositService', () => {
expect(tx.depositOrder.delete).not.toHaveBeenCalled();
});
it('reapplies a rejected deposit on the same order for the player', async () => {
tx.depositOrder.findUnique
.mockResolvedValueOnce({
id: 1n,
orderNo: 'DEP-1',
playerId: 7n,
paymentMethodId: 5n,
methodType: 'BANK',
amount: new Decimal(11),
approvedAmount: null,
status: 'REJECTED',
reviewedAt: new Date(),
rejectReason: 'Screenshot unclear',
remark: 'Screenshot unclear',
screenshotUrl: '/uploads/deposits/old.png',
})
.mockResolvedValueOnce({
id: 1n,
orderNo: 'DEP-1',
playerId: 7n,
amount: new Decimal(11),
status: 'PENDING',
createdAt: new Date(),
});
tx.depositOrder.findFirst.mockResolvedValue(null);
tx.paymentMethod.findUnique.mockResolvedValue({
id: 5n,
methodType: 'BANK',
isActive: true,
});
const result = await service.reapplyDepositOrder(
7n,
1n,
'/uploads/deposits/new.png',
11,
);
expect(tx.depositOrder.update).toHaveBeenCalledWith(
expect.objectContaining({
where: { id: 1n },
data: expect.objectContaining({
status: 'PENDING',
screenshotUrl: '/uploads/deposits/new.png',
rejectReason: null,
remark: null,
reviewerId: null,
reviewedAt: null,
}),
}),
);
expect(tx.depositOrderAuditLog.create).toHaveBeenCalledWith(
expect.objectContaining({
data: expect.objectContaining({
action: 'REOPENED',
actorId: 7n,
actorType: 'PLAYER',
statusBefore: 'REJECTED',
statusAfter: 'PENDING',
}),
}),
);
expect(result?.orderNo).toBe('DEP-1');
});
it('blocks reapply when player already has another pending deposit', async () => {
tx.depositOrder.findUnique.mockResolvedValue({
id: 1n,
orderNo: 'DEP-1',
playerId: 7n,
paymentMethodId: 5n,
methodType: 'BANK',
amount: new Decimal(11),
status: 'REJECTED',
screenshotUrl: '/uploads/deposits/old.png',
});
tx.depositOrder.findFirst.mockResolvedValue({ id: 99n });
await expect(
service.reapplyDepositOrder(7n, 1n, '/uploads/deposits/new.png'),
).rejects.toMatchObject(expectAppError('DEPOSIT_PENDING_ORDER_EXISTS'));
expect(tx.depositOrder.update).not.toHaveBeenCalled();
});
it('blocks reapply for non-rejected deposit orders', async () => {
tx.depositOrder.findUnique.mockResolvedValue({
id: 1n,
orderNo: 'DEP-1',
playerId: 7n,
paymentMethodId: 5n,
methodType: 'BANK',
amount: new Decimal(11),
status: 'PENDING',
screenshotUrl: '/uploads/deposits/old.png',
});
await expect(
service.reapplyDepositOrder(7n, 1n, '/uploads/deposits/new.png'),
).rejects.toMatchObject(expectAppError('ORDER_NOT_REJECTED'));
});
});

View File

@@ -17,6 +17,32 @@ function generateOrderNo(): string {
/** 已通过充值订单允许撤回的时间窗口 */
const DEPOSIT_REVOKE_WINDOW_MS = 5 * 60 * 1000;
export type DepositOrderAuditAction =
| 'SUBMITTED'
| 'APPROVED'
| 'REJECTED'
| 'REVOKED'
| 'REOPENED'
| 'DELETED';
type AuditLogWriter = {
depositOrderAuditLog: {
create: (args: {
data: {
depositOrderId: bigint;
action: DepositOrderAuditAction;
actorId?: bigint | null;
actorType: string;
statusBefore?: string | null;
statusAfter: string;
amount?: Decimal | null;
approvedAmount?: Decimal | null;
remark?: string | null;
};
}) => Promise<{ id: bigint }>;
};
};
@Injectable()
export class DepositService {
constructor(
@@ -228,6 +254,156 @@ export class DepositService {
// ============ Deposit Orders ============
private async recordDepositAudit(
client: AuditLogWriter,
data: {
depositOrderId: bigint;
action: DepositOrderAuditAction;
actorId?: bigint | null;
actorType: 'PLAYER' | 'ADMIN';
statusBefore?: string | null;
statusAfter: string;
amount?: Decimal | null;
approvedAmount?: Decimal | null;
remark?: string | null;
},
) {
return client.depositOrderAuditLog.create({
data: {
depositOrderId: data.depositOrderId,
action: data.action,
actorId: data.actorId ?? null,
actorType: data.actorType,
statusBefore: data.statusBefore ?? null,
statusAfter: data.statusAfter,
amount: data.amount ?? null,
approvedAmount: data.approvedAmount ?? null,
remark: data.remark ?? null,
},
});
}
private mapAuditLogRow(
row: {
id: bigint;
action: string;
actorId: bigint | null;
actorType: string;
statusBefore: string | null;
statusAfter: string;
amount: Decimal | null;
approvedAmount: Decimal | null;
remark: string | null;
createdAt: Date;
},
actorUsername?: string | null,
) {
return {
id: row.id.toString(),
action: row.action,
actorId: row.actorId?.toString() ?? null,
actorType: row.actorType,
actorUsername: actorUsername ?? null,
statusBefore: row.statusBefore,
statusAfter: row.statusAfter,
amount: row.amount?.toString() ?? null,
approvedAmount: row.approvedAmount?.toString() ?? null,
remark: row.remark,
createdAt: row.createdAt.toISOString(),
};
}
async getDepositOrderAuditLogs(orderId: bigint) {
const order = await this.prisma.depositOrder.findUnique({
where: { id: orderId },
select: { id: true },
});
if (!order) throw appBadRequest('ORDER_NOT_FOUND');
const rows = await this.prisma.depositOrderAuditLog.findMany({
where: { depositOrderId: orderId },
orderBy: { createdAt: 'asc' },
});
const actorIds = [...new Set(rows.map((r) => r.actorId).filter((id): id is bigint => id != null))];
const actors =
actorIds.length > 0
? await this.prisma.user.findMany({
where: { id: { in: actorIds } },
select: { id: true, username: true },
})
: [];
const actorMap = new Map(actors.map((a) => [a.id.toString(), a.username]));
return rows.map((row) =>
this.mapAuditLogRow(
row,
row.actorId ? actorMap.get(row.actorId.toString()) ?? null : null,
),
);
}
async getPlayerDepositOrderAuditLogs(orderId: bigint, playerId: bigint) {
const order = await this.prisma.depositOrder.findFirst({
where: { id: orderId, playerId },
select: { id: true },
});
if (!order) throw appBadRequest('ORDER_NOT_FOUND');
const rows = await this.prisma.depositOrderAuditLog.findMany({
where: { depositOrderId: orderId },
orderBy: { createdAt: 'asc' },
});
return rows.map((row) => {
const mapped = this.mapAuditLogRow(row);
return {
id: mapped.id,
action: mapped.action,
actorType: mapped.actorType,
statusBefore: mapped.statusBefore,
statusAfter: mapped.statusAfter,
amount: mapped.amount,
approvedAmount: mapped.approvedAmount,
remark: mapped.remark,
createdAt: mapped.createdAt,
};
});
}
private async attachPlayerAuditLogs(
orders: Array<{ id: bigint }>,
) {
if (!orders.length) return new Map<string, ReturnType<typeof this.mapAuditLogRow>[]>();
const orderIds = orders.map((o) => o.id);
const rows = await this.prisma.depositOrderAuditLog.findMany({
where: { depositOrderId: { in: orderIds } },
orderBy: { createdAt: 'asc' },
});
const map = new Map<string, ReturnType<typeof this.mapAuditLogRow>[]>();
for (const row of rows) {
const key = row.depositOrderId.toString();
if (!map.has(key)) map.set(key, []);
const mapped = this.mapAuditLogRow(row);
map.get(key)!.push({
id: mapped.id,
action: mapped.action,
actorId: null,
actorType: mapped.actorType,
actorUsername: null,
statusBefore: mapped.statusBefore,
statusAfter: mapped.statusAfter,
amount: mapped.amount,
approvedAmount: mapped.approvedAmount,
remark: mapped.remark,
createdAt: mapped.createdAt,
});
}
return map;
}
async createDepositOrder(
playerId: bigint,
paymentMethodId: bigint,
@@ -253,9 +429,87 @@ export class DepositService {
},
});
await this.recordDepositAudit(this.prisma, {
depositOrderId: order.id,
action: 'SUBMITTED',
actorId: playerId,
actorType: 'PLAYER',
statusBefore: null,
statusAfter: 'PENDING',
amount: order.amount,
remark: null,
});
return order;
}
/** 玩家对已拒绝订单重新提交:原订单号不变,状态恢复待审核,需新转账截图。 */
async reapplyDepositOrder(
playerId: bigint,
orderId: bigint,
screenshotUrl: string,
amount?: number,
paymentMethodId?: bigint,
) {
return this.prisma.$transaction(async (tx) => {
const order = await this.lockDepositOrder(tx, orderId);
if (order.playerId !== playerId) throw appBadRequest('ORDER_NOT_FOUND');
if (order.status !== 'REJECTED') throw appBadRequest('ORDER_NOT_REJECTED');
const otherPending = await tx.depositOrder.findFirst({
where: {
playerId,
status: 'PENDING',
id: { not: orderId },
},
select: { id: true },
});
if (otherPending) throw appBadRequest('DEPOSIT_PENDING_ORDER_EXISTS');
const targetMethodId = paymentMethodId ?? order.paymentMethodId;
const method = await tx.paymentMethod.findUnique({ where: { id: targetMethodId } });
if (!method || !method.isActive) {
throw appBadRequest('PAYMENT_METHOD_NOT_FOUND');
}
const creditAmount = amount != null ? new Decimal(amount) : order.amount;
if (creditAmount.lte(0)) throw appBadRequest('INVALID_AMOUNT');
const oldScreenshotUrl = order.screenshotUrl;
await tx.depositOrder.update({
where: { id: orderId },
data: {
status: 'PENDING',
screenshotUrl,
amount: creditAmount,
paymentMethodId: targetMethodId,
methodType: method.methodType,
approvedAmount: null,
reviewerId: null,
reviewedAt: null,
rejectReason: null,
remark: null,
},
});
await this.recordDepositAudit(tx, {
depositOrderId: orderId,
action: 'REOPENED',
actorId: playerId,
actorType: 'PLAYER',
statusBefore: order.status,
statusAfter: 'PENDING',
amount: creditAmount,
remark: null,
});
await deleteUploadFileByUrl(oldScreenshotUrl);
return tx.depositOrder.findUnique({ where: { id: orderId } });
});
}
async getPlayerDepositOrders(playerId: bigint, page = 1, pageSize = 20) {
const skip = (page - 1) * pageSize;
const where = { playerId };
@@ -274,11 +528,13 @@ export class DepositService {
}),
this.prisma.depositOrder.count({ where }),
]);
const auditMap = await this.attachPlayerAuditLogs(items);
return {
items: items.map((o) => ({
id: o.id.toString(),
orderNo: o.orderNo,
paymentMethodId: o.paymentMethodId.toString(),
methodType: o.methodType,
amount: o.amount.toString(),
screenshotUrl: o.screenshotUrl,
@@ -289,6 +545,17 @@ export class DepositService {
createdAt: o.createdAt,
reviewedAt: o.reviewedAt,
paymentMethodName: o.paymentMethod?.displayName ?? o.paymentMethod?.bankName ?? o.paymentMethod?.usdtAddress ?? null,
auditLogs: (auditMap.get(o.id.toString()) ?? []).map((log) => ({
id: log.id,
action: log.action,
actorType: log.actorType,
statusBefore: log.statusBefore,
statusAfter: log.statusAfter,
amount: log.amount,
approvedAmount: log.approvedAmount,
remark: log.remark,
createdAt: log.createdAt,
})),
})),
total,
page,
@@ -428,6 +695,18 @@ export class DepositService {
},
});
const auditLog = await this.recordDepositAudit(tx, {
depositOrderId: orderId,
action: 'APPROVED',
actorId: operatorId,
actorType: 'ADMIN',
statusBefore: order.status,
statusAfter: 'APPROVED',
amount: order.amount,
approvedAmount: creditAmount,
remark: remark ?? null,
});
// Credit player wallet
await this.funds.deposit({
userId: order.playerId,
@@ -437,7 +716,7 @@ export class DepositService {
referenceId: order.orderNo,
transactionType: 'PLAYER_DEPOSIT',
tx,
businessKey: `deposit:${order.orderNo}:approve`,
businessKey: `deposit:${order.orderNo}:approve:${auditLog.id}`,
});
if (parentAgentId) {
await this.credit.recalculateUsedCredit(parentAgentId, tx);
@@ -463,6 +742,17 @@ export class DepositService {
},
});
await this.recordDepositAudit(this.prisma, {
depositOrderId: orderId,
action: 'REJECTED',
actorId: operatorId,
actorType: 'ADMIN',
statusBefore: order.status,
statusAfter: 'REJECTED',
amount: order.amount,
remark: reason,
});
return { success: true };
}
@@ -506,6 +796,16 @@ export class DepositService {
remark: null,
},
});
await this.recordDepositAudit(tx, {
depositOrderId: orderId,
action: 'REOPENED',
actorId: operatorId,
actorType: 'ADMIN',
statusBefore: order.status,
statusAfter: 'PENDING',
amount: order.amount,
remark: null,
});
return { success: true };
}
@@ -534,6 +834,7 @@ export class DepositService {
const credit = order.approvedAmount ?? order.amount;
const parentAgentId = await this.findPlayerParentAgentId(tx, order.playerId);
const approvalCycleKey = order.reviewedAt?.getTime();
await this.funds.withdraw({
userId: order.playerId,
amount: credit,
@@ -541,8 +842,9 @@ export class DepositService {
remark: `Revoke approved deposit ${order.orderNo}`,
referenceId: order.orderNo,
transactionType: 'PLAYER_DEPOSIT_REVERSAL',
referenceType: 'DEPOSIT',
tx,
businessKey: `deposit:${order.orderNo}:reopen-reverse`,
businessKey: `deposit:${order.orderNo}:reopen-reverse:${approvalCycleKey}`,
});
if (parentAgentId) {
await this.credit.recalculateUsedCredit(parentAgentId, tx);
@@ -560,6 +862,18 @@ export class DepositService {
},
});
await this.recordDepositAudit(tx, {
depositOrderId: orderId,
action: 'REVOKED',
actorId: operatorId,
actorType: 'ADMIN',
statusBefore: order.status,
statusAfter: 'PENDING',
amount: order.amount,
approvedAmount: credit,
remark: `Revoke approved deposit ${order.orderNo}`,
});
return { success: true, voidedBets: 0 };
});
}