feat: 充值订单审计与重新申请,优化赛事展示和余额刷新
- 新增 deposit_order_audit_logs 表,记录提交/审批/拒绝/撤销/重提全链路 - 管理端充值单页增加审计历史;玩家端充值历史支持时间线与重新申请 - 已拒绝订单可原单号重提;撤销入账使用 PLAYER_DEPOSIT_REVERSAL 并加强幂等 - 结算后清除热门标记,允许归档已结算赛事,完善今日赛事时区窗口 - 足球页今日/早盘独立折叠;资料与余额在进入钱包/个人页及下注后自动刷新 - 补充投注玩法、结算返水规则文档;新增 smoke/settlement CLI 脚本 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -13,6 +13,8 @@
|
||||
"db:migrate": "prisma migrate dev",
|
||||
"db:migrate:deploy": "prisma migrate deploy && prisma generate",
|
||||
"db:seed": "ts-node prisma/seed.ts",
|
||||
"db:smoke": "ts-node src/infrastructure/database/run-smoke-cli.ts",
|
||||
"audit:settlement": "ts-node src/infrastructure/database/run-settlement-audit.ts",
|
||||
"db:reset": "ts-node src/infrastructure/database/reset-and-seed-cli.ts --yes --production",
|
||||
"db:reset:dev": "ts-node src/infrastructure/database/reset-and-seed-cli.ts --yes --dev",
|
||||
"db:studio": "prisma studio"
|
||||
|
||||
8
apps/api/prisma/migrations/20260615040059/migration.sql
Normal file
8
apps/api/prisma/migrations/20260615040059/migration.sql
Normal file
@@ -0,0 +1,8 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "market_template_items" ALTER COLUMN "updated_at" DROP DEFAULT;
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "market_template_selections" ALTER COLUMN "updated_at" DROP DEFAULT;
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "market_templates" ALTER COLUMN "updated_at" DROP DEFAULT;
|
||||
@@ -0,0 +1,25 @@
|
||||
-- CreateTable
|
||||
CREATE TABLE "deposit_order_audit_logs" (
|
||||
"id" BIGSERIAL NOT NULL,
|
||||
"deposit_order_id" BIGINT NOT NULL,
|
||||
"action" VARCHAR(32) NOT NULL,
|
||||
"actor_id" BIGINT,
|
||||
"actor_type" VARCHAR(20) NOT NULL,
|
||||
"status_before" VARCHAR(20),
|
||||
"status_after" VARCHAR(20) NOT NULL,
|
||||
"amount" DECIMAL(18,4),
|
||||
"approved_amount" DECIMAL(18,4),
|
||||
"remark" VARCHAR(500),
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "deposit_order_audit_logs_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "deposit_order_audit_logs_deposit_order_id_idx" ON "deposit_order_audit_logs"("deposit_order_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "deposit_order_audit_logs_created_at_idx" ON "deposit_order_audit_logs"("created_at");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "deposit_order_audit_logs" ADD CONSTRAINT "deposit_order_audit_logs_deposit_order_id_fkey" FOREIGN KEY ("deposit_order_id") REFERENCES "deposit_orders"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
@@ -785,6 +785,7 @@ model DepositOrder {
|
||||
|
||||
player User @relation("PlayerDepositOrders", fields: [playerId], references: [id])
|
||||
paymentMethod PaymentMethod @relation(fields: [paymentMethodId], references: [id])
|
||||
auditLogs DepositOrderAuditLog[]
|
||||
|
||||
@@index([playerId])
|
||||
@@index([status])
|
||||
@@ -792,6 +793,26 @@ model DepositOrder {
|
||||
@@map("deposit_orders")
|
||||
}
|
||||
|
||||
model DepositOrderAuditLog {
|
||||
id BigInt @id @default(autoincrement())
|
||||
depositOrderId BigInt @map("deposit_order_id")
|
||||
action String @db.VarChar(32)
|
||||
actorId BigInt? @map("actor_id")
|
||||
actorType String @map("actor_type") @db.VarChar(20)
|
||||
statusBefore String? @map("status_before") @db.VarChar(20)
|
||||
statusAfter String @map("status_after") @db.VarChar(20)
|
||||
amount Decimal? @db.Decimal(18, 4)
|
||||
approvedAmount Decimal? @map("approved_amount") @db.Decimal(18, 4)
|
||||
remark String? @db.VarChar(500)
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
|
||||
depositOrder DepositOrder @relation(fields: [depositOrderId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([depositOrderId])
|
||||
@@index([createdAt])
|
||||
@@map("deposit_order_audit_logs")
|
||||
}
|
||||
|
||||
// ============ System Config & Audit ============
|
||||
|
||||
model SystemConfig {
|
||||
|
||||
@@ -2913,6 +2913,13 @@ export class AdminController {
|
||||
return jsonResponse(result);
|
||||
}
|
||||
|
||||
@Get('deposit-orders/:id/audit-logs')
|
||||
@RequirePermissions(P.depositReview)
|
||||
async depositOrderAuditLogs(@Param('id') id: string) {
|
||||
const items = await this.depositService.getDepositOrderAuditLogs(BigInt(id));
|
||||
return jsonResponse({ items });
|
||||
}
|
||||
|
||||
@Post('deposit-orders/:id/approve')
|
||||
@RequirePermissions(P.depositReview)
|
||||
async approveDepositOrder(
|
||||
|
||||
@@ -182,7 +182,9 @@ export class PlayerController {
|
||||
]);
|
||||
const timeZone = safeTimeZone(headerTimeZone);
|
||||
const now = new Date();
|
||||
const hotMatches = (allMatches as Array<{ isHot?: boolean }>).filter((m) => m.isHot);
|
||||
const hotMatches = (allMatches as Array<{ isHot?: boolean; status?: string }>).filter(
|
||||
(m) => m.isHot && m.status !== 'SETTLED',
|
||||
);
|
||||
const todayMatches = (allMatches as Array<{ startTime: string }>).filter((m) => {
|
||||
const kickoff = new Date(m.startTime);
|
||||
return !Number.isNaN(kickoff.getTime()) && isInLocalTodayMatchWindow(kickoff, now, timeZone);
|
||||
@@ -399,4 +401,52 @@ export class PlayerController {
|
||||
);
|
||||
return jsonResponse(result);
|
||||
}
|
||||
|
||||
@Get('deposit-orders/:id/audit-logs')
|
||||
async myDepositOrderAuditLogs(
|
||||
@CurrentUser('id') userId: bigint,
|
||||
@Param('id') id: string,
|
||||
) {
|
||||
const items = await this.deposit.getPlayerDepositOrderAuditLogs(BigInt(id), userId);
|
||||
return jsonResponse({ items });
|
||||
}
|
||||
|
||||
@Post('deposit-orders/:id/reapply')
|
||||
@UseInterceptors(FileInterceptor('screenshot', { limits: { fileSize: 5 * 1024 * 1024 } }))
|
||||
async reapplyDepositOrder(
|
||||
@CurrentUser('id') userId: bigint,
|
||||
@Param('id') id: string,
|
||||
@UploadedFile() file: { originalname: string; mimetype: string; buffer: Buffer; size: number } | undefined,
|
||||
@Body() body: { paymentMethodId?: string; amount?: string },
|
||||
) {
|
||||
if (!file) throw appBadRequest('SCREENSHOT_REQUIRED');
|
||||
if (!file.mimetype.startsWith('image/')) throw appBadRequest('FILE_MUST_BE_IMAGE');
|
||||
|
||||
const amount = body.amount != null && body.amount !== '' ? parseFloat(body.amount) : undefined;
|
||||
if (amount != null && (!amount || amount <= 0)) throw appBadRequest('INVALID_AMOUNT');
|
||||
|
||||
const ext = extname(file.originalname || '.jpg').toLowerCase() || '.jpg';
|
||||
const filename = `${Date.now()}-${randomUUID().slice(0, 8)}${ext}`;
|
||||
const root = getUploadRoot();
|
||||
const targetDir = join(root, 'deposits');
|
||||
await mkdir(targetDir, { recursive: true });
|
||||
await writeFile(join(targetDir, filename), file.buffer);
|
||||
const screenshotUrl = `/uploads/deposits/${filename}`;
|
||||
|
||||
const order = await this.deposit.reapplyDepositOrder(
|
||||
userId,
|
||||
BigInt(id),
|
||||
screenshotUrl,
|
||||
amount,
|
||||
body.paymentMethodId ? BigInt(body.paymentMethodId) : undefined,
|
||||
);
|
||||
|
||||
return jsonResponse({
|
||||
id: order!.id.toString(),
|
||||
orderNo: order!.orderNo,
|
||||
amount: order!.amount.toString(),
|
||||
status: order!.status,
|
||||
createdAt: order!.createdAt,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ describe('CatalogArchiveService', () => {
|
||||
match: { findFirst: jest.Mock; update: jest.Mock; findMany: jest.Mock; updateMany: jest.Mock };
|
||||
league: { findFirst: jest.Mock; update: jest.Mock };
|
||||
bet: { findMany: jest.Mock };
|
||||
settlementBatch: { findFirst: jest.Mock; findMany: jest.Mock };
|
||||
settlementBatch: { findFirst: jest.Mock; findMany: jest.Mock; deleteMany: jest.Mock };
|
||||
market: { updateMany: jest.Mock };
|
||||
marketSelection: { updateMany: jest.Mock };
|
||||
entityTranslation: { findFirst: jest.Mock };
|
||||
@@ -28,7 +28,11 @@ describe('CatalogArchiveService', () => {
|
||||
},
|
||||
league: { findFirst: jest.fn(), update: jest.fn() },
|
||||
bet: { findMany: jest.fn().mockResolvedValue([]) },
|
||||
settlementBatch: { findFirst: jest.fn().mockResolvedValue(null), findMany: jest.fn().mockResolvedValue([]) },
|
||||
settlementBatch: {
|
||||
findFirst: jest.fn().mockResolvedValue(null),
|
||||
findMany: jest.fn().mockResolvedValue([]),
|
||||
deleteMany: jest.fn().mockResolvedValue({ count: 0 }),
|
||||
},
|
||||
market: { updateMany: jest.fn() },
|
||||
marketSelection: { updateMany: jest.fn() },
|
||||
entityTranslation: { findFirst: jest.fn().mockResolvedValue(null) },
|
||||
@@ -71,6 +75,40 @@ describe('CatalogArchiveService', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('archives settled match with stale preview batch when force is true', async () => {
|
||||
prisma.match.findFirst.mockResolvedValue({ ...baseMatch, status: 'SETTLED' });
|
||||
prisma.bet.findMany.mockResolvedValue([]);
|
||||
prisma.settlementBatch.findFirst.mockResolvedValue({ id: BigInt(99) });
|
||||
|
||||
const result = await service.archiveMatch(matchId, { force: true });
|
||||
|
||||
expect(result.matchId).toBe(matchId.toString());
|
||||
expect(prisma.settlementBatch.deleteMany).toHaveBeenCalledWith({
|
||||
where: { matchId, status: 'PREVIEW' },
|
||||
});
|
||||
expect(prisma.match.update).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
data: expect.objectContaining({
|
||||
deletedAt: expect.any(Date),
|
||||
status: 'SETTLED',
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('archives settled match without force when no warnings', async () => {
|
||||
prisma.match.findFirst.mockResolvedValue({ ...baseMatch, status: 'SETTLED' });
|
||||
prisma.bet.findMany.mockResolvedValue([]);
|
||||
|
||||
await service.archiveMatch(matchId, { force: false });
|
||||
|
||||
expect(prisma.match.update).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
data: expect.objectContaining({ status: 'SETTLED' }),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('archive with force rejects draft matches', async () => {
|
||||
prisma.match.findFirst.mockResolvedValue({ ...baseMatch, status: 'DRAFT' });
|
||||
|
||||
|
||||
@@ -70,9 +70,6 @@ export class CatalogArchiveService {
|
||||
if (match.status === 'DRAFT') {
|
||||
throw appBadRequest('MATCH_DELETE_DRAFT_ONLY');
|
||||
}
|
||||
if (match.status === 'SETTLED') {
|
||||
throw appBadRequest('ARCHIVE_BLOCKED');
|
||||
}
|
||||
const preview = await this.getMatchArchivePreview(matchId);
|
||||
if (preview.requiresForce && !opts.force) {
|
||||
throw appConflict('ARCHIVE_BLOCKED', preview);
|
||||
@@ -80,6 +77,9 @@ export class CatalogArchiveService {
|
||||
|
||||
const now = new Date();
|
||||
await this.prisma.$transaction(async (tx) => {
|
||||
await tx.settlementBatch.deleteMany({
|
||||
where: { matchId, status: 'PREVIEW' },
|
||||
});
|
||||
await tx.marketSelection.updateMany({
|
||||
where: { market: { matchId } },
|
||||
data: { status: 'CLOSED' },
|
||||
@@ -92,8 +92,7 @@ export class CatalogArchiveService {
|
||||
where: { id: matchId },
|
||||
data: {
|
||||
deletedAt: now,
|
||||
status:
|
||||
match.status === 'CANCELLED' || match.status === 'VOID' ? match.status : 'CANCELLED',
|
||||
status: TERMINAL_MATCH_STATUSES.has(match.status) ? match.status : 'CANCELLED',
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1256,7 +1256,7 @@ export class MatchesService {
|
||||
homeTeamLogoUrl: m.homeTeam?.logoUrl ?? null,
|
||||
awayTeamLogoUrl: m.awayTeam?.logoUrl ?? null,
|
||||
startTime: m.startTime.toISOString(),
|
||||
isHot: m.isHot ?? false,
|
||||
isHot: m.status === 'SETTLED' ? false : (m.isHot ?? false),
|
||||
displayOrder: m.displayOrder ?? 0,
|
||||
matchName: m.matchName ?? null,
|
||||
stage: m.stage ?? null,
|
||||
|
||||
@@ -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'));
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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 };
|
||||
});
|
||||
}
|
||||
|
||||
@@ -38,6 +38,7 @@ export class FundsPostingService {
|
||||
remark?: string;
|
||||
referenceId?: string;
|
||||
transactionType?: string;
|
||||
referenceType?: string;
|
||||
businessKey?: string;
|
||||
tx?: TxClient;
|
||||
}) {
|
||||
@@ -50,6 +51,7 @@ export class FundsPostingService {
|
||||
command.transactionType ?? 'MANUAL_WITHDRAW',
|
||||
command.tx,
|
||||
command.businessKey,
|
||||
command.referenceType,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -108,6 +108,7 @@ export class WalletService {
|
||||
transactionType = 'MANUAL_WITHDRAW',
|
||||
tx?: TxClient,
|
||||
businessKey?: string,
|
||||
referenceType = 'WITHDRAW',
|
||||
) {
|
||||
const amt = new Decimal(amount);
|
||||
if (amt.lte(0)) throw appBadRequest('AMOUNT_MUST_BE_POSITIVE');
|
||||
@@ -143,7 +144,7 @@ export class WalletService {
|
||||
balanceAfter,
|
||||
frozenBefore: w.frozen_balance,
|
||||
frozenAfter: w.frozen_balance,
|
||||
referenceType: 'WITHDRAW',
|
||||
referenceType,
|
||||
referenceId,
|
||||
businessKey,
|
||||
operatorId,
|
||||
@@ -372,6 +373,7 @@ export class WalletService {
|
||||
'ADMIN_WITHDRAW',
|
||||
'AGENT_WITHDRAW',
|
||||
'PLAYER_DEPOSIT',
|
||||
'PLAYER_DEPOSIT_REVERSAL',
|
||||
].includes(type)
|
||||
) {
|
||||
return type;
|
||||
@@ -395,6 +397,7 @@ export class WalletService {
|
||||
if (WalletService.SYSTEM_REMARKS.has(r)) return false;
|
||||
if (r.startsWith('Cashback batch ')) return false;
|
||||
if (r.startsWith('Deposit order ')) return false;
|
||||
if (r.startsWith('Revoke approved deposit ')) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -418,6 +421,9 @@ export class WalletService {
|
||||
const parts = [depositMethodName?.trim(), tx.referenceId?.trim()].filter(Boolean);
|
||||
return parts.length ? parts.join(' · ') : null;
|
||||
}
|
||||
if (type === 'PLAYER_DEPOSIT_REVERSAL' && tx.referenceId) {
|
||||
return tx.referenceId;
|
||||
}
|
||||
if (this.isCustomRemark(tx.remark)) return tx.remark!.trim();
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ import type { BetsService } from '../../betting/bets.service';
|
||||
import type { SettlementService } from '../../settlement/settlement.service';
|
||||
import type { WalletService } from '../../ledger/wallet.service';
|
||||
import type { PrismaService } from '../../../shared/prisma/prisma.service';
|
||||
import { expectEqual, expectThrows, expectTrue } from './smoke-test.helpers';
|
||||
import { expectAppErrorThrows, expectEqual, expectTrue } from './smoke-test.helpers';
|
||||
import type { SmokeTestCaseDef } from './smoke-test.cases';
|
||||
import {
|
||||
BetFlowFixtureIds,
|
||||
@@ -175,7 +175,7 @@ export function createBetFlowProbes(deps: BetFlowProbeDeps): SmokeTestCaseDef[]
|
||||
run: async () => {
|
||||
const fx = await createBetFlowFixture(deps.prisma, deps.wallet, { initialBalance: 50 });
|
||||
try {
|
||||
await expectThrows(
|
||||
await expectAppErrorThrows(
|
||||
'placeSingleBet',
|
||||
async () => {
|
||||
await deps.bets.placeSingleBet(
|
||||
@@ -187,7 +187,7 @@ export function createBetFlowProbes(deps: BetFlowProbeDeps): SmokeTestCaseDef[]
|
||||
`smoke-insuf-${fx.runId}`,
|
||||
);
|
||||
},
|
||||
'Insufficient balance',
|
||||
'INSUFFICIENT_BALANCE',
|
||||
);
|
||||
|
||||
const count = await deps.prisma.bet.count({ where: { userId: fx.playerId } });
|
||||
|
||||
@@ -14,7 +14,7 @@ import {
|
||||
type ScoreInput,
|
||||
} from '../../settlement/domain/settlement-calculator';
|
||||
import { resolveCashbackRateForBet } from '../cashback/cashback-rate.resolver';
|
||||
import { expectEqual, expectFalse, expectThrows, expectTrue } from './smoke-test.helpers';
|
||||
import { expectAppErrorThrows, expectEqual, expectFalse, expectTrue } from './smoke-test.helpers';
|
||||
import type { SmokeTestCaseMeta } from './smoke-test.types';
|
||||
|
||||
export type SmokeTestRunner = () => void | Promise<void>;
|
||||
@@ -547,7 +547,7 @@ export const SMOKE_TEST_CASES: SmokeTestCaseDef[] = [
|
||||
name: '低于最小投注额拒绝',
|
||||
run: async () => {
|
||||
const service = createBettingLimitsService();
|
||||
await expectThrows(
|
||||
await expectAppErrorThrows(
|
||||
'min stake',
|
||||
() =>
|
||||
service.validateBet({
|
||||
@@ -556,7 +556,7 @@ export const SMOKE_TEST_CASES: SmokeTestCaseDef[] = [
|
||||
stake: 0.5,
|
||||
potentialReturn: new Decimal(1),
|
||||
}),
|
||||
'Minimum stake is 1',
|
||||
'MIN_STAKE',
|
||||
{ stake: 0.5, minStake: 1 },
|
||||
);
|
||||
},
|
||||
@@ -567,7 +567,7 @@ export const SMOKE_TEST_CASES: SmokeTestCaseDef[] = [
|
||||
name: '超过单关最大投注额拒绝',
|
||||
run: async () => {
|
||||
const service = createBettingLimitsService();
|
||||
await expectThrows(
|
||||
await expectAppErrorThrows(
|
||||
'max stake',
|
||||
() =>
|
||||
service.validateBet({
|
||||
@@ -576,7 +576,7 @@ export const SMOKE_TEST_CASES: SmokeTestCaseDef[] = [
|
||||
stake: 60000,
|
||||
potentialReturn: new Decimal(70000),
|
||||
}),
|
||||
'Maximum stake is 50000',
|
||||
'MAX_STAKE',
|
||||
{ stake: 60000, maxStakeSingle: 50000 },
|
||||
);
|
||||
},
|
||||
@@ -587,7 +587,7 @@ export const SMOKE_TEST_CASES: SmokeTestCaseDef[] = [
|
||||
name: '超过最高派彩拒绝',
|
||||
run: async () => {
|
||||
const service = createBettingLimitsService();
|
||||
await expectThrows(
|
||||
await expectAppErrorThrows(
|
||||
'max payout',
|
||||
() =>
|
||||
service.validateBet({
|
||||
@@ -596,7 +596,7 @@ export const SMOKE_TEST_CASES: SmokeTestCaseDef[] = [
|
||||
stake: 100,
|
||||
potentialReturn: new Decimal(600000),
|
||||
}),
|
||||
'Potential return exceeds limit',
|
||||
'MAX_PAYOUT',
|
||||
{ potentialReturn: 600000, maxPayoutSingle: 500000 },
|
||||
);
|
||||
},
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
import { HttpException } from '@nestjs/common';
|
||||
import type { ApiErrorCode } from '@thebet365/shared';
|
||||
import { isCodedExceptionResponse } from '../../../shared/common/app-error';
|
||||
|
||||
export type SmokeTestStep = {
|
||||
label: string;
|
||||
input?: string;
|
||||
@@ -62,6 +66,18 @@ export function expectFalse(label: string, condition: boolean, input?: unknown,
|
||||
recordStep(label, input, 'false', condition ? failHint ?? 'true' : 'false', !condition);
|
||||
}
|
||||
|
||||
function resolveErrorCode(err: unknown): string | null {
|
||||
if (err instanceof HttpException) {
|
||||
const res = err.getResponse();
|
||||
if (isCodedExceptionResponse(res)) return res.code;
|
||||
}
|
||||
if (typeof err === 'object' && err !== null && 'response' in err) {
|
||||
const res = (err as { response: unknown }).response;
|
||||
if (isCodedExceptionResponse(res)) return res.code;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export async function expectThrows(
|
||||
label: string,
|
||||
fn: () => void | Promise<void>,
|
||||
@@ -77,6 +93,21 @@ export async function expectThrows(
|
||||
}
|
||||
}
|
||||
|
||||
export async function expectAppErrorThrows(
|
||||
label: string,
|
||||
fn: () => void | Promise<void>,
|
||||
code: ApiErrorCode,
|
||||
input?: unknown,
|
||||
) {
|
||||
try {
|
||||
await fn();
|
||||
recordStep(label, input, `error code ${code}`, 'no error thrown', false);
|
||||
} catch (err) {
|
||||
const actual = resolveErrorCode(err) ?? (err instanceof Error ? err.message : String(err));
|
||||
recordStep(label, input, `error code ${code}`, actual, actual === code);
|
||||
}
|
||||
}
|
||||
|
||||
export function formatStepsForResult(steps: SmokeTestStep[]): string[] {
|
||||
return steps.map((step, index) => {
|
||||
const lines = [`${index + 1}. ${step.label}`];
|
||||
|
||||
@@ -386,6 +386,7 @@ describe('SettlementService outright winner flow', () => {
|
||||
it('confirmSettlement settles outright bets as WON/LOST using stored winnerTeamId', async () => {
|
||||
const txBetUpdate = jest.fn().mockResolvedValue({});
|
||||
const txBetUpdateMany = jest.fn().mockResolvedValue({ count: 1 });
|
||||
const txMatchUpdate = jest.fn().mockResolvedValue({});
|
||||
transaction.mockImplementation(async (fn: (client: unknown) => Promise<void>) => {
|
||||
await fn({
|
||||
team: { findUnique: teamFindUnique },
|
||||
@@ -404,7 +405,7 @@ describe('SettlementService outright winner flow', () => {
|
||||
update: jest.fn().mockResolvedValue({}),
|
||||
updateMany: jest.fn().mockResolvedValue({ count: 1 }),
|
||||
},
|
||||
match: { update: jest.fn().mockResolvedValue({}) },
|
||||
match: { update: txMatchUpdate },
|
||||
});
|
||||
});
|
||||
settlementBatchFindUnique.mockResolvedValue({
|
||||
@@ -464,6 +465,12 @@ describe('SettlementService outright winner flow', () => {
|
||||
data: expect.objectContaining({ status: 'LOST' }),
|
||||
}),
|
||||
);
|
||||
expect(txMatchUpdate).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: { id: matchId },
|
||||
data: { status: 'SETTLED', isHot: false },
|
||||
}),
|
||||
);
|
||||
expect(result).toEqual({ success: true, batchId: batchId.toString() });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1099,7 +1099,7 @@ export class SettlementService {
|
||||
|
||||
await tx.match.update({
|
||||
where: { id: currentBatch.matchId },
|
||||
data: { status: 'SETTLED' },
|
||||
data: { status: 'SETTLED', isHot: false },
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
147
apps/api/src/infrastructure/database/run-settlement-audit.ts
Normal file
147
apps/api/src/infrastructure/database/run-settlement-audit.ts
Normal file
@@ -0,0 +1,147 @@
|
||||
/**
|
||||
* Prints concrete settlement / parlay / cashback amounts used in smoke & unit tests.
|
||||
* Run: pnpm --filter @thebet365/api audit:settlement
|
||||
*/
|
||||
import { Decimal } from '@prisma/client/runtime/library';
|
||||
import {
|
||||
calculateParlayPayout,
|
||||
calculatePayout,
|
||||
} from '../../domains/settlement/domain/settlement-calculator';
|
||||
import { resolveCashbackRateForBet } from '../../domains/operations/cashback/cashback-rate.resolver';
|
||||
|
||||
type Row = { scenario: string; stake: number; detail: string; payout: string; netProfit: string };
|
||||
|
||||
function fmt(n: number | string | Decimal) {
|
||||
return new Decimal(n).toFixed(2);
|
||||
}
|
||||
|
||||
function single(
|
||||
scenario: string,
|
||||
stake: number,
|
||||
odds: number,
|
||||
result: Parameters<typeof calculatePayout>[2],
|
||||
): Row {
|
||||
const payout = calculatePayout(stake, odds, result);
|
||||
return {
|
||||
scenario,
|
||||
stake,
|
||||
detail: `odds ${odds}, ${result}`,
|
||||
payout: fmt(payout),
|
||||
netProfit: fmt(payout.sub(stake)),
|
||||
};
|
||||
}
|
||||
|
||||
function parlay(
|
||||
scenario: string,
|
||||
stake: number,
|
||||
legs: Array<{ odds: number; result: Parameters<typeof calculatePayout>[2] }>,
|
||||
): Row {
|
||||
const { betResult, payout, effectiveOdds } = calculateParlayPayout(stake, legs);
|
||||
const legDesc = legs.map((l) => `${l.odds}@${l.result}`).join(' × ');
|
||||
return {
|
||||
scenario,
|
||||
stake,
|
||||
detail: `${betResult} | ${legDesc} | effOdds ${effectiveOdds.toFixed(4)}`,
|
||||
payout: fmt(payout),
|
||||
netProfit: fmt(payout.sub(stake)),
|
||||
};
|
||||
}
|
||||
|
||||
function cashbackExample(stake: number, rate: string, label: string): Row {
|
||||
const r = new Decimal(rate);
|
||||
const amount = new Decimal(stake).mul(r);
|
||||
return {
|
||||
scenario: label,
|
||||
stake,
|
||||
detail: `rate ${rate} → stake × rate`,
|
||||
payout: fmt(amount),
|
||||
netProfit: fmt(amount),
|
||||
};
|
||||
}
|
||||
|
||||
const rows: Row[] = [
|
||||
single('单关 1X2 全赢 (BF001)', 100, 2.0, 'WIN'),
|
||||
single('单关 1X2 全输 (BF002)', 100, 2.0, 'LOSE'),
|
||||
single('让球 -1 全赢 (S009)', 100, 1.85, 'WIN'),
|
||||
single('让球 -1 走水 (S010)', 100, 1.85, 'PUSH'),
|
||||
single('让球 -0.25 半输 (S011)', 100, 1.85, 'HALF_LOSE'),
|
||||
single('半赢派彩 (S011B)', 100, 1.85, 'HALF_WIN'),
|
||||
single('让球 -0.5 全输 (S012)', 100, 1.85, 'LOSE'),
|
||||
single('大小 小球赢 (S015)', 100, 1.95, 'WIN'),
|
||||
parlay('串关全中 (S016)', 100, [
|
||||
{ odds: 1.8, result: 'WIN' },
|
||||
{ odds: 2.0, result: 'WIN' },
|
||||
]),
|
||||
parlay('串关一关输 (S017)', 100, [
|
||||
{ odds: 1.8, result: 'WIN' },
|
||||
{ odds: 2.0, result: 'LOSE' },
|
||||
]),
|
||||
parlay('串关一关走水 (S018)', 100, [
|
||||
{ odds: 1.8, result: 'WIN' },
|
||||
{ odds: 2.0, result: 'PUSH' },
|
||||
{ odds: 1.9, result: 'WIN' },
|
||||
]),
|
||||
parlay('串关全走水/作废 (S019)', 100, [
|
||||
{ odds: 1.8, result: 'PUSH' },
|
||||
{ odds: 2.0, result: 'VOID' },
|
||||
]),
|
||||
];
|
||||
|
||||
const cbRates = [
|
||||
{
|
||||
label: '返水 玩家专属 (CB001)',
|
||||
rate: resolveCashbackRateForBet({
|
||||
userId: BigInt(100),
|
||||
agentId: BigInt(200),
|
||||
marketTypes: ['FT_1X2'],
|
||||
agentDefaultRate: new Decimal('0.01'),
|
||||
rules: [{ targetType: 'USER', targetId: BigInt(100), rate: new Decimal('0.03'), marketType: null }],
|
||||
}).toString(),
|
||||
},
|
||||
{
|
||||
label: '返水 玩法专属 (CB002)',
|
||||
rate: resolveCashbackRateForBet({
|
||||
userId: BigInt(100),
|
||||
agentId: BigInt(200),
|
||||
marketTypes: ['FT_HANDICAP'],
|
||||
agentDefaultRate: new Decimal('0.01'),
|
||||
rules: [
|
||||
{ targetType: 'GLOBAL', targetId: null, rate: new Decimal('0.005'), marketType: 'FT_HANDICAP' },
|
||||
],
|
||||
}).toString(),
|
||||
},
|
||||
{
|
||||
label: '返水 代理默认 (CB003)',
|
||||
rate: resolveCashbackRateForBet({
|
||||
userId: BigInt(100),
|
||||
agentId: BigInt(200),
|
||||
marketTypes: ['FT_1X2'],
|
||||
agentDefaultRate: new Decimal('0.02'),
|
||||
rules: [],
|
||||
}).toString(),
|
||||
},
|
||||
];
|
||||
|
||||
console.log('\n=== 结算派彩金额(stake=100 unless noted)===\n');
|
||||
console.table(rows);
|
||||
|
||||
console.log('\n=== 返水比例 → 到账金额(已结算注单,公式:stake × rate)===\n');
|
||||
for (const { label, rate } of cbRates) {
|
||||
console.log(`${label}: rate=${rate}`);
|
||||
console.table([
|
||||
cashbackExample(100, rate, 'stake 100'),
|
||||
cashbackExample(500, rate, 'stake 500'),
|
||||
cashbackExample(1000, rate, 'stake 1000'),
|
||||
]);
|
||||
}
|
||||
|
||||
console.log('\n=== 端到端钱包(BF001–BF005,smoke bet-flow)===\n');
|
||||
console.table([
|
||||
{ case: 'BF001', flow: '单关赢 100@2.0, 2-1', wallet: '1000 → 900 avail + 100 frozen → 1100 avail', actualReturn: '200' },
|
||||
{ case: 'BF002', flow: '单关输 和局+2-1', wallet: '1000 → 900 avail', actualReturn: '0' },
|
||||
{ case: 'BF003', flow: '幂等 50 注', wallet: '500 → 450 avail + 50 frozen', actualReturn: '—' },
|
||||
{ case: 'BF004', flow: '余额不足', wallet: '50 不变', actualReturn: '—' },
|
||||
{ case: 'BF005', flow: '代理额度 玩家输100', wallet: '玩家 900', agentUsedCredit: '1000 → 900' },
|
||||
]);
|
||||
|
||||
console.log('\n注:dev seed 下 agent1 cashbackRate 默认为 0;需后台配置规则或代理默认比例后才会产生返水批次。\n');
|
||||
30
apps/api/src/infrastructure/database/run-smoke-cli.ts
Normal file
30
apps/api/src/infrastructure/database/run-smoke-cli.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import { AppModule } from '../../app.module';
|
||||
import { SmokeTestService } from '../../domains/operations/smoke-tests/smoke-test.service';
|
||||
|
||||
async function main() {
|
||||
const app = await NestFactory.createApplicationContext(AppModule, {
|
||||
logger: ['error', 'warn'],
|
||||
});
|
||||
try {
|
||||
const smoke = app.get(SmokeTestService);
|
||||
smoke.assertAllowed();
|
||||
const summary = await smoke.run();
|
||||
console.log(
|
||||
`Smoke: pass=${summary.passed} fail=${summary.failed} skip=${summary.skipped} total=${summary.total} (${summary.durationMs}ms)`,
|
||||
);
|
||||
if (summary.failed > 0) {
|
||||
for (const r of summary.results.filter((x) => x.status === 'FAIL')) {
|
||||
console.error(`FAIL ${r.id} ${r.name}: ${r.error ?? r.message ?? ''}`);
|
||||
}
|
||||
process.exit(1);
|
||||
}
|
||||
} finally {
|
||||
await app.close();
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error(err);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -18,10 +18,28 @@ export async function seedDemoMarkets(prisma: PrismaClient, matchId: bigint) {
|
||||
cfg.marketType.includes('CORRECT_SCORE') &&
|
||||
exists._count.selections < cfg.selectionTemplate.length;
|
||||
if (needRefresh) {
|
||||
await prisma.market.delete({ where: { id: exists.id } });
|
||||
} else {
|
||||
continue;
|
||||
const existing = await prisma.marketSelection.findMany({
|
||||
where: { marketId: exists.id },
|
||||
select: { selectionCode: true },
|
||||
});
|
||||
const existingCodes = new Set(existing.map((s) => s.selectionCode));
|
||||
const missing = cfg.selectionTemplate
|
||||
.map((s, i) => ({ ...s, sortOrder: i }))
|
||||
.filter((s) => !existingCodes.has(s.code));
|
||||
if (missing.length > 0) {
|
||||
await prisma.marketSelection.createMany({
|
||||
data: missing.map((s) => ({
|
||||
marketId: exists.id,
|
||||
selectionCode: s.code,
|
||||
selectionName: s.name,
|
||||
odds: s.odds,
|
||||
sortOrder: s.sortOrder,
|
||||
status: 'OPEN',
|
||||
})),
|
||||
});
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
await prisma.market.create({
|
||||
data: {
|
||||
|
||||
Reference in New Issue
Block a user