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

@@ -87,8 +87,21 @@ const zh: Record<string, string> = {
'deposit.confirm_reopen': '订单将恢复为待审核,可再次批准或拒绝。确定继续?',
'deposit.delete': '删除',
'deposit.confirm_delete': '【仅删除记录】将永久删除本订单记录及截图文件。确定继续?',
'deposit.delete_failed': '删除失败',
'deposit.prev': '上一页',
'deposit.next': '下一页',
'deposit.audit_history': '审核记录',
'deposit.audit_action': '操作',
'deposit.audit_actor': '操作人',
'deposit.audit_time': '时间',
'deposit.audit_remark': '备注',
'deposit.audit_submitted': '提交申请',
'deposit.audit_approved': '审核通过',
'deposit.audit_rejected': '审核拒绝',
'deposit.audit_revoked': '撤销审核',
'deposit.audit_reopened': '重新审核',
'deposit.audit_deleted': '已删除',
'deposit.audit_empty': '暂无审核记录',
'deposit.add_method': '+ 添加',
'deposit.display_name': '展示名称',
'deposit.details': '详情',
@@ -357,8 +370,21 @@ const en: Record<string, string> = {
'deposit.confirm_reopen': 'The order will return to pending for approve or reject. Continue?',
'deposit.delete': 'Delete',
'deposit.confirm_delete': '[Records only] Permanently delete this order record and screenshot. Continue?',
'deposit.delete_failed': 'Delete failed',
'deposit.prev': 'Prev',
'deposit.next': 'Next',
'deposit.audit_history': 'Review history',
'deposit.audit_action': 'Action',
'deposit.audit_actor': 'Actor',
'deposit.audit_time': 'Time',
'deposit.audit_remark': 'Remark',
'deposit.audit_submitted': 'Submitted',
'deposit.audit_approved': 'Approved',
'deposit.audit_rejected': 'Rejected',
'deposit.audit_revoked': 'Approval revoked',
'deposit.audit_reopened': 'Reopened for review',
'deposit.audit_deleted': 'Deleted',
'deposit.audit_empty': 'No review history yet',
'deposit.add_method': '+ Add',
'deposit.display_name': 'Display Name',
'deposit.details': 'Details',
@@ -625,8 +651,21 @@ const ms: Record<string, string> = {
'deposit.confirm_reopen': 'Pesanan kembali menunggu untuk lulus atau tolak. Teruskan?',
'deposit.delete': 'Padam',
'deposit.confirm_delete': '[Rekod sahaja] Padam rekod pesanan dan tangkapan skrin. Teruskan?',
'deposit.delete_failed': 'Gagal memadam',
'deposit.prev': 'Sebelum',
'deposit.next': 'Seterus',
'deposit.audit_history': 'Sejarah semakan',
'deposit.audit_action': 'Tindakan',
'deposit.audit_actor': 'Pengendali',
'deposit.audit_time': 'Masa',
'deposit.audit_remark': 'Catatan',
'deposit.audit_submitted': 'Dihantar',
'deposit.audit_approved': 'Diluluskan',
'deposit.audit_rejected': 'Ditolak',
'deposit.audit_revoked': 'Kelulusan dibatalkan',
'deposit.audit_reopened': 'Dibuka semula',
'deposit.audit_deleted': 'Dipadam',
'deposit.audit_empty': 'Tiada sejarah semakan',
'deposit.add_method': '+ Tambah',
'deposit.display_name': 'Nama Paparan',
'deposit.details': 'Butiran',

View File

@@ -4,6 +4,9 @@ import 'element-plus/dist/index.css';
import App from './App.vue';
import router from './router';
import { createAdminI18n } from './i18n';
import { applyElementPlusDialogDefaults } from './plugins/element-plus-defaults';
applyElementPlusDialogDefaults();
async function bootstrap() {
const i18n = await createAdminI18n();

View File

@@ -0,0 +1,6 @@
import { ElDialog } from 'element-plus';
/** Prevent accidental form data loss from mask clicks across admin dialogs. */
export function applyElementPlusDialogDefaults() {
ElDialog.props.closeOnClickModal.default = false;
}

View File

@@ -2,6 +2,7 @@
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useAdminLocale } from '../composables/useAdminLocale';
import { resolveApiError } from '../i18n/form-validation';
import api from '../api';
import AdminTableEmpty from '../components/AdminTableEmpty.vue';
import { formatAmount } from '../utils/format-amount';
@@ -27,6 +28,20 @@ interface DepositOrderRow {
paymentMethodName: string | null;
}
interface DepositAuditLogRow {
id: string;
action: string;
actorId: string | null;
actorType: string;
actorUsername: string | null;
statusBefore: string | null;
statusAfter: string;
amount: string | null;
approvedAmount: string | null;
remark: string | null;
createdAt: string;
}
const items = ref<DepositOrderRow[]>([]);
const total = ref(0);
const page = ref(1);
@@ -53,6 +68,12 @@ const rejectReason = ref('');
const previewUrl = ref('');
const previewVisible = ref(false);
// Audit history dialog
const auditDialogVisible = ref(false);
const auditTarget = ref<DepositOrderRow | null>(null);
const auditLogs = ref<DepositAuditLogRow[]>([]);
const auditLoading = ref(false);
async function fetchList() {
loading.value = true;
try {
@@ -87,6 +108,32 @@ function openScreenshot(url: string) {
previewVisible.value = true;
}
async function openAuditHistory(row: DepositOrderRow) {
auditTarget.value = row;
auditDialogVisible.value = true;
auditLoading.value = true;
auditLogs.value = [];
try {
const { data } = await api.get(`/admin/deposit-orders/${row.id}/audit-logs`);
auditLogs.value = data.data?.items ?? [];
} catch {
auditLogs.value = [];
} finally {
auditLoading.value = false;
}
}
function auditActionLabel(action: string) {
const key = `deposit.audit_${action.toLowerCase()}`;
const translated = t(key);
return translated !== key ? translated : action;
}
function auditActorLabel(row: DepositAuditLogRow) {
if (row.actorUsername) return row.actorUsername;
return row.actorType === 'PLAYER' ? t('deposit.player') : '-';
}
async function confirmDepositAction(message: string, title: string): Promise<boolean> {
try {
await ElMessageBox.confirm(message, title, {
@@ -101,8 +148,7 @@ async function confirmDepositAction(message: string, title: string): Promise<boo
}
function showApiError(e: unknown) {
const msg = (e as { response?: { data?: { message?: string } } })?.response?.data?.message;
ElMessage.error(msg || 'Error');
ElMessage.error(resolveApiError(e, t, 'deposit.delete_failed'));
}
async function handleApprove() {
@@ -262,6 +308,7 @@ onMounted(fetchList);
<td class="remark-cell">{{ row.remark || row.rejectReason || '-' }}</td>
<td class="time-cell">{{ new Date(row.createdAt).toLocaleString() }}</td>
<td>
<button class="btn-sm btn-audit" @click="openAuditHistory(row)">{{ t('deposit.audit_history') }}</button>
<template v-if="row.status === 'PENDING'">
<button class="btn-sm btn-approve" @click="openApprove(row)">{{ t('deposit.approve') }}</button>
<button class="btn-sm btn-reject" @click="openReject(row)">{{ t('deposit.reject') }}</button>
@@ -293,7 +340,7 @@ onMounted(fetchList);
</div>
<!-- Approve Dialog -->
<div v-if="approveDialogVisible" class="dialog-overlay" @click.self="approveDialogVisible = false">
<div v-if="approveDialogVisible" class="dialog-overlay">
<div class="dialog-box">
<h3>{{ t('deposit.approve_title') }}</h3>
<p class="approve-check-hint">{{ t('deposit.approve_check_hint') }}</p>
@@ -325,7 +372,7 @@ onMounted(fetchList);
</div>
<!-- Reject Dialog -->
<div v-if="rejectDialogVisible" class="dialog-overlay" @click.self="rejectDialogVisible = false">
<div v-if="rejectDialogVisible" class="dialog-overlay">
<div class="dialog-box">
<h3>{{ t('deposit.reject_title') }}</h3>
<div v-if="rejectTarget" class="reject-content">
@@ -347,8 +394,41 @@ onMounted(fetchList);
</div>
</div>
<!-- Audit History Dialog -->
<div v-if="auditDialogVisible" class="dialog-overlay">
<div class="dialog-box audit-dialog">
<h3>{{ t('deposit.audit_history') }}</h3>
<p v-if="auditTarget" class="audit-order-no">{{ auditTarget.orderNo }} · {{ auditTarget.playerUsername || auditTarget.playerId }}</p>
<div v-if="auditLoading" class="audit-loading">{{ t('common.loading') }}</div>
<div v-else-if="!auditLogs.length" class="audit-empty">{{ t('deposit.audit_empty') }}</div>
<table v-else class="audit-table">
<thead>
<tr>
<th>{{ t('deposit.audit_action') }}</th>
<th>{{ t('deposit.audit_actor') }}</th>
<th>{{ t('deposit.approved_amount') }}</th>
<th>{{ t('deposit.audit_remark') }}</th>
<th>{{ t('deposit.audit_time') }}</th>
</tr>
</thead>
<tbody>
<tr v-for="log in auditLogs" :key="log.id">
<td>{{ auditActionLabel(log.action) }}</td>
<td>{{ auditActorLabel(log) }}</td>
<td>{{ log.approvedAmount ? formatAmount(log.approvedAmount) : (log.amount ? formatAmount(log.amount) : '-') }}</td>
<td class="remark-cell">{{ log.remark || '-' }}</td>
<td class="time-cell">{{ new Date(log.createdAt).toLocaleString() }}</td>
</tr>
</tbody>
</table>
<div class="dialog-actions">
<button class="btn-cancel" @click="auditDialogVisible = false">{{ t('common.cancel') }}</button>
</div>
</div>
</div>
<!-- Screenshot Preview -->
<div v-if="previewVisible" class="dialog-overlay" @click.self="previewVisible = false">
<div v-if="previewVisible" class="dialog-overlay">
<div class="preview-box">
<img :src="previewUrl" class="preview-image" />
<button class="close-preview" @click="previewVisible = false"></button>
@@ -386,6 +466,15 @@ onMounted(fetchList);
.btn-reject:hover { background: #4a2525; }
.btn-reopen { background: #2a2410; color: #e6a23c; }
.btn-reopen:hover { background: #3a3218; }
.action-hint {
display: inline-block;
margin-left: 4px;
font-size: 11px;
color: #888;
vertical-align: middle;
}
.btn-audit { background: #1f2433; color: #8ab4ff; }
.btn-audit:hover { background: #2a3348; }
.btn-delete { background: #2a2a2a; color: #aaa; }
.btn-delete:hover { background: #3a3a3a; color: #f56c6c; }
.actions-cell { white-space: nowrap; }
@@ -628,6 +717,13 @@ onMounted(fetchList);
background: var(--danger-text);
}
.audit-dialog { min-width: 520px; max-width: 760px; }
.audit-order-no { margin: -8px 0 12px; font-size: 12px; color: var(--text-muted); }
.audit-loading, .audit-empty { padding: 20px 0; text-align: center; color: var(--text-muted); font-size: 13px; }
.audit-table { width: 100%; border-collapse: collapse; font-size: 12px; margin-bottom: 8px; }
.audit-table th, .audit-table td { padding: 8px 6px; border-bottom: 1px solid var(--border-soft); text-align: left; }
.audit-table th { color: var(--text-muted); font-weight: 700; }
.close-preview {
background: var(--text);
color: #ffffff;

View File

@@ -238,7 +238,7 @@ async function doUpload() {
</div>
<!-- Upload dialog -->
<div v-if="uploadDialogVisible" class="dialog-overlay" @click.self="uploadDialogVisible = false">
<div v-if="uploadDialogVisible" class="dialog-overlay">
<div class="dialog">
<div class="dialog-header">
<span>{{ t('media.upload_dialog') }}</span>

View File

@@ -234,7 +234,7 @@ onMounted(fetchList);
</table>
<!-- Create/Edit Dialog -->
<div v-if="dialogVisible" class="dialog-overlay" @click.self="dialogVisible = false">
<div v-if="dialogVisible" class="dialog-overlay">
<div class="dialog-box">
<h3>{{ editingId ? t('deposit.edit_method') : t('deposit.create_method') }}</h3>
<div class="form-group" v-if="!editingId">

View File

@@ -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"

View 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;

View File

@@ -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;

View File

@@ -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 {

View File

@@ -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(

View File

@@ -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,
});
}
}

View File

@@ -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' });

View File

@@ -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',
},
});
});

View File

@@ -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,

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 };
});
}

View File

@@ -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,
);
}

View File

@@ -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;
}

View File

@@ -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 } });

View File

@@ -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 },
);
},

View File

@@ -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}`];

View File

@@ -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() });
});
});

View File

@@ -1099,7 +1099,7 @@ export class SettlementService {
await tx.match.update({
where: { id: currentBatch.matchId },
data: { status: 'SETTLED' },
data: { status: 'SETTLED', isHot: false },
});
});

View 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=== 端到端钱包BF001BF005smoke 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');

View 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);
});

View File

@@ -18,11 +18,29 @@ 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: {
matchId,

View File

@@ -12,6 +12,7 @@ import { useAuthStore } from '../stores/auth';
import { formatMoney, parseAmount } from '../utils/localeDisplay';
import BetSuccessOverlay from './BetSuccessOverlay.vue';
import api from '../api';
import { usePlayerProfile } from '../composables/usePlayerProfile';
const props = defineProps<{ modelValue: boolean }>();
const emit = defineEmits<{ 'update:modelValue': [boolean] }>();
@@ -19,6 +20,7 @@ const emit = defineEmits<{ 'update:modelValue': [boolean] }>();
const { t, locale } = useI18n();
const slip = useBetSlipStore();
const auth = useAuthStore();
const { refreshProfile } = usePlayerProfile();
const show = computed({
get: () => props.modelValue,
set: (v) => emit('update:modelValue', v),
@@ -261,7 +263,7 @@ async function placeBet() {
}
success.value = t('bet.place_success');
showSuccess.value = true;
await loadBalance();
await Promise.all([loadBalance(), refreshProfile()]);
setTimeout(() => {
if (showSuccess.value) onSuccessDone();
}, 2200);

View File

@@ -6,7 +6,7 @@ import { formatMoney } from '../utils/localeDisplay';
import { usePlayerProfile } from '../composables/usePlayerProfile';
const { locale, t } = useI18n();
const { profileRaw } = usePlayerProfile();
const { profileRaw, refreshProfile } = usePlayerProfile();
const router = useRouter();
const open = ref(false);
const root = ref<HTMLElement | null>(null);
@@ -38,7 +38,9 @@ const total = computed(() =>
);
function toggle() {
open.value = !open.value;
const next = !open.value;
open.value = next;
if (next) void refreshProfile();
}
function close() {

View File

@@ -64,6 +64,8 @@ const openCount = computed(() => props.matches.filter(m => m.matchPhase === 'ope
:src="leagueLogoUrl || saishiImg"
alt=""
class="league-saishi"
loading="lazy"
decoding="async"
/>
</button>

View File

@@ -91,6 +91,8 @@ const liveScoreText = computed(() => {
class="team-flag"
:class="{ 'flag-logo': homeIsLogo }"
alt=""
loading="lazy"
decoding="async"
/>
</div>
@@ -108,6 +110,8 @@ const liveScoreText = computed(() => {
class="team-flag"
:class="{ 'flag-logo': awayIsLogo }"
alt=""
loading="lazy"
decoding="async"
/>
</div>
</div>

View File

@@ -2,6 +2,7 @@
import { ref, computed, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import api from '../../api';
import { usePlayerProfile } from '../../composables/usePlayerProfile';
import { formatMoney, parseAmount } from '../../utils/localeDisplay';
import { teamFlagUrl } from '../../utils/teamFlag';
import BetSuccessOverlay from '../BetSuccessOverlay.vue';
@@ -23,6 +24,7 @@ const props = defineProps<{
const emit = defineEmits<{ close: [] }>();
const { t, locale } = useI18n();
const { refreshProfile } = usePlayerProfile();
const step = ref<'form' | 'success'>('form');
const stake = ref(1);
@@ -105,6 +107,7 @@ async function submit() {
balance.value = successBalance.value;
step.value = 'success';
showSuccess.value = true;
void refreshProfile();
} catch (e: unknown) {
error.value =
(e as { response?: { data?: { error?: string } } })?.response?.data?.error ||

View File

@@ -23,6 +23,7 @@ const profileRaw = ref<ProfileData | null>(null);
const loading = ref(false);
let loadPromise: Promise<void> | null = null;
let assigningDefault = false;
let visibilityBound = false;
function profileSeed(profile: ProfileData | null): string {
if (!profile) return '';
@@ -111,6 +112,20 @@ async function loadProfile(force = false) {
return loadPromise;
}
function refreshProfile() {
return loadProfile(true);
}
function bindProfileVisibilityRefresh() {
if (visibilityBound || typeof document === 'undefined') return;
visibilityBound = true;
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'visible' && profileRaw.value) {
void loadProfile(true);
}
});
}
const avatarKey = computed(() => {
const saved = profileRaw.value?.preferences?.avatarKey;
if (saved && isValidAvatarKey(saved)) return saved;
@@ -138,6 +153,8 @@ export function usePlayerProfile() {
avatarKey,
avatarUrl,
loadProfile,
refreshProfile,
bindProfileVisibilityRefresh,
setAvatarKey,
};
}

View File

@@ -138,6 +138,7 @@ export default {
tx_admin_deposit: 'Admin top-up',
tx_agent_deposit: 'Agent top-up',
tx_player_deposit: 'Self deposit',
tx_player_deposit_reversal: 'Deposit reversal',
tx_withdraw: 'Withdrawal',
tx_admin_withdraw: 'Admin withdraw',
tx_agent_withdraw: 'Agent withdraw',
@@ -152,7 +153,8 @@ export default {
tx_cashback: 'Cashback credit',
tx_resettle: 'Resettlement',
summary_bet: 'Bet {betNo}',
summary_opening_bonus: 'Opening bonus',
remark_deposit_revoke: 'Revoked approved deposit {orderNo}',
remark_deposit_revoke_generic: 'Revoked approved deposit',
stats_income: 'Income',
stats_expense: 'Expense',
stats_net: 'Net',
@@ -221,6 +223,25 @@ export default {
apply_time: 'Apply time',
review_time: 'Review time',
remark: 'Remark',
audit_title: 'Review history',
audit_submitted: 'Submitted',
audit_approved: 'Approved',
audit_rejected: 'Rejected',
audit_revoked: 'Approval revoked',
audit_reopened: 'Reopened for review',
audit_by_player: 'Player',
audit_by_admin: 'Platform review',
audit_amount: 'Amount',
audit_credited: 'Credited amount',
audit_remark_label: 'Note',
audit_summary: 'Review history · {count} steps',
audit_toggle_show: 'Show review history',
audit_toggle_hide: 'Hide review history',
view_detail: 'View details',
order_detail: 'Order details',
reapply: 'Re-apply',
reapply_hint: 'You are resubmitting this order. Transfer again and upload a new screenshot.',
back_to_history: 'Back to history',
},
cashback: {
title: 'Cashback Details',

View File

@@ -144,6 +144,7 @@ export default {
tx_admin_deposit: 'Tambah baki admin',
tx_agent_deposit: 'Tambah baki ejen',
tx_player_deposit: 'Deposit sendiri',
tx_player_deposit_reversal: 'Pembalikan deposit',
tx_withdraw: 'Pengeluaran',
tx_admin_withdraw: 'Pengeluaran admin',
tx_agent_withdraw: 'Pengeluaran ejen',
@@ -158,7 +159,8 @@ export default {
tx_cashback: 'Kredit rebat',
tx_resettle: 'Penyelesaian Semula',
summary_bet: 'Pertaruhan {betNo}',
summary_opening_bonus: 'Bonus pembukaan',
remark_deposit_revoke: 'Deposit diluluskan dibatalkan {orderNo}',
remark_deposit_revoke_generic: 'Deposit diluluskan dibatalkan',
stats_income: 'Pendapatan',
stats_expense: 'Perbelanjaan',
stats_net: 'Bersih',
@@ -227,6 +229,25 @@ export default {
apply_time: 'Masa permohonan',
review_time: 'Masa semakan',
remark: 'Catatan',
audit_title: 'Sejarah semakan',
audit_submitted: 'Dihantar',
audit_approved: 'Diluluskan',
audit_rejected: 'Ditolak',
audit_revoked: 'Kelulusan dibatalkan',
audit_reopened: 'Dibuka semula untuk semakan',
audit_by_player: 'Pemain',
audit_by_admin: 'Semakan platform',
audit_amount: 'Jumlah',
audit_credited: 'Jumlah dikreditkan',
audit_remark_label: 'Catatan',
audit_summary: 'Sejarah semakan · {count} langkah',
audit_toggle_show: 'Lihat sejarah semakan',
audit_toggle_hide: 'Sembunyikan sejarah semakan',
view_detail: 'Lihat butiran',
order_detail: 'Butiran pesanan',
reapply: 'Mohon semula',
reapply_hint: 'Anda menghantar semula pesanan ini. Buat pindahan baharu dan muat naik tangkapan skrin baharu.',
back_to_history: 'Kembali ke sejarah',
},
cashback: {
title: 'Butiran Rebat',

View File

@@ -138,6 +138,7 @@ export default {
tx_admin_deposit: '管理员上分',
tx_agent_deposit: '代理上分',
tx_player_deposit: '自助充值',
tx_player_deposit_reversal: '充值撤销',
tx_withdraw: '人工提款',
tx_admin_withdraw: '管理员下分',
tx_agent_withdraw: '代理下分',
@@ -152,7 +153,8 @@ export default {
tx_cashback: '返水入账',
tx_resettle: '重新结算',
summary_bet: '注单 {betNo}',
summary_opening_bonus: '开户赠金',
remark_deposit_revoke: '撤销已通过充值 {orderNo}',
remark_deposit_revoke_generic: '撤销已通过充值',
stats_income: '收入',
stats_expense: '支出',
stats_net: '净额',
@@ -221,6 +223,25 @@ export default {
apply_time: '申请时间',
review_time: '审核时间',
remark: '审核备注',
audit_title: '审核记录',
audit_submitted: '提交申请',
audit_approved: '审核通过',
audit_rejected: '审核拒绝',
audit_revoked: '撤销审核',
audit_reopened: '重新审核',
audit_by_player: '玩家提交',
audit_by_admin: '平台审核',
audit_amount: '金额',
audit_credited: '入账金额',
audit_remark_label: '备注',
audit_summary: '审核记录 · {count} 步',
audit_toggle_show: '查看审核记录',
audit_toggle_hide: '收起审核记录',
view_detail: '查看详情',
order_detail: '订单详情',
reapply: '重新申请',
reapply_hint: '将在原订单上重新提交,请重新转账并上传新的截图。',
back_to_history: '返回充值记录',
},
cashback: {
title: '返水明细',

View File

@@ -52,7 +52,7 @@ const showBottomNav = computed(() => {
return false;
});
const { announcements, load: loadPlayerHome } = usePlayerHome();
const { loadProfile } = usePlayerProfile();
const { loadProfile, refreshProfile, bindProfileVisibilityRefresh } = usePlayerProfile();
const mainRef = ref<HTMLElement | null>(null);
const tabScrollTops = new Map<string, number>();
const customerServiceOpen = ref(false);
@@ -71,8 +71,11 @@ watch(
},
);
const balanceRefreshPaths = ['/profile', '/wallet', '/bets'];
onMounted(() => {
if (auth.user?.locale) void initFromUser(auth.user.locale);
bindProfileVisibilityRefresh();
});
watch(
@@ -87,6 +90,16 @@ watch(
},
{ immediate: true },
);
watch(
() => route.path,
(path) => {
if (!auth.token) return;
if (balanceRefreshPaths.some((p) => path === p || path.startsWith(`${p}/`))) {
void refreshProfile();
}
},
);
</script>
<template>

View File

@@ -0,0 +1,26 @@
export type CashbackRecord = {
id: string;
batchNo: string;
periodStart: string;
periodEnd: string;
confirmedAt: string | null;
effectiveStake: string;
betCount: number;
rate: string;
amount: string;
createdAt: string;
};
/** API returns a plain array; older clients may expect { items }. */
export function parseCashbackApiData(data: unknown): CashbackRecord[] {
if (Array.isArray(data)) return data as CashbackRecord[];
if (data && typeof data === 'object' && 'items' in data) {
const items = (data as { items?: unknown }).items;
return Array.isArray(items) ? (items as CashbackRecord[]) : [];
}
return [];
}
export function sumCashbackAmount(rows: Array<{ amount: string }>): number {
return rows.reduce((sum, row) => sum + Math.abs(parseFloat(row.amount) || 0), 0);
}

View File

@@ -0,0 +1,112 @@
/** Player-facing deposit audit log remark formatting — strips internal order codes & API templates. */
const ORDER_NO_SUFFIX = /\s+[A-Z0-9]{10,}\s*$/i;
const INTERNAL_REMARK_EXACT = [
/^Revoke approved deposit\s*[A-Z0-9]*\s*$/i,
/^撤销已通过充值\s*[A-Z0-9]*\s*$/,
/^Deposit order\s+[A-Z0-9]+\s*$/i,
];
export type DepositAuditLogLike = {
action: string;
remark: string | null;
};
export type DepositAuditRemarkDisplay =
| { kind: 'reject'; text: string }
| { kind: 'note'; text: string }
| null;
function normalizeRemark(value: string | null | undefined) {
return value?.trim() ?? '';
}
/** True when remark is empty or only internal/system text — hide from player UI. */
export function isHiddenDepositAuditRemark(log: DepositAuditLogLike): boolean {
const remark = normalizeRemark(log.remark);
if (!remark) return true;
if (log.action === 'REVOKED') {
return INTERNAL_REMARK_EXACT.some((pattern) => pattern.test(remark));
}
return INTERNAL_REMARK_EXACT.some((pattern) => pattern.test(remark));
}
function sanitizePlayerRemark(raw: string): string | null {
let text = raw.trim();
if (!text) return null;
if (/^Revoke approved deposit/i.test(text)) {
return null;
}
if (/^撤销已通过充值/.test(text)) {
return null;
}
if (/^Deposit order\s+/i.test(text)) {
return null;
}
text = text.replace(ORDER_NO_SUFFIX, '').trim();
return text || null;
}
/** Format remark for timeline; returns null when nothing meaningful to show. */
export function formatDepositAuditRemark(
log: DepositAuditLogLike,
t: (key: string, params?: Record<string, unknown>) => string,
): DepositAuditRemarkDisplay {
const remark = normalizeRemark(log.remark);
if (!remark) return null;
if (log.action === 'REVOKED' && isHiddenDepositAuditRemark(log)) {
return { kind: 'note', text: t('wallet.remark_deposit_revoke_generic') };
}
const sanitized = sanitizePlayerRemark(remark);
if (!sanitized) return null;
if (log.action === 'REJECTED') {
return { kind: 'reject', text: sanitized };
}
return { kind: 'note', text: sanitized };
}
/** Skip reject remark in timeline when card-level reject reason already shows the same text. */
export function shouldShowAuditRejectInTimeline(
log: DepositAuditLogLike,
orderRejectReason: string | null | undefined,
): boolean {
if (log.action !== 'REJECTED') return true;
const remark = normalizeRemark(log.remark);
if (!remark) return false;
const cardReason = normalizeRemark(orderRejectReason);
return remark !== cardReason;
}
export function auditActionTone(action: string): 'submitted' | 'approved' | 'rejected' | 'revoked' | 'reopened' | 'default' {
switch (action.toUpperCase()) {
case 'SUBMITTED':
return 'submitted';
case 'APPROVED':
return 'approved';
case 'REJECTED':
return 'rejected';
case 'REVOKED':
return 'revoked';
case 'REOPENED':
return 'reopened';
default:
return 'default';
}
}
/** Secondary actor line — only when it adds meaning beyond the action title. */
export function auditActorSecondary(log: { action: string; actorType: string }, t: (key: string) => string): string | null {
if (log.actorType === 'PLAYER' && (log.action === 'SUBMITTED' || log.action === 'REOPENED')) {
return t('recharge.audit_by_player');
}
return null;
}

View File

@@ -22,6 +22,7 @@ export const TX_KEY_MAP: Record<string, string> = {
DEPOSIT: 'wallet.tx_deposit',
WITHDRAW: 'wallet.tx_withdraw',
PLAYER_DEPOSIT: 'wallet.tx_player_deposit',
PLAYER_DEPOSIT_REVERSAL: 'wallet.tx_player_deposit_reversal',
};
export function txTypeKey(type: string): string {
@@ -53,11 +54,29 @@ export function txSummaryLabel(
export function isDepositType(type: string): boolean {
const t = type.toUpperCase();
return (t.includes('DEPOSIT') || t === 'CASHBACK_DEPOSIT') && !isCashbackType(type);
return (t.includes('DEPOSIT') || t === 'CASHBACK_DEPOSIT') && !isCashbackType(type) && t !== 'PLAYER_DEPOSIT_REVERSAL';
}
export function isDepositReversalType(type: string): boolean {
return type.toUpperCase() === 'PLAYER_DEPOSIT_REVERSAL';
}
export function txRemarkLabel(
tx: { transactionType: string; remark?: string | null; referenceId?: string | null },
t: (key: string, params?: Record<string, unknown>) => string,
): string {
const type = tx.transactionType.toUpperCase();
const remark = tx.remark?.trim() ?? '';
if (type === 'PLAYER_DEPOSIT_REVERSAL') {
return t('wallet.remark_deposit_revoke_generic');
}
return remark;
}
export function isWithdrawType(type: string): boolean {
return type.toUpperCase().includes('WITHDRAW');
const t = type.toUpperCase();
if (t === 'PLAYER_DEPOSIT_REVERSAL') return false;
return t.includes('WITHDRAW');
}
export function isBetType(type: string): boolean {

View File

@@ -8,6 +8,8 @@ import GoldSpinner from '../components/GoldSpinner.vue';
import { usePullToRefresh } from '../composables/usePullToRefresh';
import { useOnLocaleChange } from '../composables/useOnLocaleChange';
import { parseCashbackApiData, type CashbackRecord } from '../utils/cashback';
const route = useRoute();
const router = useRouter();
const { t, locale } = useI18n();
@@ -17,19 +19,6 @@ const highlightBatchNo = computed(() => {
return typeof q === 'string' ? q.trim() : '';
});
type CashbackRecord = {
id: string;
batchNo: string;
periodStart: string;
periodEnd: string;
confirmedAt: string | null;
effectiveStake: string;
betCount: number;
rate: string;
amount: string;
createdAt: string;
};
const items = ref<CashbackRecord[]>([]);
const loading = ref(false);
const initialLoading = ref(true);
@@ -72,8 +61,7 @@ async function fetchRecords(p = 1) {
loading.value = true;
try {
const { data } = await api.get('/player/cashbacks', { params: { page: p } });
const result = data.data ?? { items: [], total: 0, pageSize: 20 };
const newItems = result.items ?? [];
const newItems = parseCashbackApiData(data.data);
if (p === 1) {
items.value = newItems;
@@ -81,7 +69,7 @@ async function fetchRecords(p = 1) {
items.value = [...items.value, ...newItems];
}
const pageSize = result.pageSize ?? 20;
const pageSize = 20;
hasMore.value = newItems.length >= pageSize;
page.value = p;
} catch {

View File

@@ -68,7 +68,10 @@ const filterNow = ref(new Date());
const { summaryMatches, summaryLoading, loadSummary } = usePlayerMatches();
const matches = summaryMatches;
const loading = summaryLoading;
const expandedLeagues = ref<Set<string>>(new Set());
const expandedLeagues = ref<Record<TimeTab, Set<string>>>({
today: new Set(),
early: new Set(),
});
async function loadMatches() {
filterNow.value = new Date();
@@ -86,23 +89,23 @@ const pullIndicatorStyle = () => ({
opacity: Math.min(pullDistance.value / 48, 1),
});
const filteredMatches = computed(() => {
function filterMatchesForTab(tab: TimeTab) {
if (mainTab.value !== 'matches') return [];
const now = filterNow.value;
return matches.value.filter((m) => {
const timeMatch =
timeTab.value === 'today'
tab === 'today'
? isInTodayMatchWindow(m.startTime, now)
: isAfterTodayMatchWindow(m.startTime, now);
if (!timeMatch) return false;
if (!showAll.value && m.matchPhase !== 'open' && m.matchPhase !== undefined) return false;
return true;
});
});
}
const leagueGroups = computed<LeagueGroup[]>(() => {
function buildLeagueGroups(source: Match[]): LeagueGroup[] {
const map = new Map<string, LeagueGroup>();
for (const m of filteredMatches.value) {
for (const m of source) {
const id = m.leagueId ?? m.leagueName;
if (!map.has(id)) {
map.set(id, {
@@ -127,29 +130,34 @@ const leagueGroups = computed<LeagueGroup[]>(() => {
(a.matches[0]?.displayOrder ?? 0) - (b.matches[0]?.displayOrder ?? 0) ||
a.leagueName.localeCompare(b.leagueName),
);
});
}
watch(leagueGroups, (groups) => {
const ids = new Set(expandedLeagues.value);
const todayLeagueGroups = computed(() => buildLeagueGroups(filterMatchesForTab('today')));
const earlyLeagueGroups = computed(() => buildLeagueGroups(filterMatchesForTab('early')));
function syncExpandedLeagues(groups: LeagueGroup[], tab: TimeTab) {
const current = expandedLeagues.value[tab];
const ids = new Set(current);
for (const id of [...ids]) {
if (!groups.some((g) => g.leagueId === id)) ids.delete(id);
}
if (ids.size !== expandedLeagues.value.size) expandedLeagues.value = ids;
// 默认只展开第一个联赛,减少首屏 DOM
if (groups.length > 0 && expandedLeagues.value.size === 0) {
expandedLeagues.value = new Set([groups[0].leagueId]);
if (groups.length > 0 && ids.size === 0) {
ids.add(groups[0].leagueId);
}
if (ids.size !== current.size || [...ids].some((id) => !current.has(id))) {
expandedLeagues.value = { ...expandedLeagues.value, [tab]: ids };
}
});
function isLeagueExpanded(leagueId: string) {
return expandedLeagues.value.has(leagueId);
}
watch(todayLeagueGroups, (groups) => syncExpandedLeagues(groups, 'today'));
watch(earlyLeagueGroups, (groups) => syncExpandedLeagues(groups, 'early'));
function toggleLeague(leagueId: string) {
const next = new Set(expandedLeagues.value);
const tab = timeTab.value;
const next = new Set(expandedLeagues.value[tab]);
if (next.has(leagueId)) next.delete(leagueId);
else next.add(leagueId);
expandedLeagues.value = next;
expandedLeagues.value = { ...expandedLeagues.value, [tab]: next };
}
function selectMainTab(tab: MainTab) {
@@ -232,26 +240,49 @@ function goMatch(id: string) {
<div v-if="loading" class="state">
<GoldSpinner :size="36" />
</div>
<div v-else-if="leagueGroups.length" class="league-list">
<template v-else>
<div v-show="timeTab === 'today'">
<div v-if="todayLeagueGroups.length" class="league-list">
<LeagueAccordionItem
v-for="group in leagueGroups"
:key="group.leagueId"
v-for="group in todayLeagueGroups"
:key="`today-${group.leagueId}`"
:league-id="group.leagueId"
:league-name="group.leagueName"
:league-logo-url="group.leagueLogoUrl"
:matches="group.matches"
:expanded="isLeagueExpanded(group.leagueId)"
:expanded="expandedLeagues.today.has(group.leagueId)"
@toggle="toggleLeague(group.leagueId)"
@bet="goMatch"
/>
</div>
<div v-else class="empty">
<img :src="emptyMatchesImg" alt="" class="empty-icon" />
<p>{{ t('bet.no_matches') }}</p>
</div>
</div>
<div v-show="timeTab === 'early'">
<div v-if="earlyLeagueGroups.length" class="league-list">
<LeagueAccordionItem
v-for="group in earlyLeagueGroups"
:key="`early-${group.leagueId}`"
:league-id="group.leagueId"
:league-name="group.leagueName"
:league-logo-url="group.leagueLogoUrl"
:matches="group.matches"
:expanded="expandedLeagues.early.has(group.leagueId)"
@toggle="toggleLeague(group.leagueId)"
@bet="goMatch"
/>
</div>
<div v-else class="empty">
<img :src="emptyMatchesImg" alt="" class="empty-icon" />
<p>{{ t('bet.no_matches') }}</p>
</div>
</div>
</template>
</div>
<OutrightPanel v-if="mainTab === 'outright'" class="outright-tab" />
</div>

View File

@@ -1,5 +1,5 @@
<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { ref, onMounted, onActivated, computed } from 'vue';
import { useRouter, RouterLink } from 'vue-router';
import { useI18n } from 'vue-i18n';
import api from '../api';
@@ -7,19 +7,17 @@ import { formatMoney } from '../utils/localeDisplay';
import LocaleFlag from '../components/LocaleFlag.vue';
import { useAuthStore } from '../stores/auth';
import { useAppLocale } from '../composables/useAppLocale';
import { usePlayerProfile } from '../composables/usePlayerProfile';
import GoldSpinner from '../components/GoldSpinner.vue';
import { usePullToRefresh } from '../composables/usePullToRefresh';
import { parseCashbackApiData, sumCashbackAmount } from '../utils/cashback';
import walletBg from '../assets/images/wallet-bg.webp';
const { t, locale } = useI18n();
const router = useRouter();
const auth = useAuthStore();
const { locales, setLocale, initFromUser } = useAppLocale();
const profile = ref<{
username?: string;
wallet?: { availableBalance: string; frozenBalance: string };
} | null>(null);
const { profileRaw, refreshProfile } = usePlayerProfile();
const loading = ref(true);
const error = ref(false);
@@ -33,10 +31,8 @@ async function fetchProfile() {
loading.value = true;
error.value = false;
try {
const { data } = await api.get('/player/profile');
profile.value = data.data;
initFromUser(data.data?.locale);
// Fetch cashback total in parallel
await refreshProfile();
initFromUser(profileRaw.value?.locale);
void fetchCashbackTotal();
} catch {
error.value = true;
@@ -46,6 +42,11 @@ async function fetchProfile() {
}
async function fetchCashbackTotal() {
try {
const { data } = await api.get('/player/cashbacks');
cashbackTotal.value = sumCashbackAmount(parseCashbackApiData(data.data)).toString();
} catch {
// Fallback: sum wallet cashback credits when batch detail API is unavailable.
try {
const { data } = await api.get('/player/wallet/transactions/stats');
const byType = data.data?.byType ?? [];
@@ -57,7 +58,8 @@ async function fetchCashbackTotal() {
}
cashbackTotal.value = sum.toString();
} catch {
// Ignore errors, keep default value
// Keep default value
}
}
}
@@ -65,6 +67,10 @@ onMounted(() => {
void fetchProfile();
});
onActivated(() => {
void fetchProfile();
});
const { pullDistance, refreshing, spinning, progress } = usePullToRefresh({
onRefresh: async () => { await fetchProfile(); },
});
@@ -84,7 +90,7 @@ function logout() {
}
const balanceDisplay = computed(() =>
formatMoney(profile.value?.wallet?.availableBalance, locale.value),
formatMoney(profileRaw.value?.wallet?.availableBalance, locale.value),
);
const balanceAmountClass = computed(() => {
@@ -143,7 +149,7 @@ const balanceAmountClass = computed(() => {
<div class="bank-card-footer">
<div class="bank-card-field">
<span class="bank-card-label">持卡人</span>
<span class="bank-card-holder">{{ profile?.username }}</span>
<span class="bank-card-holder">{{ profileRaw?.username }}</span>
</div>
<div class="bank-card-field bank-card-field--center">
<span class="bank-card-label">累计返水</span>
@@ -151,7 +157,7 @@ const balanceAmountClass = computed(() => {
</div>
<div class="bank-card-field bank-card-field--right">
<span class="bank-card-label">未结算</span>
<span class="bank-card-stat">{{ formatMoney(profile?.wallet?.frozenBalance, locale) }}</span>
<span class="bank-card-stat">{{ formatMoney(profileRaw?.wallet?.frozenBalance, locale) }}</span>
</div>
</div>
</div>

View File

@@ -6,13 +6,32 @@ import api from '../api';
import GoldSpinner from '../components/GoldSpinner.vue';
import { usePullToRefresh } from '../composables/usePullToRefresh';
import { formatMoney } from '../utils/localeDisplay';
import {
auditActionTone,
auditActorSecondary,
formatDepositAuditRemark,
shouldShowAuditRejectInTimeline,
} from '../utils/depositAuditDisplay';
const router = useRouter();
const { t, locale } = useI18n();
interface DepositAuditLog {
id: string;
action: string;
actorType: string;
statusBefore: string | null;
statusAfter: string;
amount: string | null;
approvedAmount: string | null;
remark: string | null;
createdAt: string;
}
interface DepositOrder {
id: string;
orderNo: string;
paymentMethodId?: string;
methodType: string;
amount: string;
status: string;
@@ -22,6 +41,7 @@ interface DepositOrder {
createdAt: string;
reviewedAt: string | null;
paymentMethodName: string | null;
auditLogs?: DepositAuditLog[];
}
const items = ref<DepositOrder[]>([]);
@@ -34,6 +54,8 @@ const hasMore = ref(true);
const sentinel = ref<HTMLElement | null>(null);
let observer: IntersectionObserver | null = null;
const selectedOrder = ref<DepositOrder | null>(null);
async function fetchOrders(p = 1) {
if (loading.value) return;
loading.value = true;
@@ -99,7 +121,107 @@ function goRecharge() {
router.push('/wallet/recharge');
}
onMounted(fetchOrders);
function openDetail(order: DepositOrder) {
selectedOrder.value = order;
}
function closeDetail() {
selectedOrder.value = null;
}
function reapply(order: DepositOrder) {
const query: Record<string, string> = {
orderId: order.id,
methodType: order.methodType,
amount: order.amount,
};
if (order.paymentMethodId) {
query.methodId = order.paymentMethodId;
}
router.push({ path: '/wallet/recharge', query });
}
function normalizeText(value: string | null | undefined) {
return value?.trim() ?? '';
}
/** Backend sets remark = rejectReason on reject; show one line only. */
function orderNote(order: DepositOrder): { label: string; text: string } | null {
const rejectReason = normalizeText(order.rejectReason);
const remark = normalizeText(order.remark);
if (order.status === 'REJECTED') {
const text = rejectReason || remark;
if (!text) return null;
return { label: t('recharge.reject_reason'), text };
}
if (remark) {
return { label: t('recharge.remark'), text: remark };
}
return null;
}
function orderNoteLine(order: DepositOrder) {
const note = orderNote(order);
return note ? `${note.label}: ${note.text}` : null;
}
function auditActionLabel(action: string) {
const key = `recharge.audit_${action.toLowerCase()}` as const;
const translated = t(key);
return translated !== key ? translated : action;
}
function auditStepClass(action: string) {
return `audit-step--${auditActionTone(action)}`;
}
function formatAuditTime(iso: string) {
return new Date(iso).toLocaleString(undefined, {
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
});
}
function formatOrderTime(iso: string) {
return new Date(iso).toLocaleString();
}
function auditRemarkForTimeline(log: DepositAuditLog, order: DepositOrder) {
if (log.action === 'REJECTED' && !shouldShowAuditRejectInTimeline(log, order.rejectReason)) {
return null;
}
return formatDepositAuditRemark(log, t);
}
function auditLogsForDisplay(order: DepositOrder) {
return [...(order.auditLogs ?? [])]
.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())
.map((log) => ({
log,
actor: auditActorSecondary(log, t),
remark: auditRemarkForTimeline(log, order),
}));
}
function auditNoteLine(text: string) {
return `${t('recharge.audit_remark_label')}: ${text}`;
}
function auditNoteDisplayText(remark: { kind: 'note'; text: string }) {
if (remark.text === t('wallet.remark_deposit_revoke_generic')) {
return remark.text;
}
return auditNoteLine(remark.text);
}
function auditStepCount(order: DepositOrder) {
return order.auditLogs?.length ?? 0;
}
</script>
<template>
@@ -117,7 +239,7 @@ onMounted(fetchOrders);
<GoldSpinner v-if="spinning" :size="28" :progress="progress" :active="spinning" />
</div>
<div v-if="loading" class="state">
<div v-if="initialLoading && loading" class="state">
<GoldSpinner :size="36" />
</div>
@@ -125,7 +247,16 @@ onMounted(fetchOrders);
<div v-if="!items.length" class="empty">{{ t('recharge.no_orders') }}</div>
<div v-else class="order-list">
<div v-for="order in items" :key="order.id" class="order-card" :class="{ rejected: order.status === 'REJECTED' }">
<div
v-for="order in items"
:key="order.id"
class="order-card"
:class="{ rejected: order.status === 'REJECTED' }"
role="button"
tabindex="0"
@click="openDetail(order)"
@keydown.enter="openDetail(order)"
>
<div class="order-header">
<span class="method-badge" :class="order.methodType === 'BANK' ? 'bank' : 'usdt'">{{ order.methodType }}</span>
<span :class="['status-badge', statusClass(order.status)]">{{ statusLabel(order.status) }}</span>
@@ -141,19 +272,33 @@ onMounted(fetchOrders);
<div class="order-times">
<div class="time-row">
<span class="time-label">{{ t('recharge.apply_time') }}</span>
<span class="time-value">{{ new Date(order.createdAt).toLocaleString() }}</span>
<span class="time-value">{{ formatOrderTime(order.createdAt) }}</span>
</div>
<div v-if="order.reviewedAt" class="time-row">
<span class="time-label">{{ t('recharge.review_time') }}</span>
<span class="time-value">{{ new Date(order.reviewedAt).toLocaleString() }}</span>
<span class="time-value">{{ formatOrderTime(order.reviewedAt) }}</span>
</div>
</div>
<div v-if="order.remark" class="order-remark">
{{ t('recharge.remark') }}: {{ order.remark }}
<div
v-if="orderNoteLine(order)"
:class="order.status === 'REJECTED' ? 'reject-reason' : 'order-remark'"
>
{{ orderNoteLine(order) }}
</div>
<div v-if="order.status === 'REJECTED' && order.rejectReason" class="reject-reason">
{{ t('recharge.reject_reason') }}: {{ order.rejectReason }}
<div v-if="auditStepCount(order)" class="card-detail-hint">
<span class="card-detail-summary">
{{ t('recharge.audit_summary', { count: auditStepCount(order) }) }}
</span>
<span class="card-detail-link">{{ t('recharge.view_detail') }} </span>
</div>
<button
v-else
type="button"
class="card-detail-link-only"
@click.stop="openDetail(order)"
>
{{ t('recharge.view_detail') }}
</button>
</div>
</div>
</div>
@@ -168,6 +313,98 @@ onMounted(fetchOrders);
{{ t('common.no_more') }}
</div>
</template>
<Teleport to="body">
<div v-if="selectedOrder" class="detail-overlay" @click.self="closeDetail">
<div class="detail-modal" role="dialog" aria-modal="true" :aria-label="t('recharge.order_detail')">
<button type="button" class="detail-close" :aria-label="t('common.close')" @click="closeDetail"></button>
<h3 class="detail-title">{{ t('recharge.order_detail') }}</h3>
<div class="detail-summary">
<div class="detail-summary-head">
<span class="method-badge" :class="selectedOrder.methodType === 'BANK' ? 'bank' : 'usdt'">
{{ selectedOrder.methodType }}
</span>
<span :class="['status-badge', statusClass(selectedOrder.status)]">
{{ statusLabel(selectedOrder.status) }}
</span>
</div>
<div class="detail-amount">{{ formatMoney(selectedOrder.amount, locale) }}</div>
<div
v-if="selectedOrder.approvedAmount && selectedOrder.approvedAmount !== selectedOrder.amount"
class="approved-amount"
>
{{ t('recharge.credited') }}: {{ formatMoney(selectedOrder.approvedAmount, locale) }}
</div>
<div class="detail-method-name">{{ selectedOrder.paymentMethodName || '-' }}</div>
<div class="detail-row">
<span class="detail-label">{{ t('recharge.apply_time') }}</span>
<span class="detail-value">{{ formatOrderTime(selectedOrder.createdAt) }}</span>
</div>
<div v-if="selectedOrder.reviewedAt" class="detail-row">
<span class="detail-label">{{ t('recharge.review_time') }}</span>
<span class="detail-value">{{ formatOrderTime(selectedOrder.reviewedAt) }}</span>
</div>
<div
v-if="orderNoteLine(selectedOrder)"
:class="selectedOrder.status === 'REJECTED' ? 'reject-reason' : 'order-remark'"
>
{{ orderNoteLine(selectedOrder) }}
</div>
</div>
<div v-if="selectedOrder.auditLogs?.length" class="detail-audit">
<h4 class="detail-audit-title">{{ t('recharge.audit_title') }}</h4>
<div class="audit-track">
<div
v-for="(entry, logIdx) in auditLogsForDisplay(selectedOrder)"
:key="entry.log.id"
class="audit-step"
:class="auditStepClass(entry.log.action)"
>
<div class="audit-step-rail" aria-hidden="true">
<span class="audit-dot" />
<span v-if="logIdx < auditLogsForDisplay(selectedOrder).length - 1" class="audit-line" />
</div>
<div class="audit-step-body">
<div class="audit-step-head">
<span class="audit-step-title">{{ auditActionLabel(entry.log.action) }}</span>
<time class="audit-step-time">{{ formatAuditTime(entry.log.createdAt) }}</time>
</div>
<p v-if="entry.actor" class="audit-step-actor">{{ entry.actor }}</p>
<p
v-if="entry.log.approvedAmount && entry.log.action === 'APPROVED'"
class="audit-step-credited"
>
{{ t('recharge.audit_credited') }} {{ formatMoney(entry.log.approvedAmount, locale) }}
</p>
<div
v-if="entry.remark?.kind === 'reject'"
class="audit-step-box audit-step-box--reject"
>
<span class="audit-step-box-label">{{ t('recharge.reject_reason') }}</span>
<span class="audit-step-box-text">{{ entry.remark.text }}</span>
</div>
<p v-else-if="entry.remark?.kind === 'note'" class="audit-step-note">
{{ auditNoteDisplayText(entry.remark) }}
</p>
</div>
</div>
</div>
</div>
<button
v-if="selectedOrder.status === 'REJECTED'"
type="button"
class="modal-reapply-btn btn-gold-outline"
@click.stop="reapply(selectedOrder)"
>
{{ t('recharge.reapply') }}
</button>
</div>
</div>
</Teleport>
</div>
</template>
@@ -189,6 +426,11 @@ onMounted(fetchOrders);
padding: 16px;
position: relative;
overflow: hidden;
cursor: pointer;
-webkit-tap-highlight-color: transparent;
}
.order-card:active {
opacity: 0.92;
}
.order-card::before {
content: '';
@@ -198,21 +440,20 @@ onMounted(fetchOrders);
background: linear-gradient(90deg, transparent, rgba(212, 175, 55, 0.6), transparent);
}
.order-card.rejected {
background: linear-gradient(135deg, #1a1a1a 0%, #1f1f1f 40%, #161616 100%);
border-color: rgba(100, 100, 100, 0.2);
opacity: 0.7;
background: #141414;
border-color: rgba(245, 108, 108, 0.22);
}
.order-card.rejected::before {
background: linear-gradient(90deg, transparent, rgba(100, 100, 100, 0.4), transparent);
background: linear-gradient(90deg, transparent, rgba(245, 108, 108, 0.35), transparent);
}
.order-card.rejected .order-amount {
background: linear-gradient(135deg, #888, #666);
-webkit-background-clip: text;
background-clip: text;
color: transparent;
background: none;
-webkit-background-clip: unset;
background-clip: unset;
color: #bbb;
}
.order-card.rejected .info-label {
color: rgba(150, 150, 150, 0.7);
color: #888;
}
.order-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px; }
.method-badge { padding: 2px 8px; border-radius: 10px; font-size: 11px; font-weight: 700; }
@@ -247,8 +488,54 @@ onMounted(fetchOrders);
border-radius: 6px;
margin-top: 6px;
border-left: 2px solid rgba(212, 175, 55, 0.3);
line-height: 1.45;
word-break: break-word;
}
.reject-reason {
margin-top: 8px;
font-size: 12px;
color: #c07070;
background: transparent;
padding: 6px 0 0;
border-radius: 0;
border: none;
border-top: 1px solid rgba(245, 108, 108, 0.18);
line-height: 1.45;
word-break: break-word;
}
.card-detail-hint {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
margin-top: 10px;
padding-top: 10px;
border-top: 1px solid rgba(212, 175, 55, 0.12);
}
.card-detail-summary {
font-size: 11px;
color: rgba(212, 175, 55, 0.65);
font-weight: 600;
}
.card-detail-link {
font-size: 11px;
color: var(--primary-light);
font-weight: 700;
white-space: nowrap;
}
.card-detail-link-only {
display: block;
width: 100%;
margin-top: 10px;
padding: 0;
border: none;
background: none;
text-align: right;
font-size: 11px;
color: var(--primary-light);
font-weight: 700;
cursor: pointer;
}
.reject-reason { margin-top: 8px; font-size: 12px; color: #f56c6c; background: #2a1515; padding: 6px 10px; border-radius: 6px; }
.sentinel {
height: 1px;
@@ -268,4 +555,291 @@ onMounted(fetchOrders);
padding: 16px 0 4px;
letter-spacing: 0.03em;
}
.detail-overlay {
position: fixed;
inset: 0;
z-index: 200;
background: rgba(0, 0, 0, 0.48);
display: flex;
align-items: flex-end;
justify-content: center;
padding: 0;
}
.detail-modal {
position: relative;
width: 100%;
max-width: 480px;
max-height: min(88vh, 720px);
overflow-y: auto;
background: #141414;
border: 1px solid #2a2a2a;
border-bottom: none;
border-radius: 14px 14px 0 0;
padding: 16px 16px calc(14px + env(safe-area-inset-bottom, 0px));
box-shadow: 0 -4px 24px rgba(0, 0, 0, 0.28);
}
.detail-close {
position: absolute;
top: 12px;
right: 12px;
width: 28px;
height: 28px;
border: none;
border-radius: 50%;
background: transparent;
color: #777;
font-size: 13px;
cursor: pointer;
line-height: 1;
}
.detail-title {
margin: 0 28px 12px 0;
font-size: 15px;
font-weight: 600;
color: #e8e8e8;
}
.detail-summary {
margin-bottom: 14px;
padding: 12px;
border-radius: 10px;
background: rgba(255, 255, 255, 0.02);
border: 1px solid #222;
}
.detail-summary-head {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 10px;
}
.detail-amount {
font-size: 22px;
font-weight: 700;
margin-bottom: 4px;
color: var(--primary-light, #d4af37);
letter-spacing: -0.02em;
}
.detail-method-name {
font-size: 12px;
color: #999;
font-weight: 500;
margin-bottom: 8px;
}
.detail-row {
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: 12px;
margin-bottom: 6px;
}
.detail-label {
font-size: 12px;
color: #888;
flex-shrink: 0;
}
.detail-value {
font-size: 12px;
color: #ccc;
text-align: right;
word-break: break-word;
}
.detail-summary .order-remark {
margin-top: 8px;
font-size: 11px;
color: #999;
background: transparent;
padding: 6px 0 0;
border-radius: 0;
border: none;
border-top: 1px solid #222;
line-height: 1.45;
word-break: break-word;
}
.detail-summary .reject-reason {
margin-top: 8px;
font-size: 11px;
color: #b08888;
background: transparent;
padding: 6px 0 0;
border-radius: 0;
border: none;
border-top: 1px solid rgba(245, 108, 108, 0.15);
line-height: 1.45;
word-break: break-word;
}
.detail-summary .approved-amount {
font-size: 11px;
font-weight: 500;
}
.detail-audit {
margin-top: 2px;
padding-top: 12px;
border-top: 1px solid #222;
}
.detail-audit-title {
margin: 0 0 10px;
font-size: 12px;
font-weight: 600;
color: #888;
letter-spacing: 0.02em;
}
.audit-track {
display: flex;
flex-direction: column;
gap: 0;
}
.audit-step {
display: flex;
gap: 8px;
min-height: 0;
}
.audit-step-rail {
flex: 0 0 10px;
display: flex;
flex-direction: column;
align-items: center;
padding-top: 4px;
}
.audit-dot {
width: 5px;
height: 5px;
border-radius: 50%;
background: #555;
flex-shrink: 0;
}
.audit-line {
flex: 1;
width: 1px;
min-height: 10px;
margin: 3px 0;
background: #2a2a2a;
}
.audit-step-body {
flex: 1;
min-width: 0;
padding-bottom: 12px;
}
.audit-step:last-child .audit-step-body {
padding-bottom: 0;
}
.audit-step-head {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 8px;
}
.audit-step-title {
font-size: 12px;
font-weight: 600;
color: #ccc;
line-height: 1.35;
}
.audit-step-time {
font-size: 10px;
color: #666;
font-variant-numeric: tabular-nums;
white-space: nowrap;
flex-shrink: 0;
}
.audit-step-actor {
margin: 2px 0 0;
font-size: 11px;
color: #999;
line-height: 1.4;
}
.audit-step-credited {
margin: 3px 0 0;
font-size: 11px;
font-weight: 500;
color: #7eb87a;
line-height: 1.4;
}
.audit-step-note {
margin: 4px 0 0;
font-size: 11px;
color: #888;
line-height: 1.45;
word-break: break-word;
}
.audit-step-box {
margin-top: 4px;
padding: 6px 8px;
border-radius: 6px;
display: flex;
flex-direction: column;
gap: 1px;
line-height: 1.4;
word-break: break-word;
}
.audit-step-box--reject {
background: transparent;
border: 1px solid rgba(245, 108, 108, 0.22);
}
.audit-step-box-label {
font-size: 10px;
font-weight: 500;
color: #c07070;
letter-spacing: 0.01em;
}
.audit-step-box-text {
font-size: 11px;
color: #b08888;
}
.audit-step--submitted .audit-dot {
background: #c9a227;
}
.audit-step--approved .audit-dot {
background: #5fad5a;
}
.audit-step--rejected .audit-dot {
background: #d06060;
}
.audit-step--revoked .audit-dot {
background: #777;
}
.audit-step--reopened .audit-dot {
background: #c9a227;
}
.modal-reapply-btn {
width: 100%;
margin-top: 14px;
padding: 11px 16px;
font-size: 13px;
font-weight: 600;
cursor: pointer;
}
</style>

View File

@@ -1,14 +1,21 @@
<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { useRouter, useRoute } from 'vue-router';
import { useI18n } from 'vue-i18n';
import imageCompression from 'browser-image-compression';
import api from '../api';
import GoldSpinner from '../components/GoldSpinner.vue';
const router = useRouter();
const route = useRoute();
const { t } = useI18n();
const reapplyOrderId = computed(() => {
const id = route.query.orderId;
return typeof id === 'string' && id ? id : '';
});
const isReapply = computed(() => !!reapplyOrderId.value);
interface PaymentMethod {
id: string;
methodType: string;
@@ -36,13 +43,39 @@ const bankMethods = computed(() => methods.value.filter((m) => m.methodType ===
const usdtMethods = computed(() => methods.value.filter((m) => m.methodType === 'USDT'));
const currentMethods = computed(() => methodType.value === 'BANK' ? bankMethods.value : usdtMethods.value);
function applyReapplyQuery() {
const type = route.query.methodType;
if (type === 'BANK' || type === 'USDT') {
methodType.value = type;
}
const methodId = typeof route.query.methodId === 'string' ? route.query.methodId : '';
if (methodId) {
const match = methods.value.find((m) => m.id === methodId);
if (match) {
selectedMethod.value = match;
}
}
if (!selectedMethod.value && currentMethods.value.length) {
selectedMethod.value = currentMethods.value[0];
}
const amountQuery = typeof route.query.amount === 'string' ? route.query.amount : '';
const parsedAmount = parseFloat(amountQuery);
if (amountQuery && parsedAmount > 0) {
amount.value = amountQuery;
}
}
async function fetchMethods() {
loading.value = true;
try {
const { data } = await api.get('/player/payment-methods');
methods.value = (data.data ?? []).map((m: any) => ({ ...m, id: String(m.id) }));
// Auto-select first available
if (currentMethods.value.length) {
if (isReapply.value) {
applyReapplyQuery();
} else if (currentMethods.value.length) {
selectedMethod.value = currentMethods.value[0];
}
} catch { /* */ } finally {
@@ -145,10 +178,19 @@ async function handleSubmit() {
submitting.value = true;
try {
const fd = new FormData();
fd.append('paymentMethodId', selectedMethod.value.id);
fd.append('amount', String(amt));
fd.append('screenshot', screenshotFile.value);
if (isReapply.value) {
fd.append('paymentMethodId', selectedMethod.value.id);
const { data } = await api.post(`/player/deposit-orders/${reapplyOrderId.value}/reapply`, fd);
const result = data.data;
orderNo.value = result?.orderNo ?? '';
success.value = true;
return;
}
fd.append('paymentMethodId', selectedMethod.value.id);
const { data } = await api.post('/player/deposit-orders', fd);
const result = data.data;
orderNo.value = result?.orderNo ?? '';
@@ -206,10 +248,12 @@ onMounted(fetchMethods);
<h3>{{ t('recharge.submitted') }}</h3>
<p class="order-no">{{ orderNo }}</p>
<p class="success-hint">{{ t('recharge.pending_review') }}</p>
<button class="btn-primary" @click="resetForm">{{ t('recharge.new_recharge') }}</button>
<button v-if="isReapply" class="btn-primary" @click="goHistory">{{ t('recharge.back_to_history') }}</button>
<button v-else class="btn-primary" @click="resetForm">{{ t('recharge.new_recharge') }}</button>
</div>
<template v-else>
<div v-if="isReapply" class="reapply-banner">{{ t('recharge.reapply_hint') }}</div>
<div class="type-tabs">
<button
:class="['tab', methodType === 'BANK' && 'active']"
@@ -330,6 +374,17 @@ onMounted(fetchMethods);
.state { display: flex; justify-content: center; padding: 48px; }
.reapply-banner {
margin-bottom: 12px;
padding: 10px 12px;
border-radius: 8px;
font-size: 12px;
line-height: 1.45;
color: #ffd0d0;
background: rgba(245, 108, 108, 0.12);
border: 1px solid rgba(245, 108, 108, 0.25);
}
.type-tabs {
display: flex; margin-bottom: 12px;
border-radius: 6px; overflow: hidden;

View File

@@ -4,7 +4,7 @@ import { useRoute, useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import api from '../api';
import { formatMoney } from '../utils/localeDisplay';
import { txTypeKey, isCashbackType, txDisplayType, txSummaryLabel } from '../utils/walletTx';
import { txTypeKey, isCashbackType, txDisplayType, txSummaryLabel, txRemarkLabel, isDepositReversalType } from '../utils/walletTx';
import GoldSpinner from '../components/GoldSpinner.vue';
import { usePullToRefresh } from '../composables/usePullToRefresh';
@@ -108,6 +108,7 @@ const cashbackBatchNo = computed(() => {
const referenceLabel = computed(() => {
if (isCashbackTx.value) return t('wallet.ref_cashback');
if (!tx.value?.referenceType) return '';
if (isDepositReversalType(tx.value.transactionType)) return t('wallet.ref_deposit');
const rt = tx.value.referenceType.toUpperCase();
if (rt === 'BET') return t('wallet.ref_bet');
if (rt === 'DEPOSIT') return t('wallet.ref_deposit');
@@ -115,6 +116,11 @@ const referenceLabel = computed(() => {
return tx.value.referenceType;
});
const remarkText = computed(() => {
if (!tx.value) return '';
return txRemarkLabel(tx.value, t);
});
function goBetDetail() {
if (!tx.value?.betNo) return;
router.push(`/bets/${tx.value.betNo}`);
@@ -180,7 +186,7 @@ function goCashbackDetail() {
</div>
</section>
<section v-if="tx.referenceType || tx.remark" class="section">
<section v-if="tx.referenceType || remarkText" class="section">
<div class="section-title">{{ t('wallet.detail_reference') }}</div>
<div class="summary-rows">
<div v-if="tx.referenceType" class="sum-row">
@@ -191,9 +197,9 @@ function goCashbackDetail() {
<span>{{ t('wallet.detail_reference_id') }}</span>
<span class="mono">{{ tx.referenceId }}</span>
</div>
<div v-if="tx.remark" class="sum-row">
<div v-if="remarkText" class="sum-row">
<span>{{ t('wallet.detail_remark') }}</span>
<span class="remark">{{ tx.remark }}</span>
<span class="remark">{{ remarkText }}</span>
</div>
</div>
<button v-if="tx.betNo" type="button" class="bet-link" @click="goBetDetail">

View File

@@ -5,6 +5,7 @@ import { useI18n } from 'vue-i18n';
import api from '../api';
import { formatMoney, formatMoneyCompact } from '../utils/localeDisplay';
import { txTypeKey, txDisplayType, txSummaryLabel } from '../utils/walletTx';
import { parseCashbackApiData, sumCashbackAmount } from '../utils/cashback';
import GoldSpinner from '../components/GoldSpinner.vue';
import { usePullToRefresh } from '../composables/usePullToRefresh';
@@ -54,12 +55,12 @@ async function fetchData() {
try {
const [txRes, cbRes] = await Promise.all([
api.get('/player/wallet/transactions', { params: { page: 1 } }),
api.get('/player/cashbacks').catch(() => ({ data: { data: { items: [], totalAmount: '0' } } })),
api.get('/player/cashbacks').catch(() => ({ data: { data: [] } })),
]);
const result = txRes.data.data ?? { items: [] };
items.value = (result.items ?? []).slice(0, PREVIEW_COUNT);
const cbData = cbRes.data?.data;
cashbackTotal.value = cbData?.totalAmount ?? cbData?.items?.reduce((s: number, r: { amount: string }) => s + Math.abs(parseFloat(r.amount) || 0), 0)?.toString() ?? '0';
const cbRows = parseCashbackApiData(cbRes.data?.data);
cashbackTotal.value = sumCashbackAmount(cbRows).toString();
} catch {
/* ignore */
} finally {

View File

@@ -11,6 +11,8 @@
## MVP 验收清单18 项)
玩法与串关规则参考:[投注玩法说明.md](./投注玩法说明.md)。
- [ ] 玩家可登录、改密码、切换语言
- [ ] 代理可创建直属玩家
- [ ] 代理可给直属玩家上分/下分

430
docs/投注玩法说明.md Normal file
View File

@@ -0,0 +1,430 @@
# 投注玩法说明
本文档为 **Explanation说明**:集中描述 thebet365 第一版**足球赛前盘**的每种玩法如何下注、如何判赢。
派彩金额公式见 [结算与返水金额规则.md](./结算与返水金额规则.md);结算操作流程见 [settlement-and-fund-flow-analysis.md](./settlement-and-fund-flow-analysis.md)。
---
## 1. 范围与注单类型
### 1.1 产品范围v1
| 项 | 说明 |
|----|------|
| 运动 | 仅足球(`SPORT_TYPE_FOOTBALL` |
| 时段 | **赛前盘**:开球时间之前可下注(`isPreMatchKickoff` |
| 不含 | 滚球、Cash Out、改单、系统串关 |
与玩家端「我的 → 投注规则」文案一致(`apps/player/src/i18n/zh-CN.ts` `rules_p1``rules_p5`)。
### 1.2 注单类型
| 类型 | 枚举 | 说明 |
|------|------|------|
| 单关 | `SINGLE` | 1 个选项1 笔本金 |
| 串关 | `PARLAY` | 25 腿(`PARLAY_MIN_LEGS=2``PARLAY_MAX_LEGS=5`),赔率连乘 |
**数据模型**:库表为 `Bet`(注单)+ `BetSelection`(选项腿)。玩家端 Pinia store 名 `betSlip`,逻辑上等价于「投注单」。
### 1.3 API 入口
| 操作 | 路径 |
|------|------|
| 单关下注 | `POST /api/player/bets/single` |
| 串关下注 | `POST /api/player/bets/parlay` |
---
## 2. 玩法总览表
权威目录:`packages/shared/src/market-catalog.ts``FOOTBALL_MARKET_CATALOG`**共 18 种**足球盘口)。
| marketType | 中文名 | 时段 | 主要选项 | 默认线 | 单关 | 串关 | 串关序 | 结算分类 | 结算依据 | 默认 seed |
|------------|--------|------|----------|--------|------|------|--------|----------|----------|-----------|
| `FT_1X2` | 全场 1X2 | FT | HOME / DRAW / AWAY | — | ✓ | ✓ | 3 | SCORE | 全场比分 | ✓ |
| `FT_HANDICAP` | 全场让球 | FT | HOME / AWAY | -0.5 | ✓ | ✓ | 1 | HANDICAP | 全场比分 + 让球线 | ✓ |
| `FT_OVER_UNDER` | 全场大小 | FT | OVER / UNDER | 2.5 | ✓ | ✓ | 2 | TOTAL | 全场总进球 + 大小线 | ✓ |
| `FT_ODD_EVEN` | 全场单双 | FT | ODD / EVEN | — | ✓ | ✓ | 4 | ODD_EVEN | 全场总进球奇偶 | ✓ |
| `HT_1X2` | 半场 1X2 | HT | HOME / DRAW / AWAY | — | ✓ | ✓ | 7 | SCORE | 半场比分 | ✓ |
| `HT_HANDICAP` | 半场让球 | HT | HOME / AWAY | -0.5 | ✓ | ✓ | 5 | HANDICAP | 半场比分 + 让球线 | ✓ |
| `HT_OVER_UNDER` | 半场大小 | HT | OVER / UNDER | 1.5 | ✓ | ✓ | 6 | TOTAL | 半场总进球 + 大小线 | ✓ |
| `FT_CORRECT_SCORE` | 全场波胆 | FT | 见 §3.E | — | ✓ | ✗ | — | CORRECT_SCORE | 全场精确比分 | ✓ |
| `HT_CORRECT_SCORE` | 上半场波胆 | HT | 见 §3.E | — | ✓ | ✗ | — | CORRECT_SCORE | 半场精确比分 | ✗ |
| `SH_CORRECT_SCORE` | 下半场波胆 | SH | 见 §3.E | — | ✓ | ✗ | — | CORRECT_SCORE | 下半场比分FTHT | ✗ |
| `OUTRIGHT_WINNER` | 冠军 | OUTRIGHT | 球队 code | — | ✓ | ✗ | — | OUTRIGHT | 冠军球队 code | ✗* |
| `FT_TEAM_TOTAL_HOME` | 主队进球大小 | FT | OVER / UNDER | 1.5 | ✓ | ✓ | 8 | TOTAL | 主队全场进球 | ✓ |
| `FT_TEAM_TOTAL_AWAY` | 客队进球大小 | FT | OVER / UNDER | 1.5 | ✓ | ✓ | 9 | TOTAL | 客队全场进球 | ✓ |
| `HT_FT` | 半全场 | FT | 9 组合,见 §3.F | — | ✓ | ✓ | 10 | SCORE | 半场结果 + 全场结果 | ✓ |
| `FT_TOTAL_GOALS` | 总进球数 | FT | TG_0_1 … TG_7_PLUS | — | ✓ | ✓ | 11 | SCORE | 全场总进球区间 | ✓ |
| `FT_CORNERS_HANDICAP` | 全场角球让球 | FT | HOME / AWAY | -0.5 | ✓ | ✓ | 12 | MANUAL_STATS | 主客角球 + 让球线 | ✓ |
| `FT_CORNERS_OVER_UNDER` | 全场角球大小 | FT | OVER / UNDER | 8.5 | ✓ | ✓ | 13 | MANUAL_STATS | 角球总数 + 大小线 | ✓ |
| `FT_CARDS_OVER_UNDER` | 全场罚牌大小 | FT | OVER / UNDER | 3.5 | ✓ | ✓ | 14 | MANUAL_STATS | 罚牌总数 + 大小线 | ✓ |
\* `OUTRIGHT_WINNER` 不在常规赛事 seed 模板中,由世界杯 48 强等单独同步,见 [默认数据说明.md](./默认数据说明.md)。
**默认 seed 刻意不含**`HT_CORRECT_SCORE``SH_CORRECT_SCORE`(系统仍识别并可结算)。
---
## 3. 按类别详解
以下判赢逻辑对应 `apps/api/src/domains/settlement/domain/settlement-calculator.ts``settleSelection()`
腿级结果:`WIN` | `HALF_WIN` | `PUSH` | `HALF_LOSE` | `LOSE` | `VOID`
### 3.A 独赢盘1X2
**结算分类**`SCORE`
#### FT_1X2全场 1X2 / Full Time 1X2
| 项 | 内容 |
|----|------|
| 玩法说明 | 预测**全场 90 分钟**(含补时,不含加时/点球)结束时的赛果 |
| 选项 | `HOME` 主胜 · `DRAW` 和局 · `AWAY` 客胜 |
| 判赢 | 比较 `ftHome``ftAway`:主胜 / 和 / 客胜 |
| 示例 | 全场 2:1`HOME`**WIN**;选 `DRAW`**LOSE** |
| 串关 | 允许(`parlayOrder=3` |
| 快照字段 | 无盘口线 |
#### HT_1X2半场 1X2
| 项 | 内容 |
|----|------|
| 玩法说明 | 预测**上半场**结束时的赛果 |
| 选项 | `HOME` / `DRAW` / `AWAY` |
| 判赢 | 比较 `htHome``htAway` |
| 示例 | 半场 0:0、全场 1:0选半场 `DRAW`**WIN** |
| 串关 | 允许(`parlayOrder=7` |
---
### 3.B 让球盘(亚洲盘)
**结算分类**`HANDICAP`(角球盘为 `MANUAL_STATS`,算法同为让球)
**通用规则**
- 选项:`HOME`(主队受让/让球侧)/ `AWAY`(客队)
- 让球线存于 `BetSelection.handicapLine`(下注时快照)
- 主队视角:`adj = 本队进球 + handicapLine 对手进球`
- `adj > 0` → WIN`adj = 0` → PUSH`adj < 0` → LOSE
- 客队选项使用 **相反符号** 的让球线(代码内对客队取 `-line`
- 四分之一盘(`.25` / `.75`)可产生半赢半输,见 [§5](#5-四分之一盘25--75)
#### FT_HANDICAP全场让球
| 项 | 内容 |
|----|------|
| 默认线 | -0.5(表示主队让半球,即主队需净胜至少 1 球才全赢) |
| 统计 | `ftHome``ftAway` |
| 串关 | 允许;**禁止** `.25`/`.75` 线进入串关 |
**示例**(线 -0.5,选主队 `HOME`
| 比分 | 结果 |
|------|------|
| 2:1 | WIN2 + (-0.5) 1 = 0.5 > 0 |
| 1:1 | LOSE |
| 1:0 | WIN |
#### HT_HANDICAP半场让球
| 项 | 内容 |
|----|------|
| 默认线 | -0.5 |
| 统计 | `htHome``htAway` |
| 串关 | 允许(禁止四分之一线) |
#### FT_CORNERS_HANDICAP全场角球让球
| 项 | 内容 |
|----|------|
| 默认线 | -0.5 |
| 统计 | 管理员录入 `homeCorners``awayCorners`;缺失时结算报错 `SETTLEMENT_STAT_MISSING` |
| 判赢 | 与足球让球相同,但用角球数代替进球 |
| 串关 | 允许(禁止四分之一线) |
---
### 3.C 大小盘Over/Under
**结算分类**`TOTAL`(角球/罚牌为 `MANUAL_STATS`,算法同为大小)
**通用规则**
- 选项:`OVER`(大)/ `UNDER`(小)
- 大小线存于 `BetSelection.totalLine`
- 大球:`总进球 > line` → WIN`= line` → PUSH`< line` → LOSE
- 小球:相反
- 支持四分之一盘半赢半输;串关禁止 `.25`/`.75` 线
| marketType | 中文名 | 默认线 | 统计对象 |
|------------|--------|--------|----------|
| `FT_OVER_UNDER` | 全场大小 | 2.5 | `ftHome + ftAway` |
| `HT_OVER_UNDER` | 半场大小 | 1.5 | `htHome + htAway` |
| `FT_TEAM_TOTAL_HOME` | 主队进球大小 | 1.5 | `ftHome` |
| `FT_TEAM_TOTAL_AWAY` | 客队进球大小 | 1.5 | `ftAway` |
| `FT_CORNERS_OVER_UNDER` | 全场角球大小 | 8.5 | `homeCorners + awayCorners` |
| `FT_CARDS_OVER_UNDER` | 全场罚牌大小 | 3.5 | `homeCards + awayCards` |
**示例**`FT_OVER_UNDER` 线 2.5,选 `OVER`
| 比分 | 总进球 | 结果 |
|------|--------|------|
| 2:1 | 3 | WIN |
| 1:1 | 2 | LOSE |
| 2:0 | 2 | LOSE2 不大于 2.5 |
角球/罚牌盘:结算前须在管理端录入对应统计字段,否则无法确认结算。
---
### 3.D 单双Odd/Even
#### FT_ODD_EVEN全场单双
| 项 | 内容 |
|----|------|
| 选项 | `ODD` 单 · `EVEN` 双 |
| 判赢 | 全场总进球 `ftHome + ftAway` 为奇数或偶数 |
| 示例 | 0:0 → 总进球 0 → **双EVEN 赢)** |
| 串关 | 允许(`parlayOrder=4` |
---
### 3.E 波胆Correct Score— 仅单关
**结算分类**`CORRECT_SCORE`
**串关**:全部 `allowParlay: false`,不可进入串关。
| marketType | 比分来源 |
|------------|----------|
| `FT_CORRECT_SCORE` | 全场 `ftHome:ftAway` |
| `HT_CORRECT_SCORE` | 半场 `htHome:htAway` |
| `SH_CORRECT_SCORE` | 下半场 `(ftHomehtHome):(ftAwayhtAway)` |
**选项类型**
1. **精确比分**code 形如 `SCORE_2_1`(表示 2:1
2. **其它主胜** `OTHER_HOME`:主胜,且精确比分不在模板列表中
3. **其它和局** `OTHER_DRAW`:和局,且精确比分不在模板列表中
4. **其它客胜** `OTHER_AWAY`:客胜,且精确比分不在模板列表中
**模板列表**`market-catalog.ts`
- 全场:`FT_CORRECT_SCORE_TEMPLATE`28 项,含 3 个 OTHER_*
- 半场/下半场:`HT_CORRECT_SCORE_TEMPLATE`17 项)
**判赢逻辑**
-`SCORE_h_a`:实际比分完全相等 → WIN否则 LOSE
- 若实际比分在模板中有对应 `SCORE_*` 项,则 OTHER_* 选项 LOSE
- 若实际比分**不在**模板中,则按主胜/和/客胜归到对应 OTHER_* → WIN
**示例**(全场波胆,实际 4:2
- 模板含 `SCORE_4_2` → 选 `SCORE_4_2` **WIN**,选 `OTHER_HOME` **LOSE**
- 若模板不含 4:2 → 选 `OTHER_HOME` **WIN**(主队胜)
---
### 3.F 组合 / 区间
#### HT_FT半全场 / Half TimeFull Time
| 项 | 内容 |
|----|------|
| 玩法说明 | 同时预测**半场结果**与**全场结果** |
| 选项 code | `{半场}_{全场}`,各为 `HOME` / `DRAW` / `AWAY`,共 9 种 |
| 判赢 | 实际组合须与选项完全一致 |
| code | 含义 |
|------|------|
| `HOME_HOME` | 半场主胜 + 全场主胜 |
| `HOME_DRAW` | 半场主胜 + 全场和 |
| `HOME_AWAY` | 半场主胜 + 全场客胜 |
| `DRAW_HOME` | 半场和 + 全场主胜 |
| `DRAW_DRAW` | 半场和 + 全场和 |
| `DRAW_AWAY` | 半场和 + 全场客胜 |
| `AWAY_HOME` | 半场客胜 + 全场主胜 |
| `AWAY_DRAW` | 半场客胜 + 全场和 |
| `AWAY_AWAY` | 半场客胜 + 全场客胜 |
**示例**:半场 1:0、全场 1:1 → 半场 HOME、全场 DRAW → 选 `HOME_DRAW` **WIN**
#### FT_TOTAL_GOALS总进球数区间
| 选项 code | 区间 |
|-----------|------|
| `TG_0_1` | 01 球 |
| `TG_2_3` | 23 球 |
| `TG_4_6` | 46 球 |
| `TG_7_PLUS` | 7 球及以上 |
判赢:按全场 `ftHome + ftAway` 落入区间。
**示例**3:2 → 总进球 5 → 选 `TG_4_6` **WIN**
---
### 3.G 冠军Outright
#### OUTRIGHT_WINNER
| 项 | 内容 |
|----|------|
| 玩法说明 | 预测联赛/赛事**最终冠军**(如世界杯夺冠球队) |
| 选项 | 各参赛队 `selectionCode` = 球队 code`FRA``BRA` |
| 判赢 | `selectionCode === winnerTeamCode`(管理员指定冠军) |
| 串关 | **禁止** |
| 前置条件 | 联赛内常规赛事须全部 `SETTLED``CANCELLED` 后才可结算冠军盘 |
| 玩家入口 | `/bet` →「优胜冠军」→ `OutrightBetModal`**不走** BetSlip 串关) |
---
## 4. 串关规则
实现:`packages/shared/src/betting-rules.ts``canSelectForParlay`)、`apps/api/src/domains/betting/bets.service.ts``apps/player/src/stores/betSlip.ts`
| 规则 | 说明 |
|------|------|
| 腿数 | **25 腿** |
| 同场限制 | **每场比赛最多 1 项**(前端 `SAME_MATCH`;后端 `PARLAY_SAME_MATCH_FORBIDDEN` |
| 禁止玩法 | 波胆3 种)、冠军盘 |
| 禁止盘口线 | 让球/大小族(含队进球、角球、罚牌)的 **`.25` / `.75` 线**`QUARTER_LINE` |
| 可串关玩法 | `PARLAY_MARKET_TYPES`**14 种**(见总览表「串关=✓」行) |
| 串关列表 API | `GET /api/player/matches?scope=parlay` 仅返回含可串关盘口的赛事 |
**串关派彩**(连乘有效因子、任一脚 LOSE 整单 LOST 等)见 [结算与返水金额规则.md §3](./结算与返水金额规则.md)。
---
## 5. 四分之一盘(.25 / .75
让球/大小盘盘口线为 **0.25 或 0.75** 的整数倍时(如 -0.25、2.75),系统将盘口**拆成两条半盘**分别判定,再合并为腿级结果:
| 两半组合 | 合并结果 |
|----------|----------|
| 两赢 | WIN |
| 两输 | LOSE |
| 一赢一走 | HALF_WIN |
| 一输一走 | HALF_LOSE |
| 一赢一输 | PUSH |
| 场景 | 单关 | 串关 |
|------|------|------|
| 四分之一线 | **允许**下注 | **禁止**选入(`QUARTER_LINE` |
**示例 1** — 全场让球 **-0.25**,选主队,比分 **0:0**
- 拆为 -0 与 -0.5 两半:-0 → PUSH-0.5 → LOSE
- 合并 → **HALF_LOSE**(退一半本金,见派彩文档)
**示例 2** — 全场大小 **2.25**,选小球,总进球 **2**
- 拆为 2.0 与 2.5:对 2.0 小球 PUSH对 2.5 小球 WIN
- 合并 → **HALF_WIN**
---
## 6. 下注校验与限额
### 6.1 下注校验(`BetsService.validateSelection`
| 校验项 | 说明 |
|--------|------|
| 盘口状态 | 选项与盘口均为 `OPEN` |
| 玩家可见 | `showOnPlayer = true` |
| 赛事 | `PUBLISHED`;非冠军盘须未开球 |
| 运动 | 仅足球 |
| 赔率版本 | 请求 `oddsVersion` 须与库内一致 |
| 单关/串关 | 单关要求 `allowSingle`;串关走 `canSelectForParlay` |
| 资金 | 通过 `FundsPostingService.freezeBet` 冻结本金 |
### 6.2 默认限额(`betting-limits.service.ts`
| 配置项 | 默认值 |
|--------|--------|
| 最小单注 | 1 |
| 单关最大投注 | 50,000 |
| 串关最大投注 | 20,000 |
| 单关最高派彩 | 500,000 |
| 串关最高派彩 | 1,000,000 |
| 玩家每日投注上限 | 200,000 |
可在管理端 `systemConfig` 覆盖;`potentialReturn` 超限会拒单(`MAX_PAYOUT`)。
### 6.3 其它
- **未知 marketType** 结算时默认 **LOSE**
- **选项 code 回退**:若快照无 code可从中文名推断`settlement-helpers.ts`
- **玩家选盘**:赛事详情 → 点赔率 → `BetSlipDrawer`;波胆用 `CorrectScorePanel`
---
## 7. 下注与结算流程摘要
```mermaid
sequenceDiagram
participant Player
participant API
participant Admin
Player->>API: POST /player/bets/single 或 parlay
API->>API: validateSelection + freezeBet
Admin->>API: recordScore
Admin->>API: previewSettlement
Admin->>API: confirmSettlement
API->>API: settleSelection 逐腿判赢
API->>API: calculatePayout 或 calculateParlayPayout
API->>Player: 钱包 settleBet 入账
```
| 阶段 | 说明 |
|------|------|
| 下注 | 创建 `Bet` + `BetSelection`,冻结 `stake` |
| 录入比分 | 赛事 → `PENDING_SETTLEMENT` |
| 预览 | 生成 `SettlementBatch`PREVIEW可含角球/罚牌统计 |
| 确认 | 写入腿级 `resultStatus`、注单 `status`/`actualReturn`,解冻并派彩 |
**跨场串关**:每场结算时只更新该场腿的 `resultStatus`;全部腿有结果后才调用 `calculateParlayPayout` 一次。
详细流程见 [settlement-and-fund-flow-analysis.md](./settlement-and-fund-flow-analysis.md)。
---
## 8. 代码真源与相关文档
### 8.1 代码索引
| 主题 | 文件 |
|------|------|
| 玩法目录18 种) | `packages/shared/src/market-catalog.ts` |
| 串关选盘规则 | `packages/shared/src/betting-rules.ts` |
| 下注与校验 | `apps/api/src/domains/betting/bets.service.ts` |
| 下注限额 | `apps/api/src/domains/betting/betting-limits.service.ts` |
| 腿级结算 | `apps/api/src/domains/settlement/domain/settlement-calculator.ts` |
| 结算流程 | `apps/api/src/domains/settlement/settlement.service.ts` |
| 结算辅助 | `apps/api/src/domains/settlement/domain/settlement-helpers.ts` |
| 单元测试 | `apps/api/src/domains/settlement/domain/settlement-calculator.spec.ts` |
| Smoke 用例 | `apps/api/src/domains/operations/smoke-tests/smoke-test.cases.ts` |
| 玩家投注单 | `apps/player/src/stores/betSlip.ts` |
### 8.2 相关文档
| 文档 | 内容 |
|------|------|
| [结算与返水金额规则.md](./结算与返水金额规则.md) | 单关/串关派彩公式、四分之一盘金额、返水 |
| [settlement-and-fund-flow-analysis.md](./settlement-and-fund-flow-analysis.md) | 结算三步、钱包流水 |
| [默认数据说明.md](./默认数据说明.md) | seed 盘口范围、48 强冠军盘 |
| [UAT_CHECKLIST.md](./UAT_CHECKLIST.md) | 投注与串关 UAT 项 |
### 8.3 文档分工
| 本文档 | 结算金额文档 |
|--------|--------------|
| 每种玩法怎么选、怎么判赢 | stake × odds 怎么算 |
| 串关能否选、同场限制 | 串关连乘因子与 payout |
| 角球/罚牌统计要求 | HALF_WIN 派彩数值示例 |
---
*最后更新:与 `FOOTBALL_MARKET_CATALOG`18 种)及 `settlement-calculator.ts` 实现对齐。*

View File

@@ -0,0 +1,410 @@
# 结算与返水金额规则
本文档为 **Reference参考**:只描述**金额如何计算**,不涉及管理端操作步骤。各玩法定义与判赢规则见 [投注玩法说明.md](./投注玩法说明.md);赛事结算流程见 [settlement-and-fund-flow-analysis.md](./settlement-and-fund-flow-analysis.md)。
---
## 1. 说明与术语
| 术语 | 含义 |
|------|------|
| **stake** | 投注本金(`Bet.stake` |
| **odds** | 欧赔,含本金系数(`BetSelection.odds` 或 leg 快照) |
| **payout** | 派彩总额,**含本金**(函数 `calculatePayout` / `calculateParlayPayout` 的返回值) |
| **actualReturn** | 确认结算后写入注单的派彩,与 `payout` 一致 |
| **净盈亏** | `payout - stake`LOSE 时 payout=0净亏 = -stake |
| **rate** | 返水比例,**小数**`0.01` = 1% |
| **lineAmount** | 单笔注单返水:`stake × rate` |
**精度**:业务金额在库中为 `Decimal(18,4)`;返水比例为 `Decimal(8,4)`。计算链使用 Prisma `Decimal` 全精度,**无额外 round**Admin UI 百分比输入另有 `rate-percent.ts` 转换,不影响 API 计算)。
### 代码真源索引
| 主题 | 文件 |
|------|------|
| 单关/串关派彩、四分之一盘 | `apps/api/src/domains/settlement/domain/settlement-calculator.ts` |
| 确认结算、`actualReturn`、注单状态 | `apps/api/src/domains/settlement/settlement.service.ts` |
| 钱包冻结/结算/重结算 | `apps/api/src/domains/ledger/wallet.service.ts` |
| 返水费率 | `apps/api/src/domains/operations/cashback/cashback-rate.resolver.ts` |
| 返水聚合/批次/入账 | `apps/api/src/domains/operations/cashback/cashback.service.ts` |
| 下注限额、`potentialReturn` | `apps/api/src/domains/betting/betting-limits.service.ts``bets.service.ts` |
| 代理授信 | `apps/api/src/domains/agent/agent-credit.service.ts` |
| 串关选盘限制 | `packages/shared/src/betting-rules.ts` |
| 可执行数值对照 | `apps/api/src/infrastructure/database/run-settlement-audit.ts` |
---
## 2. 单关派彩公式
函数:`calculatePayout(stake, odds, result)`
| 腿级结果 `SelectionResult` | 公式 | 说明 |
|---------------------------|------|------|
| **WIN** | `stake × odds` | 全赢 |
| **HALF_WIN** | `stake/2 × odds + stake/2` | 等价于 `stake × (odds + 1) / 2` |
| **PUSH** | `stake` | 走水,退本 |
| **VOID** | `stake` | 作废,退本 |
| **HALF_LOSE** | `stake / 2` | 半输,退一半本金 |
| **LOSE** | `0` | 全输 |
### 数值示例stake = 100
| 用例 ID | 场景 | odds | 结果 | payout | 净盈亏 |
|---------|------|------|------|--------|--------|
| BF001 | 1X2 主胜全赢 | 2.0 | WIN | **200.00** | +100.00 |
| BF002 | 1X2 和局选项全输 | — | LOSE | **0.00** | -100.00 |
| S009 | 让球 -1 全赢 | 1.85 | WIN | **185.00** | +85.00 |
| S010 | 让球 -1 走水 | 1.85 | PUSH | **100.00** | 0.00 |
| S011 | 让球 -0.25 半输 @ 0-0 | 1.85 | HALF_LOSE | **50.00** | -50.00 |
| S011B | 半赢派彩系数 | 1.85 | HALF_WIN | **142.50** | +42.50 |
| S012 | 让球 -0.5 全输 @ 0-0 | 1.85 | LOSE | **0.00** | -100.00 |
| S015 | 大小 小球 0-0 | 1.95 | WIN | **195.00** | +95.00 |
---
## 3. 串关派彩公式
函数:`calculateParlayPayout(stake, legs[])`
返回:`{ betResult, payout, effectiveOdds }`
```mermaid
flowchart TD
start[开始] --> anyLose{任一脚 LOSE?}
anyLose -->|是| lost["payout=0, betResult=LOST"]
anyLose -->|否| combine[连乘有效因子]
combine --> allPush{全部 PUSH 或 VOID?}
allPush -->|是| push["payout=stake, betResult=PUSH"]
allPush -->|否| won["payout=stake×combinedOdds, betResult=WON"]
```
### 各腿有效因子
| 腿级结果 | 连乘因子 |
|----------|----------|
| WIN | × `odds` |
| HALF_WIN | × `(odds + 1) / 2` |
| HALF_LOSE | × `0.5` |
| PUSH / VOID | × `1.0`(不参与升赔) |
| LOSE | 整单终止payout = 0 |
**最终**`payout = stake × combinedOdds`(除非 LOST 或全 PUSH/VOID
### 数值示例stake = 100
| 用例 ID | 腿组合 | effectiveOdds | payout | 净盈亏 |
|---------|--------|---------------|--------|--------|
| S016 | 1.8 WIN × 2.0 WIN | 3.6000 | **360.00** | +260.00 |
| S017 | 1.8 WIN × 2.0 LOSE | 0 | **0.00** | -100.00 |
| S018 | 1.8 WIN × 2.0 PUSH × 1.9 WIN | 3.4200 | **342.00** | +242.00 |
| S019 | 1.8 PUSH × 2.0 VOID | 1.0000 | **100.00** | 0.00 |
### 串关下注限制
串关**禁止**四分之一让球/大小盘(`.25` / `.75` 线),见 `canSelectForParlay` → 错误码 `QUARTER_LINE`。单关可使用四分之一盘。
### 跨场结算时序(影响何时产生 payout
1. 结算**某一场比赛**时,只更新该场对应腿的 `resultStatus`
2. 若其他场腿尚无结果 → 注单仍为 **PENDING**,此时无最终 `payout`
3. **任一脚在本场结算为 LOSE** 且其余腿已有结果 → 整单 **LOST**`payout = 0`
4. 全部腿均有结果后 → 调用 `calculateParlayPayout` 一次,写入 `actualReturn` 并入账。
---
## 4. 四分之一盘(.25 / .75
让球/大小盘为 `.25``.75` 时,`settleHandicap` / `settleOverUnder` 拆成**两条半盘**分别判定 WIN/PUSH/LOSE再合并
| 两半组合 | 合并结果 |
|----------|----------|
| 两赢 | WIN |
| 两输 | LOSE |
| 一赢一平 | HALF_WIN |
| 一输一平 | HALF_LOSE |
| 一赢一输 | PUSH |
**示例S011**:主让 -0.25,比分 0-0 → **HALF_LOSE** → payout = 50stake=100
---
## 5. `actualReturn` 与注单 `status` 映射
确认结算时(`SettlementService.confirmSettlement`
- **单关1 腿)**`result = settleSelection(...)``payout = calculatePayout(...)`**`actualReturn = payout`**
- **单关多腿 / 串关**:各腿结果齐备后 → **`actualReturn = calculateParlayPayout(...).payout`**
注单状态由 `betStatusFromSelection` 映射:
| 腿级 / 整单结果 | `Bet.status` |
|-----------------|--------------|
| LOSE | **LOST** |
| PUSH、VOID | **PUSH** |
| WIN、HALF_WIN、**HALF_LOSE** | **WON** |
### 易错点
| 场景 | actualReturn | Bet.status |
|------|--------------|------------|
| 单关半输HALF_LOSE | `stake/2`(如 50 | **WON**(部分返还仍记赢单) |
| 串关任一脚 LOSE | 0 | **LOST** |
| 串关全 PUSH/VOID | stake | **PUSH** |
串关确认入账时,钱包侧 `result` 简化为:整单 LOST → `LOSE`;整单 PUSH → `PUSH`;整单 WON → `WIN`(不区分腿级半赢半输)。
---
## 6. 钱包金额变动(结算侧)
### 下注冻结(`freezeForBet`
```
availableBalance -= stake
frozenBalance += stake
transactionType = BET_FREEZE
```
余额不足(`availableBalance < stake`)→ `INSUFFICIENT_BALANCE`
### 结算入账(`settleBet`
```
frozenBalance -= stake
availableBalance += payout // payout 即 actualReturn
```
| 传入 result | 流水类型 | payout 典型值 |
|-------------|----------|---------------|
| WIN | BET_SETTLE_WIN | stake × odds |
| HALF_WIN | BET_SETTLE_WIN | 半赢派彩 |
| LOSE | BET_SETTLE_LOSE | 0 |
| HALF_LOSE | BET_SETTLE_LOSE | stake / 2 |
| PUSH | BET_SETTLE_PUSH | stake |
| VOID | BET_VOID_REFUND | stake |
幂等键:`businessKey = settle:{batchNo}:{betNo}`
### 作废 / 取消比赛
- `Bet.status = VOID`**`actualReturn = stake`**
- 调用 `settleBet(..., payout=stake, result='VOID')`**BET_VOID_REFUND**
### 重结算(`confirmResettlement`
```
delta = 新 payout - 旧 actualReturn
```
- `delta > 0``applyResettleDelta`,流水 **BET_SETTLE_WIN**
- `delta < 0` → 流水 **RESETTLE_REVERSE**(可扣至**负余额**
- 注单 `settlementStatus = RESETTLED``actualReturn` 更新为新 payout
### 端到端钱包示例
| 用例 ID | 流程 | 钱包变化 | actualReturn |
|---------|------|----------|--------------|
| BF001 | 单关赢 100@2.02-1 | 1000 → 900 avail + 100 frozen → **1100 avail** | 200 |
| BF002 | 单关输(和局+2-1 | 1000 → **900 avail** | 0 |
| BF003 | 幂等 50 注 | 500 → **450 avail + 50 frozen** | — |
| BF004 | 余额不足 | **50 不变** | — |
| BF005 | 代理线玩家输 100 | 玩家 **900 avail** | 0 |
BF001 流水顺序:`MANUAL_DEPOSIT``BET_FREEZE``BET_SETTLE_WIN`
---
## 7. 下注时金额校验(与派彩相关)
### potentialReturn下单时估算
| 类型 | 公式 |
|------|------|
| 单关 | `stake × odds` |
| 串关 | `stake × ∏(各腿 odds)` |
按**全赢**估算,不含半赢/走水;用于 `maxPayout*` 校验。
### 默认限额(`BettingLimitsService`,可被 `system_config` 覆盖)
| 配置键 | 默认值 |
|--------|--------|
| `bet.min_stake` | 1 |
| `bet.max_stake_single` | 50,000 |
| `bet.max_stake_parlay` | 20,000 |
| `bet.max_payout_single` | 500,000 |
| `bet.max_payout_parlay` | 1,000,000 |
| `bet.daily_stake_limit` | 200,000`placedAt` 当日,排除 VOID/CANCELLED |
返水基数 `stake` 为通过上述校验后的下注金额,**与返水 rate 无联动**。
---
## 8. 返水金额算法
### 8.1 单笔返水
```
lineAmount = stake × rate
```
- **stake**:整单本金;串关**不按 leg 拆分**。
- 实现:`cashback.service.ts``bet.stake.mul(rate)`
### 8.2 费率解析(`resolveCashbackRateForBet`
**规则表 `CashbackRule` 优先级**(数值越大越优先):
| 优先级 | targetType | 匹配条件 |
|--------|------------|----------|
| 3 | USER | `targetId === userId` |
| 2 | AGENT | `targetId === agentId`(玩家直属代理) |
| 1 | GLOBAL | 无 targetId 限制 |
- 规则带 **marketType** 时,注单**任一** `BetSelection.marketType` 命中才适用;否则跳过该规则。
- **同优先级**:遍历规则时 `priority > best.priority`**严格大于**),先写入的同优先级规则不会被后者覆盖。
- **无规则命中** → 使用 `agentDefaultRate`(见下节)。
### 8.3 默认费率 `agentDefaultRate`(无 CashbackRule 时)
| 玩家类型 | 来源 |
|----------|------|
| 有 `parentId`(代理线下) | 直属代理 `AgentProfile.cashbackRate`;无 profile → **0** |
| 无 parent邀请人 sponsor 为 ADMIN | `system_config``cashback.admin_invite_rate` |
| 无 parent 的其他平台直属 | `system_config``cashback.platform_direct_rate` |
未配置时平台直属/邀请费率默认 **0**。子代理 `cashbackRate` 不得高于父代理。
### 8.4 合格注单(进入返水批次)
查询条件(`aggregatePeriod`
```
status IN ('WON', 'LOST')
settledAt 落在 [periodStart 00:00:00.000, periodEnd 23:59:59.999]
rate > 0
未被其他 PREVIEW / CONFIRMED 批次的 cashback_bets 占用
```
**不包含**PENDING、VOID、CANCELLED、**PUSH** 等。
周期按 **`settledAt`**,不是 `placedAt`
### 8.5 批次汇总
| 层级 | 公式 |
|------|------|
| 单笔 | `lineAmount = stake × rate` |
| 玩家 | `amount = Σ lineAmount``effectiveStake = Σ stake` |
| 展示 rate | `amount / effectiveStake`(加权平均,仅展示) |
| 平台批次 | `totalAmount = Σ 玩家 amount` |
### 8.6 发放入账
确认批次(`confirmBatch`)时:
| 字段 | 值 |
|------|-----|
| transactionType | **CASHBACK_DEPOSIT** |
| amount | 玩家批次 `item.amount`(正数) |
| businessKey | `cashback:{batchNo}:{userId}` |
| 效果 | `availableBalance += amount` |
**平台直充,不扣代理 credit**confirm **不**调用 `recalculateUsedCredit`
同时将批次内注单 `Bet.isCashbacked = true`
### 8.7 数值示例(费率 → 到账)
| 用例 ID | 场景 | rate | stake 100 | stake 500 | stake 1000 |
|---------|------|------|-----------|-----------|------------|
| CB001 | 玩家专属规则 | 0.03 (3%) | 3.00 | 15.00 | 30.00 |
| CB002 | 玩法专属 FT_HANDICAP | 0.005 (0.5%) | 0.50 | 2.50 | 5.00 |
| CB003 | 无规则,代理默认 | 0.02 (2%) | 2.00 | 10.00 | 20.00 |
| CB004 | 玩法不匹配回退默认 | 0.01 (1%) | 1.00 | — | — |
### 8.8 本地 dev seed
- `agent1` / `agent2``AgentProfile.cashbackRate` 默认为 schema **0**seed 未显式设置。
- seed **不创建** `CashbackRule`**不写入** 平台返水 `system_config`
- 本地要产生返水批次需在管理端配置代理默认比例、CashbackRule 或平台直属费率。
---
## 9. 代理授信与金额的间接关系
```
usedCredit = directPlayerLiability + childExposure
availableCredit = creditLimit - usedCredit
```
- **directPlayerLiability** = Σ(直属玩家的 `availableBalance + frozenBalance`
- **childExposure** = Σ max(子代理 `creditLimit`, 子代理 `usedCredit`)
| 事件 | 与返水/结算关系 |
|------|----------------|
| 玩家结算输/赢 | 改变余额 → 结算后重算 usedCredit |
| 返水 confirm | **不**扣代理 credit**不**即时重算;余额增加后**下次重算**计入负债 |
| 代理给玩家上分 | 检查 `availableCredit ≥ amount` |
**BF005**:玩家输 100 → 玩家 avail **900**;代理 `usedCredit` **1000 → 900**(结算后重算)。
---
## 10. 数值对照总表与验证
### 10.1 派彩速查stake = 100
| 类型 | 场景 | payout |
|------|------|--------|
| 单关 | 1X2 @2.0 WIN | 200.00 |
| 单关 | LOSE | 0.00 |
| 单关 | 让球 -1 @1.85 WIN | 185.00 |
| 单关 | PUSH | 100.00 |
| 单关 | HALF_LOSE | 50.00 |
| 单关 | HALF_WIN @1.85 | 142.50 |
| 单关 | 小球 @1.95 WIN | 195.00 |
| 串关 | 1.8×2.0 全中 | 360.00 |
| 串关 | 一关 LOSE | 0.00 |
| 串关 | 含 PUSH | 342.00 |
| 串关 | 全 PUSH/VOID | 100.00 |
### 10.2 返水速查rate × stake
| rate | stake 100 | stake 1000 |
|------|-----------|------------|
| 3% (0.03) | 3.00 | 30.00 |
| 2% (0.02) | 2.00 | 20.00 |
| 0.5% (0.005) | 0.50 | 5.00 |
### 10.3 维护与回归命令
```bash
# 打印与本文一致的金额对照表
pnpm --filter @thebet365/api audit:settlement
# 结算引擎单测(含 S016S019 串关)
pnpm --filter @thebet365/api exec jest settlement-calculator.spec.ts --runInBand
# 全量 smoke含 S009S019、CB001CB004、BF001BF005
pnpm test:smoke
```
修改 `settlement-calculator.ts``cashback-rate.resolver.ts` 或 smoke 期望金额时,**须同步更新本文档**并重新运行上述命令。
### 10.4 Smoke / 单测用例索引
| 套件 | ID 范围 | 内容 |
|------|---------|------|
| settlement | S009S019 | 让球/大小/串关派彩数值 |
| settlement | S011B | HALF_WIN 系数 |
| cashback | CB001CB004 | 费率解析 |
| bet-flow | BF001BF005 | 钱包 + 代理额度端到端 |
---
## 附录:支持的 marketType结算判定入口
金额规则与下列盘口共用 `settleSelection`;具体比分判定逻辑见 `settlement-calculator.ts`,本文不展开。
`FT_1X2``HT_1X2``FT_ODD_EVEN``FT_HANDICAP``HT_HANDICAP``FT_OVER_UNDER``HT_OVER_UNDER``FT_CORRECT_SCORE``HT_CORRECT_SCORE``SH_CORRECT_SCORE``HT_FT``FT_TOTAL_GOALS`、球队进球、角球/牌数相关盘、`OUTRIGHT_WINNER` 等。
未知 marketType 默认腿级结果 **LOSE**payout = 0

View File

@@ -69,6 +69,8 @@
## 三、默认赛事与盘口
各玩法判赢规则与 18 种盘口完整说明见 [投注玩法说明.md](./投注玩法说明.md)。
### 联赛
| 代码 | 名称 |

View File

@@ -11,6 +11,7 @@
"dev:manage": "pnpm --filter @thebet365/admin dev",
"build": "pnpm -r run build",
"test": "pnpm -r run test",
"test:smoke": "pnpm --filter @thebet365/api db:smoke",
"db:generate": "pnpm --filter @thebet365/api db:generate",
"db:migrate": "pnpm --filter @thebet365/api db:migrate",
"db:migrate:deploy": "pnpm --filter @thebet365/api db:migrate:deploy",

View File

@@ -877,6 +877,16 @@ export const API_ERROR_MESSAGES = {
'en-US': 'Order is already pending review',
'ms-MY': 'Pesanan sudah menunggu semakan',
},
ORDER_NOT_REJECTED: {
'zh-CN': '仅已拒绝的充值订单可重新申请',
'en-US': 'Only rejected deposit orders can be resubmitted',
'ms-MY': 'Hanya pesanan deposit yang ditolak boleh dihantar semula',
},
DEPOSIT_PENDING_ORDER_EXISTS: {
'zh-CN': '您已有待审核的充值订单,请等待审核完成后再提交',
'en-US': 'You already have a pending deposit order. Wait for review before submitting another.',
'ms-MY': 'Anda sudah ada pesanan deposit menunggu. Tunggu semakan selesai sebelum hantar lagi.',
},
ORDER_NOT_APPROVED: {
'zh-CN': '仅已通过的充值订单可撤销',
'en-US': 'Only approved deposit orders can be revoked',

View File

@@ -879,6 +879,16 @@ export const API_ERROR_MESSAGES = {
'en-US': 'Order is already pending review',
'ms-MY': 'Pesanan sudah menunggu semakan',
},
ORDER_NOT_REJECTED: {
'zh-CN': '仅已拒绝的充值订单可重新申请',
'en-US': 'Only rejected deposit orders can be resubmitted',
'ms-MY': 'Hanya pesanan deposit yang ditolak boleh dihantar semula',
},
DEPOSIT_PENDING_ORDER_EXISTS: {
'zh-CN': '您已有待审核的充值订单,请等待审核完成后再提交',
'en-US': 'You already have a pending deposit order. Wait for review before submitting another.',
'ms-MY': 'Anda sudah ada pesanan deposit menunggu. Tunggu semakan selesai sebelum hantar lagi.',
},
ORDER_NOT_APPROVED: {
'zh-CN': '仅已通过的充值订单可撤销',
'en-US': 'Only approved deposit orders can be revoked',

View File

@@ -1,6 +1,7 @@
export const PLATFORM_TIME_ZONE = 'Asia/Kuala_Lumpur';
export const PLATFORM_TIME_ZONE_OFFSET_MINUTES = 8 * 60;
export const PLATFORM_TIME_ZONE_OFFSET_LABEL = 'UTC+8';
export const MATCH_TODAY_NEXT_DAY_CUTOFF_HOUR = 12;
const PICKER_DATETIME_RE = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2}))?$/;
function pad2(value) {
return String(value).padStart(2, '0');
@@ -19,6 +20,68 @@ function formatDateTime(date, locale, options) {
return new Intl.DateTimeFormat('en-US', options).format(date);
}
}
function timeZoneParts(date, timeZone) {
const parts = new Intl.DateTimeFormat('en-US', {
timeZone,
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hourCycle: 'h23',
}).formatToParts(date);
return new Map(parts.map((part) => [part.type, part.value]));
}
function dayKeyInTimeZone(date, timeZone) {
const parts = timeZoneParts(date, timeZone);
return `${parts.get('year')}-${parts.get('month')}-${parts.get('day')}`;
}
function offsetMinutesInTimeZone(date, timeZone) {
const parts = timeZoneParts(date, timeZone);
const asUtc = Date.UTC(Number(parts.get('year')), Number(parts.get('month')) - 1, Number(parts.get('day')), Number(parts.get('hour')), Number(parts.get('minute')), Number(parts.get('second')));
return Math.round((asUtc - date.getTime()) / 60000);
}
function zonedWallTimeToUtc(parts, timeZone) {
const wallMs = Date.UTC(parts.year, parts.month - 1, parts.day, parts.hour, parts.minute ?? 0, parts.second ?? 0);
let utcMs = wallMs;
for (let i = 0; i < 3; i += 1) {
utcMs = wallMs - offsetMinutesInTimeZone(new Date(utcMs), timeZone) * 60 * 1000;
}
return new Date(utcMs);
}
function localDayParts(date, timeZone) {
const parts = timeZoneParts(date, timeZone);
return {
year: Number(parts.get('year')),
month: Number(parts.get('month')),
day: Number(parts.get('day')),
};
}
function addDaysToParts(parts, days) {
const d = new Date(Date.UTC(parts.year, parts.month - 1, parts.day + days));
return {
year: d.getUTCFullYear(),
month: d.getUTCMonth() + 1,
day: d.getUTCDate(),
};
}
function localTodayMatchWindow(now = new Date(), timeZone) {
if (timeZone) {
const today = localDayParts(now, timeZone);
const tomorrow = addDaysToParts(today, 1);
return {
start: zonedWallTimeToUtc({ ...today, hour: 0 }, timeZone),
end: zonedWallTimeToUtc({ ...tomorrow, hour: MATCH_TODAY_NEXT_DAY_CUTOFF_HOUR }, timeZone),
};
}
const start = new Date(now);
start.setHours(0, 0, 0, 0);
const end = new Date(start);
end.setDate(end.getDate() + 1);
end.setHours(MATCH_TODAY_NEXT_DAY_CUTOFF_HOUR, 0, 0, 0);
return { start, end };
}
function parsePickerParts(value) {
const match = PICKER_DATETIME_RE.exec(value.trim());
if (!match)
@@ -83,64 +146,95 @@ export function formatPlatformMatchDateTime(value, locale = 'en-US') {
});
return `${formatted} ${PLATFORM_TIME_ZONE_OFFSET_LABEL}`;
}
export function getLocalGmtOffsetLabel(value = new Date()) {
export function getLocalGmtOffsetLabel(value = new Date(), timeZone) {
const date = validDate(value) ?? new Date();
const offsetMinutes = -date.getTimezoneOffset();
const offsetMinutes = timeZone
? offsetMinutesInTimeZone(date, timeZone)
: -date.getTimezoneOffset();
const sign = offsetMinutes >= 0 ? '+' : '-';
const abs = Math.abs(offsetMinutes);
const hours = Math.floor(abs / 60);
const minutes = abs % 60;
return minutes === 0 ? `GMT${sign}${hours}` : `GMT${sign}${hours}:${pad2(minutes)}`;
}
export function isSameLocalCalendarDay(value, now = new Date()) {
export function isSameLocalCalendarDay(value, now = new Date(), timeZone) {
const date = validDate(value);
if (!date)
return false;
if (timeZone) {
return dayKeyInTimeZone(date, timeZone) === dayKeyInTimeZone(now, timeZone);
}
return (date.getFullYear() === now.getFullYear() &&
date.getMonth() === now.getMonth() &&
date.getDate() === now.getDate());
}
export function isInLocalToday(value, now = new Date()) {
export function isInLocalToday(value, now = new Date(), timeZone) {
const date = validDate(value);
if (!date)
return false;
if (timeZone) {
return dayKeyInTimeZone(date, timeZone) === dayKeyInTimeZone(now, timeZone);
}
const start = new Date(now);
start.setHours(0, 0, 0, 0);
const end = new Date(start);
end.setDate(end.getDate() + 1);
return date >= start && date < end;
}
export function isAfterLocalToday(value, now = new Date()) {
export function isAfterLocalToday(value, now = new Date(), timeZone) {
const date = validDate(value);
if (!date)
return false;
if (timeZone) {
return dayKeyInTimeZone(date, timeZone) > dayKeyInTimeZone(now, timeZone);
}
const end = new Date(now);
end.setHours(0, 0, 0, 0);
end.setDate(end.getDate() + 1);
return date >= end;
}
export function isInLocalTodayMatchWindow(value, now = new Date(), timeZone) {
const date = validDate(value);
if (!date)
return false;
const { start, end } = localTodayMatchWindow(now, timeZone);
return date >= start && date < end;
}
export function isAfterLocalTodayMatchWindow(value, now = new Date(), timeZone) {
const date = validDate(value);
if (!date)
return false;
const { end } = localTodayMatchWindow(now, timeZone);
return date >= end;
}
export function formatLocalMatchDateTime(value, locale = 'en-US', options = {}) {
const date = validDate(value);
if (!date)
return '';
const variant = options.variant ?? 'compact';
const time = formatDateTime(date, locale, {
...(options.timeZone ? { timeZone: options.timeZone } : {}),
hour: '2-digit',
minute: '2-digit',
...(options.includeSeconds ? { second: '2-digit' } : {}),
});
let text;
if (variant === 'compact') {
if (options.todayLabel && isSameLocalCalendarDay(date)) {
if (options.todayLabel && isSameLocalCalendarDay(date, new Date(), options.timeZone)) {
text = `${options.todayLabel} ${time}`;
}
else {
const day = formatDateTime(date, locale, { month: 'numeric', day: 'numeric' });
const day = formatDateTime(date, locale, {
...(options.timeZone ? { timeZone: options.timeZone } : {}),
month: 'numeric',
day: 'numeric',
});
text = `${day} ${time}`;
}
}
else {
const day = formatDateTime(date, locale, {
...(options.timeZone ? { timeZone: options.timeZone } : {}),
year: 'numeric',
month: '2-digit',
day: '2-digit',
@@ -149,5 +243,5 @@ export function formatLocalMatchDateTime(value, locale = 'en-US', options = {})
}
if (options.includeTimeZone === false)
return text;
return `${text} ${getLocalGmtOffsetLabel(date)}`;
return `${text} ${getLocalGmtOffsetLabel(date, options.timeZone)}`;
}