From 8e1cbdba9fad37aadccf71b6dc2f9644d0fc7586 Mon Sep 17 00:00:00 2001 From: zhaoxing <2558691827@qq.com> Date: Sun, 15 Nov 2026 21:57:31 +0800 Subject: [PATCH 01/15] =?UTF-8?q?feat(semi-auto):=20=E9=87=8D=E6=9E=84?= =?UTF-8?q?=E5=AE=A2=E6=88=B7=E8=B5=84=E6=96=99=E6=94=B6=E9=9B=86=E4=B8=8E?= =?UTF-8?q?=E8=99=8E=E7=89=99=E7=BB=91=E5=AE=9A=E7=A1=AE=E8=AE=A4=E6=B5=81?= =?UTF-8?q?=E7=A8=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 客户资料页按设计稿重构,区服固定四项下拉,游戏编号/角色名校验 - 虎牙登录与绑定页统一深色样式,扫码页新增改用手机号登录 - 待确认角色 UID 改用 huyaUid,不再展示虎牙加密 roleId - 绑定确认新增两侧角色比对,不一致禁止确认,会话过期引导重新登录 - 新增迁移 168/169 与角色绑定单测,脚本换行符固定为 LF --- apps/backend/.gitattributes | 4 + .../168_semi_auto_binding_role_id.sql | 14 + .../169_semi_auto_customer_profile.sql | 18 + .../src/routes/customer-fulfillment.ts | 46 + .../dev-mock/mock-semi-auto-connector.ts | 6 + .../src/services/semi-auto/binding-role-id.ts | 16 + .../semi-auto/huya-connector-client.ts | 2 + .../huya-native/huya-native-connector.ts | 30 +- .../semi-auto/semi-auto-binding-role.test.ts | 142 +++ .../semi-auto/semi-auto-task-service.ts | 269 ++++- .../weibo-native/weibo-native-connector.ts | 2 + apps/frontend/src/lib/http.ts | 22 + .../pages/admin/AdminSemiAutoTasksPage.tsx | 41 + .../CustomerFulfillmentPage.tsx | 1030 +++++++++++++++-- .../src/services/customer-fulfillment.ts | 41 +- apps/frontend/src/styles/client.css | 724 ++++++++++-- apps/frontend/src/types/admin/semi-auto.ts | 8 + .../src/types/customer-fulfillment.ts | 32 + 18 files changed, 2238 insertions(+), 209 deletions(-) create mode 100644 apps/backend/.gitattributes create mode 100644 apps/backend/src/db/migrations/168_semi_auto_binding_role_id.sql create mode 100644 apps/backend/src/db/migrations/169_semi_auto_customer_profile.sql create mode 100644 apps/backend/src/services/semi-auto/binding-role-id.ts create mode 100644 apps/backend/src/services/semi-auto/semi-auto-binding-role.test.ts diff --git a/apps/backend/.gitattributes b/apps/backend/.gitattributes new file mode 100644 index 00000000..375c8b6f --- /dev/null +++ b/apps/backend/.gitattributes @@ -0,0 +1,4 @@ +# 容器内 /bin/sh 直接执行的脚本必须是 LF。 +# Windows 下 core.autocrlf=true 会把 checkout 出来的 .sh 转成 CRLF, +# 导致 `set: Illegal option -`,backend 容器反复重启。 +*.sh text eol=lf diff --git a/apps/backend/src/db/migrations/168_semi_auto_binding_role_id.sql b/apps/backend/src/db/migrations/168_semi_auto_binding_role_id.sql new file mode 100644 index 00000000..7b5b0bc6 --- /dev/null +++ b/apps/backend/src/db/migrations/168_semi_auto_binding_role_id.sql @@ -0,0 +1,14 @@ +-- 168_semi_auto_binding_role_id.sql +-- +-- 客户页角色绑定需要保存平台侧角色 ID: +-- 1. 虎牙 checkUserBindGameAccount 的 gameRole.roleId 即平台侧角色 ID; +-- 2. 客户工单资料里的游戏 ID(gameId / characterId)作为客户填写角色 ID; +-- 3. 两侧角色 ID 不一致时禁止确认绑定,只允许重新扫码或联系客服。 +-- +-- 该列只保存平台识别结果,不参与订单、资金等 A 级事实。 + +ALTER TABLE semi_auto_tasks + ADD COLUMN IF NOT EXISTS bind_game_role_id TEXT NOT NULL DEFAULT ''; + +COMMENT ON COLUMN semi_auto_tasks.bind_game_role_id IS + '平台侧游戏角色 ID(虎牙 gameRole.roleId),用于与客户填写角色比对'; diff --git a/apps/backend/src/db/migrations/169_semi_auto_customer_profile.sql b/apps/backend/src/db/migrations/169_semi_auto_customer_profile.sql new file mode 100644 index 00000000..81996656 --- /dev/null +++ b/apps/backend/src/db/migrations/169_semi_auto_customer_profile.sql @@ -0,0 +1,18 @@ +-- 169_semi_auto_customer_profile.sql +-- +-- 半自动订单不会生成 work_orders,客户资料页 /c/<订单号> 是唯一入口: +-- 1. 客户在授权页填写本次需要绑定的角色名称 / 游戏编号(角色 ID)/ 区服; +-- 2. 平台识别到角色后,用这里填写的角色 ID 与 bind_game_role_id 比对; +-- 3. 两侧不一致时禁止确认绑定,只能重新扫码或联系客服。 + +ALTER TABLE semi_auto_tasks + ADD COLUMN IF NOT EXISTS customer_game_role_name TEXT NOT NULL DEFAULT '', + ADD COLUMN IF NOT EXISTS customer_game_role_id TEXT NOT NULL DEFAULT '', + ADD COLUMN IF NOT EXISTS customer_game_server_zone TEXT NOT NULL DEFAULT ''; + +COMMENT ON COLUMN semi_auto_tasks.customer_game_role_name IS + '客户在授权页填写的游戏角色名称'; +COMMENT ON COLUMN semi_auto_tasks.customer_game_role_id IS + '客户在授权页填写的游戏编号 / 角色 ID,用于与平台识别角色比对'; +COMMENT ON COLUMN semi_auto_tasks.customer_game_server_zone IS + '客户在授权页填写的区服'; diff --git a/apps/backend/src/routes/customer-fulfillment.ts b/apps/backend/src/routes/customer-fulfillment.ts index 793b121c..98507025 100644 --- a/apps/backend/src/routes/customer-fulfillment.ts +++ b/apps/backend/src/routes/customer-fulfillment.ts @@ -1,15 +1,19 @@ import { Router } from 'express' import { + confirmPublicBinding, getPublicWeiboCountryCodes, listPublicSemiAutoTasks, loginPublicHuyaSms, loginPublicWeiboSms, markCustomerLinkOpened, + pollPublicBinding, pollPublicLogin, pollPublicWeiboQrLogin, + savePublicTaskProfile, sendPublicHuyaSmsCode, sendPublicWeiboSmsCode, + startPublicBinding, startPublicLogin, startPublicWeiboQrLogin, verifyPublicHuyaSmsChallenge, @@ -70,6 +74,48 @@ router.get( }), ) +router.post( + '/:orderNo/tasks/:taskId/profile', + writeLimit, + createRouteHandler( + (req) => savePublicTaskProfile(req.params.orderNo, req.params.taskId, req.body || {}), + { + successMessage: '角色资料已保存', + errorMessage: '保存角色资料失败', + scope: '[customer-fulfillment/:orderNo/tasks/:taskId/profile]', + }, + ), +) + +router.post( + '/:orderNo/tasks/:taskId/binding/start', + writeLimit, + createRouteHandler((req) => startPublicBinding(req.params.orderNo, req.params.taskId, req.body), { + successMessage: '绑定会话已创建', + errorMessage: '开始账号绑定失败', + scope: '[customer-fulfillment/:orderNo/tasks/:taskId/binding/start]', + }), +) + +router.get( + '/:orderNo/tasks/:taskId/binding/status', + readLimit, + createRouteHandler((req) => pollPublicBinding(req.params.orderNo, req.params.taskId), { + errorMessage: '刷新账号绑定状态失败', + scope: '[customer-fulfillment/:orderNo/tasks/:taskId/binding/status]', + }), +) + +router.post( + '/:orderNo/tasks/:taskId/binding/confirm', + writeLimit, + createRouteHandler((req) => confirmPublicBinding(req.params.orderNo, req.params.taskId), { + successMessage: '绑定已确认', + errorMessage: '确认账号绑定失败', + scope: '[customer-fulfillment/:orderNo/tasks/:taskId/binding/confirm]', + }), +) + router.get( '/:orderNo/tasks/:taskId/weibo/config', readLimit, diff --git a/apps/backend/src/services/dev-mock/mock-semi-auto-connector.ts b/apps/backend/src/services/dev-mock/mock-semi-auto-connector.ts index 1349c6d5..7c35bdf6 100644 --- a/apps/backend/src/services/dev-mock/mock-semi-auto-connector.ts +++ b/apps/backend/src/services/dev-mock/mock-semi-auto-connector.ts @@ -50,6 +50,7 @@ type MockSession = { bindingQrExpiresAtMs: number bindGameAccount: string bindGameRole: string + bindGameRoleId: string bindGameChannel: string message: string tickets: Map @@ -136,8 +137,10 @@ function bindingView(session: MockSession): ConnectorBindingSession { status: session.bindingStatus, qrImage: session.bindingStatus === 'not_started' ? '' : buildMockBindingQr(session.sessionId), qrExpiresAt: new Date(session.bindingQrExpiresAtMs).toISOString(), + qrUrl: '', bindGameAccount: session.bindGameAccount, bindGameRole: session.bindGameRole, + bindGameRoleId: session.bindGameRoleId, bindGameChannel: session.bindGameChannel, message: session.message, } @@ -158,6 +161,7 @@ function markRoleReady(session: MockSession) { session.bindingStatus = 'role_ready' session.bindGameAccount = `mock-account-${session.sessionId.slice(-6)}` session.bindGameRole = 'Mock测试角色' + session.bindGameRoleId = `mock-role-${session.sessionId.slice(-6)}` session.bindGameChannel = '虎牙' session.message = 'Mock 已识别游戏角色,请确认绑定' } @@ -188,6 +192,7 @@ export function createMockLoginSession(input: { bindingQrExpiresAtMs: 0, bindGameAccount: '', bindGameRole: '', + bindGameRoleId: '', bindGameChannel: '', message: 'Mock 登录二维码已生成,轮询后会自动模拟扫码成功', tickets: new Map(), @@ -230,6 +235,7 @@ export function sendMockHuyaSmsCode(input: { bindingQrExpiresAtMs: 0, bindGameAccount: '', bindGameRole: '', + bindGameRoleId: '', bindGameChannel: '', message: 'Mock 短信验证码已发送,请输入 123456', tickets: new Map(), diff --git a/apps/backend/src/services/semi-auto/binding-role-id.ts b/apps/backend/src/services/semi-auto/binding-role-id.ts new file mode 100644 index 00000000..6ecda7f1 --- /dev/null +++ b/apps/backend/src/services/semi-auto/binding-role-id.ts @@ -0,0 +1,16 @@ +/** + * 虎牙 checkUserBindGameAccount 返回的 gameRole.roleId 是 40 位加密串, + * 无法直接和客户填写的游戏编号比对;平台侧可用于核对的是登录账号的数值 UID(huyaUid)。 + * + * 取数优先级:角色 ID 本身是纯数字 > 数值 UID > 原始角色 ID。 + * 这样既兼容未来虎牙直接下发数值角色 ID,也避免把加密串展示给客户。 + */ +export function resolveBindingRoleId(roleId: unknown, huyaUid: unknown): string { + const rawRoleId = String(roleId ?? '').trim() + + if (/^\d+$/.test(rawRoleId)) return rawRoleId + + const uid = String(huyaUid ?? '').trim() + + return /^\d+$/.test(uid) ? uid : rawRoleId +} diff --git a/apps/backend/src/services/semi-auto/huya-connector-client.ts b/apps/backend/src/services/semi-auto/huya-connector-client.ts index ea1751b5..d2e06045 100644 --- a/apps/backend/src/services/semi-auto/huya-connector-client.ts +++ b/apps/backend/src/services/semi-auto/huya-connector-client.ts @@ -95,8 +95,10 @@ export type ConnectorBindingSession = { | 'failed' qrImage: string qrExpiresAt: string + qrUrl: string bindGameAccount: string bindGameRole: string + bindGameRoleId: string bindGameChannel: string hasExistingBinding?: boolean rebindRequested?: boolean diff --git a/apps/backend/src/services/semi-auto/huya-native/huya-native-connector.ts b/apps/backend/src/services/semi-auto/huya-native/huya-native-connector.ts index 8bc31c4f..a1dbc772 100644 --- a/apps/backend/src/services/semi-auto/huya-native/huya-native-connector.ts +++ b/apps/backend/src/services/semi-auto/huya-native/huya-native-connector.ts @@ -12,6 +12,7 @@ import path from 'node:path' import { runtimeConfig } from '../../../config/runtime.js' import { createHttpError } from '../../../utils/http.js' import { logWarn } from '../../../utils/logger.js' +import { resolveBindingRoleId } from '../binding-role-id.js' import type { ConnectorBindingSession, ConnectorBrowserTicket, @@ -62,10 +63,12 @@ type NativeBindingStatus = ConnectorBindingSession['status'] type NativeBindState = { status: NativeBindingStatus qrImage: string + qrUrl: string qrToken: string expiresAtMs: number account: string role: string + roleId: string channel: string hasExistingBinding: boolean rebindRequested: boolean @@ -135,10 +138,12 @@ function defaultBindingState(): NativeBindState { return { status: 'not_started', qrImage: '', + qrUrl: '', qrToken: '', expiresAtMs: 0, account: '', role: '', + roleId: '', channel: '', hasExistingBinding: false, rebindRequested: false, @@ -223,18 +228,29 @@ function smsBehavior(page = 'https://www.huya.com/g'): { behavior: string; page: function parseRole(response: HuyaBindResponse | null): { account: string role: string + roleId: string channel: string } { - if (!response || response.status !== 200) return { account: '', role: '', channel: '' } + if (!response || response.status !== 200) { + return { account: '', role: '', roleId: '', channel: '' } + } const data: HuyaGameAccountData = response.accountData const account = data.gameAccount.nick || data.gameRole.roleName const role = data.gameRole.roleName const channel = [data.gameRole.platName, data.gameRole.areaName].filter(Boolean).join(' · ') - return { account, role, channel } + // 虎牙 checkUserBindGameAccount 的 gameRole.roleId 就是平台侧角色 ID; + // 该字段一直存在于 RPC 响应里,之前被丢弃,导致客户页无法做两侧角色比对。 + const roleId = String(data.gameRole.roleId || '').trim() + return { account, role, roleId, channel } } -function bindingRoleKey(role: { account: string; role: string; channel: string }): string { - return [role.account, role.role, role.channel].join('\u0000') +function bindingRoleKey(role: { + account: string + role: string + roleId?: string + channel: string +}): string { + return [role.account, role.role, role.roleId || '', role.channel].join('\u0000') } function configValues() { @@ -720,6 +736,7 @@ export class HuyaNativeConnector { } session.binding.status = 'qr_pending' session.binding.qrImage = mini.image + session.binding.qrUrl = urls.qrUrl session.binding.qrToken = mini.token session.binding.expiresAtMs = this.now() + BINDING_QR_TTL_MS session.binding.message = options.forceRebind @@ -1042,12 +1059,13 @@ export class HuyaNativeConnector { private markRoleReady( session: NativeSession, - role: { account: string; role: string; channel: string }, + role: { account: string; role: string; roleId?: string; channel: string }, existingBinding = false, ): void { session.binding.status = 'role_ready' session.binding.account = role.account session.binding.role = role.role + session.binding.roleId = role.roleId || '' session.binding.channel = role.channel session.binding.message = existingBinding ? '当前账号已有绑定角色,请确认直接使用' @@ -1131,8 +1149,10 @@ export class HuyaNativeConnector { status: binding.status, qrImage: binding.qrImage, qrExpiresAt: binding.expiresAtMs ? iso(binding.expiresAtMs) : '', + qrUrl: binding.qrUrl, bindGameAccount: binding.account, bindGameRole: binding.role, + bindGameRoleId: resolveBindingRoleId(binding.roleId, session.uid), bindGameChannel: binding.channel, hasExistingBinding: binding.hasExistingBinding, rebindRequested: binding.rebindRequested, diff --git a/apps/backend/src/services/semi-auto/semi-auto-binding-role.test.ts b/apps/backend/src/services/semi-auto/semi-auto-binding-role.test.ts new file mode 100644 index 00000000..5ba3ea98 --- /dev/null +++ b/apps/backend/src/services/semi-auto/semi-auto-binding-role.test.ts @@ -0,0 +1,142 @@ +import assert from 'node:assert/strict' +import { describe, it } from 'node:test' + +import { resolveBindingRoleId } from './binding-role-id.js' +import { compareBindingRole, normalizeCustomerProfile } from './semi-auto-task-service.js' + +const task = (id: string, name: string, huyaUid = '') => ({ + customer_game_id: id, + customer_game_role: name, + huya_uid: huyaUid, +}) + +describe('待确认角色 UID 取数(huyaUid)', () => { + it('角色 ID 本身是纯数字时直接使用', () => { + assert.equal(resolveBindingRoleId('1192083858', 1199608910400), '1192083858') + }) + + it('角色 ID 是加密串时改用数值 UID', () => { + assert.equal( + resolveBindingRoleId('834ee3e75a1bfc9f65fb6b966bac7ef318e68ea', '1199608910400'), + '1199608910400', + ) + }) + + it('缺少角色 ID 时回退到数值 UID', () => { + assert.equal(resolveBindingRoleId('', 1199608910400), '1199608910400') + }) + + it('没有可用数值 UID 时保留原始角色 ID', () => { + assert.equal( + resolveBindingRoleId('834ee3e75a1bfc9f65fb6b966bac7ef318e68ea', ''), + '834ee3e75a1bfc9f65fb6b966bac7ef318e68ea', + ) + assert.equal(resolveBindingRoleId(null, undefined), '') + }) + + it('虎牙加密串角色 ID 改用 huyaUid 参与比对', () => { + const result = compareBindingRole(task('1199608910400', '大鲨鱼伊塞53', '1199608910400'), { + bindGameRole: '大鲨鱼伊塞53', + bindGameRoleId: '834ee3e75a1bfc9f65fb6b966bac7ef318e68ea', + }) + assert.equal(result.verdict, 'match') + assert.equal(result.boundRoleId, '1199608910400') + }) + + it('没有 huyaUid 时保留原始加密串,仍判不一致', () => { + const result = compareBindingRole(task('1199608910400', '大鲨鱼伊塞53'), { + bindGameRole: '大鲨鱼伊塞53', + bindGameRoleId: '834ee3e75a1bfc9f65fb6b966bac7ef318e68ea', + }) + assert.equal(result.verdict, 'mismatch') + assert.equal(result.boundRoleId, '834ee3e75a1bfc9f65fb6b966bac7ef318e68ea') + }) +}) + +describe('客户填写角色与平台识别角色比对', () => { + it('两侧角色 ID 一致时允许确认', () => { + const result = compareBindingRole(task('1192083858', '巫师基尔斯84'), { + bindGameRole: '巫师基尔斯84', + bindGameRoleId: '1192083858', + }) + assert.equal(result.verdict, 'match') + assert.equal(result.customerRoleId, '1192083858') + assert.equal(result.boundRoleId, '1192083858') + }) + + it('两侧角色 ID 不一致时禁止确认', () => { + const result = compareBindingRole(task('1192083858', '巫师基尔斯84'), { + bindGameRole: '我是火星人2222', + bindGameRoleId: '166909256', + }) + assert.equal(result.verdict, 'mismatch') + assert.match(result.message, /不一致/) + }) + + it('缺少角色 ID 时退回角色名称比对', () => { + const matched = compareBindingRole(task('', '巫师基尔斯84'), { + bindGameRole: '巫师基尔斯84', + bindGameRoleId: '', + }) + assert.equal(matched.verdict, 'match') + + const mismatched = compareBindingRole(task('', '巫师基尔斯84'), { + bindGameRole: '我是火星人2222', + bindGameRoleId: '', + }) + assert.equal(mismatched.verdict, 'mismatch') + }) + + it('两侧都没有可核对信息时标记为 unknown', () => { + const result = compareBindingRole(task('', ''), { bindGameRole: '', bindGameRoleId: '' }) + assert.equal(result.verdict, 'unknown') + }) +}) + +describe('客户角色资料校验', () => { + it('清理空白并保留纯数字角色 ID', () => { + const profile = normalizeCustomerProfile({ + roleName: ' 巫师基尔斯84 ', + roleId: ' 1192083858 ', + serverZone: ' 苹果V区 ', + }) + assert.deepEqual(profile, { + roleName: '巫师基尔斯84', + roleId: '1192083858', + serverZone: '苹果V区', + }) + }) + + it('角色 ID 非数字时拒绝保存', () => { + assert.throws( + () => normalizeCustomerProfile({ roleName: '巫师基尔斯84', roleId: 'abc123' }), + /只能是数字/, + ) + }) + + it('缺区服时拒绝保存', () => { + assert.throws( + () => normalizeCustomerProfile({ roleName: '巫师基尔斯84', roleId: '1192083858' }), + /区服只能选择/, + ) + }) + + it('区服不在固定选项时拒绝保存', () => { + assert.throws( + () => + normalizeCustomerProfile({ + roleName: '巫师基尔斯84', + roleId: '1192083858', + serverZone: '苹果微信区', + }), + /区服只能选择/, + ) + }) + + it('角色名称与角色 ID 都为空时拒绝保存', () => { + assert.throws( + () => normalizeCustomerProfile({ roleName: ' ', roleId: '', serverZone: '苹果V区' }), + /请完整填写区服/, + ) + }) +}) diff --git a/apps/backend/src/services/semi-auto/semi-auto-task-service.ts b/apps/backend/src/services/semi-auto/semi-auto-task-service.ts index 5efe0b64..5ee7a8da 100644 --- a/apps/backend/src/services/semi-auto/semi-auto-task-service.ts +++ b/apps/backend/src/services/semi-auto/semi-auto-task-service.ts @@ -98,7 +98,14 @@ type TaskRow = { platform_nickname: string bind_game_account: string bind_game_role: string + bind_game_role_id: string bind_game_channel: string + customer_game_role_name: string + customer_game_role_id: string + customer_game_server_zone: string + customer_game_id: string + customer_game_role: string + customer_server_zone: string target_quantity: number completed_quantity: number assigned_admin_user_id: number | null @@ -175,7 +182,20 @@ function displayStatus(task: TaskRow) { return { key: 'failed', label: '需客服处理' } } if (task.login_status === 'authenticated') { - return { key: 'waiting_operator', label: '等待客服处理' } + // 虎牙需要客户确认绑定角色后才算授权完成;微博登录即授权。 + if (task.platform === 'weibo' || task.binding_status === 'confirmed') { + return { key: 'waiting_operator', label: '等待客服处理' } + } + if (task.binding_status === 'role_ready') { + return { key: 'binding_confirm', label: '待确认绑定角色' } + } + if (task.binding_status === 'expired') { + return { key: 'binding_expired', label: '绑定二维码已过期' } + } + if (task.binding_status === 'failed') { + return { key: 'binding_failed', label: '绑定失败,需重新扫码' } + } + return { key: 'waiting_binding', label: '等待客户绑定角色' } } if (task.login_status === 'scanned') return { key: 'login_scanned', label: '已扫码,确认中' } if (task.login_status === 'qr_pending') return { key: 'waiting_login', label: '等待客户登录' } @@ -205,7 +225,11 @@ function mapTask(task: TaskRow) { platformNickname: task.platform_nickname, bindGameAccount: task.bind_game_account, bindGameRole: task.bind_game_role, + bindGameRoleId: task.bind_game_role_id, bindGameChannel: task.bind_game_channel, + customerGameRoleId: task.customer_game_id || '', + customerGameRoleName: task.customer_game_role || '', + customerServerZone: task.customer_server_zone || '', targetQuantity: Number(task.target_quantity || 1), completedQuantity: Number(task.completed_quantity || 0), assignedAdminUserId: task.assigned_admin_user_id ? Number(task.assigned_admin_user_id) : null, @@ -289,13 +313,41 @@ const TASK_SELECT = ` cfg.semi_auto_config_json, credential.credential_status, credential.credential_source, - credential.credential_updated_at + credential.credential_updated_at, + COALESCE( + NULLIF(task.customer_game_role_id, ''), + wo.material_json->'collect'->'fields'->>'gameId', + wo.material_json->'collect'->'fields'->>'characterId', + '' + ) AS customer_game_id, + COALESCE( + NULLIF(task.customer_game_role_name, ''), + NULLIF(wo.material_json->'collect'->'fields'->>'gameNickname', ''), + NULLIF(wo.material_json->'collect'->'fields'->>'roleName', ''), + '' + ) AS customer_game_role, + COALESCE( + NULLIF(task.customer_game_server_zone, ''), + wo.material_json->'collect'->'fields'->>'serverZone', + '' + ) AS customer_server_zone FROM semi_auto_tasks task JOIN orders o ON o.id = task.order_id JOIN order_items oi ON oi.id = task.order_item_id LEFT JOIN manual_fulfillment_configs cfg ON cfg.id = task.manual_fulfillment_config_id LEFT JOIN admin_users admin ON admin.id = task.assigned_admin_user_id LEFT JOIN semi_auto_credentials credential ON credential.id = task.credential_id + LEFT JOIN LATERAL ( + SELECT candidate.material_json + FROM work_orders candidate + WHERE candidate.order_item_id = task.order_item_id + OR (candidate.order_item_id IS NULL AND candidate.order_id = task.order_id) + OR (o.platform_order_id <> '' AND candidate.platform_order_id = o.platform_order_id) + ORDER BY (candidate.order_item_id = task.order_item_id) DESC NULLS LAST, + (candidate.order_id = task.order_id) DESC NULLS LAST, + candidate.id DESC + LIMIT 1 + ) wo ON TRUE ` async function loadTask(taskId: number): Promise { @@ -354,6 +406,24 @@ function assertHuyaTask(task: TaskRow) { } } +/** + * 半自动订单没有工单,资料页 /c/<订单号> 是唯一入口。 + * 未提交区服 / 游戏编号 / 角色名时,不允许开始登录,避免后续无法比对角色。 + */ +function assertCustomerProfileReady(task: TaskRow) { + if (task.platform !== 'huya') return + if ( + !String(task.customer_game_server_zone || '').trim() || + !String(task.customer_game_role_id || '').trim() || + !String(task.customer_game_role_name || '').trim() + ) { + throw createHttpError('请先提交游戏角色资料', { + statusCode: 409, + errorCode: 'semi_auto_profile_required', + }) + } +} + async function createLoginSessionForTask( task: TaskRow, orderNo: string, @@ -679,6 +749,98 @@ export async function markCustomerLinkOpened(orderNoInput: unknown, taskIdInput: return { ok: true } } +export type CustomerProfileInput = { + roleName?: unknown + roleId?: unknown + serverZone?: unknown +} + +const CUSTOMER_SERVER_ZONES = new Set(['苹果Q区', '苹果V区', '安卓Q区', '安卓V区']) + +export function normalizeCustomerProfile(input: CustomerProfileInput = {}) { + const roleName = String(input.roleName ?? '') + .trim() + .slice(0, 100) + const roleId = String(input.roleId ?? '') + .replace(/\s+/g, '') + .slice(0, 64) + const serverZone = String(input.serverZone ?? '') + .trim() + .slice(0, 100) + if (roleId && !/^\d+$/.test(roleId)) { + throw createHttpError('游戏编号 / 角色 ID 只能是数字', { + statusCode: 400, + errorCode: 'semi_auto_profile_role_id_invalid', + }) + } + if (!CUSTOMER_SERVER_ZONES.has(serverZone)) { + throw createHttpError('区服只能选择 苹果Q区 / 苹果V区 / 安卓Q区 / 安卓V区', { + statusCode: 400, + errorCode: 'semi_auto_profile_server_zone_invalid', + }) + } + if (!roleName || !roleId) { + throw createHttpError('请完整填写区服、游戏编号和角色名', { + statusCode: 400, + errorCode: 'semi_auto_profile_required', + }) + } + return { roleName, roleId, serverZone } +} + +/** + * 半自动订单没有 work_orders,客户资料只能在授权页 /c/<订单号> 收集。 + * 保存后立即参与“客户填写角色 vs 平台识别角色”的比对。 + */ +export async function savePublicTaskProfile( + orderNoInput: unknown, + taskIdInput: unknown, + payload: CustomerProfileInput = {}, +) { + const orderNo = normalizeOrderNo(orderNoInput) + const taskId = normalizeId(taskIdInput) + const task = await loadTaskForOrder(orderNo, taskId) + if (task.platform !== 'huya') { + throw createHttpError('当前平台不需要填写游戏角色', { + statusCode: 409, + errorCode: 'semi_auto_profile_not_supported', + }) + } + if (task.execution_status === 'completed' || task.execution_status === 'cancelled') { + throw createHttpError('当前订单已结束,不能修改角色资料', { + statusCode: 409, + errorCode: 'semi_auto_task_closed', + }) + } + if (task.binding_status === 'confirmed') { + throw createHttpError('绑定已确认,不能修改角色资料', { + statusCode: 409, + errorCode: 'semi_auto_profile_locked', + }) + } + const profile = normalizeCustomerProfile(payload) + await withTransaction(async (client) => { + await client.query( + ` + UPDATE semi_auto_tasks + SET customer_game_role_name = $2, + customer_game_role_id = $3, + customer_game_server_zone = $4, + updated_at = NOW() + WHERE id = $1 + `, + [task.id, profile.roleName, profile.roleId, profile.serverZone], + ) + await appendTaskEvent(client, task.id, { + eventType: 'customer_profile_saved', + actorType: 'customer', + detail: profile, + }) + }) + const updated = await loadTask(task.id) + return { task: mapTask(updated) } +} + function mapLoginUpdate(session: ConnectorLoginSession) { const statusMap: Record = { verification_pending: 'waiting_login', @@ -705,8 +867,13 @@ async function updateLoginTask( options: { credentialSource?: 'qr' | 'sms'; method?: 'qr' | 'sms' } = {}, ) { const mapped = mapLoginUpdate(session) + // 虎牙登录成功还不算授权完成,必须等客户确认绑定角色;微博登录即授权。 const nextExecutionStatus: ExecutionStatus = - mapped.status === 'authenticated' ? 'waiting_operator' : task.execution_status + mapped.status === 'authenticated' + ? task.platform === 'weibo' || task.binding_status === 'confirmed' + ? 'waiting_operator' + : 'waiting_customer' + : task.execution_status const storedCredential = mapped.status === 'authenticated' && mapped.hasCredential ? task.platform === 'weibo' @@ -779,27 +946,86 @@ function mapBindingUpdate(session: ConnectorBindingSession) { return { status: statusMap[session.status] || 'failed', qrImage: String(session.qrImage || ''), + qrExpiresAt: String(session.qrExpiresAt || ''), + qrUrl: String(session.qrUrl || ''), bindGameAccount: String(session.bindGameAccount || ''), bindGameRole: String(session.bindGameRole || ''), + bindGameRoleId: String(session.bindGameRoleId || ''), bindGameChannel: String(session.bindGameChannel || ''), + hasExistingBinding: session.hasExistingBinding === true, + rebindRequested: session.rebindRequested === true, message: String(session.message || ''), } } +export type BindingRoleComparison = { + verdict: 'match' | 'mismatch' | 'unknown' + customerRoleName: string + customerRoleId: string + boundRoleName: string + boundRoleId: string + message: string +} + +function normalizeRoleText(value: unknown): string { + return String(value ?? '') + .replace(/\s+/g, '') + .toLowerCase() +} + +/** + * 客户填写角色与平台识别角色必须一致才允许确认绑定。 + * + * 两侧都有角色 ID 时以 ID 为准(截图里的“两侧角色 ID 不一致”); + * 任一侧缺 ID 时退回角色名比对;两边都取不到才判 unknown,转客服核对。 + */ +export function compareBindingRole( + task: Pick, + binding: { bindGameRole?: string; bindGameRoleId?: string }, +): BindingRoleComparison { + const customerRoleName = String(task.customer_game_role || '').trim() + const customerRoleId = String(task.customer_game_id || '').trim() + const boundRoleName = String(binding.bindGameRole || '').trim() + const rawBoundRoleId = String(binding.bindGameRoleId || '').trim() + // 虎牙 gameRole.roleId 是 40 位加密串,客户填写的是数值游戏编号; + // 平台侧可比对的是登录账号的数值 UID(huyaUid),不能拿加密串直接比对。 + const numericHuyaUid = /^\d+$/.test(String(task.huya_uid || '').trim()) + ? String(task.huya_uid).trim() + : '' + const boundRoleId = /^\d+$/.test(rawBoundRoleId) + ? rawBoundRoleId + : numericHuyaUid || rawBoundRoleId + const base = { customerRoleName, customerRoleId, boundRoleName, boundRoleId } + if (customerRoleId && boundRoleId) { + return customerRoleId === boundRoleId + ? { ...base, verdict: 'match', message: '两侧角色 ID 一致,可确认绑定' } + : { ...base, verdict: 'mismatch', message: '两侧角色 ID 不一致,无法确认绑定' } + } + if (customerRoleName && boundRoleName) { + return normalizeRoleText(customerRoleName) === normalizeRoleText(boundRoleName) + ? { ...base, verdict: 'match', message: '两侧角色名称一致,可确认绑定' } + : { ...base, verdict: 'mismatch', message: '两侧角色名称不一致,无法确认绑定' } + } + return { + ...base, + verdict: 'unknown', + message: '未获取到可核对的两侧角色信息,请联系客服核对后再确认', + } +} + async function updateBindingTask( task: TaskRow, session: ConnectorBindingSession, actorType: TaskActorType, ) { const mapped = mapBindingUpdate(session) + const comparison = compareBindingRole(task, mapped) const executionStatus: ExecutionStatus = mapped.status === 'confirmed' ? 'waiting_operator' - : mapped.status === 'failed' || mapped.status === 'expired' - ? 'failed' - : task.execution_status === 'completed' || task.execution_status === 'cancelled' - ? task.execution_status - : 'waiting_customer' + : task.execution_status === 'completed' || task.execution_status === 'cancelled' + ? task.execution_status + : 'waiting_customer' await withTransaction(async (client) => { await client.query( ` @@ -807,6 +1033,7 @@ async function updateBindingTask( SET binding_status = $2, bind_game_account = CASE WHEN $3 <> '' THEN $3 ELSE bind_game_account END, bind_game_role = CASE WHEN $4 <> '' THEN $4 ELSE bind_game_role END, + bind_game_role_id = CASE WHEN $8 <> '' THEN $8 ELSE bind_game_role_id END, bind_game_channel = CASE WHEN $5 <> '' THEN $5 ELSE bind_game_channel END, bound_at = CASE WHEN $2 IN ('role_ready', 'confirmed') THEN COALESCE(bound_at, NOW()) ELSE bound_at END, execution_status = $6, @@ -822,6 +1049,7 @@ async function updateBindingTask( mapped.bindGameChannel, executionStatus, mapped.message, + mapped.bindGameRoleId, ], ) await appendTaskEvent(client, task.id, { @@ -834,7 +1062,9 @@ async function updateBindingTask( detail: { gameAccount: mapped.bindGameAccount, gameRole: mapped.bindGameRole, + gameRoleId: mapped.bindGameRoleId, gameChannel: mapped.bindGameChannel, + verdict: comparison.verdict, message: mapped.message, }, }) @@ -842,10 +1072,16 @@ async function updateBindingTask( return { status: mapped.status, qrImage: mapped.qrImage, + qrExpiresAt: mapped.qrExpiresAt, + qrUrl: mapped.qrUrl, bindGameAccount: mapped.bindGameAccount, bindGameRole: mapped.bindGameRole, + bindGameRoleId: mapped.bindGameRoleId, bindGameChannel: mapped.bindGameChannel, + hasExistingBinding: mapped.hasExistingBinding, + rebindRequested: mapped.rebindRequested, message: mapped.message, + comparison, } } @@ -854,6 +1090,7 @@ export async function startPublicLogin(orderNoInput: unknown, taskIdInput: unkno const taskId = normalizeId(taskIdInput) await ensureSemiAutoTasksForOrder(orderNo) const task = await loadTaskForOrder(orderNo, taskId) + assertCustomerProfileReady(task) if (task.execution_status === 'completed' || task.execution_status === 'cancelled') { throw createHttpError('当前订单已结束,不能重新登录', { statusCode: 409, @@ -907,6 +1144,13 @@ export async function startPublicLogin(orderNoInput: unknown, taskIdInput: unkno UPDATE semi_auto_tasks SET connector_session_id = $2, login_status = 'qr_pending', + binding_status = 'not_started', + bind_game_account = '', + bind_game_role = '', + bind_game_role_id = '', + bind_game_channel = '', + binding_started_at = NULL, + bound_at = NULL, execution_status = 'waiting_customer', auth_started_at = COALESCE(auth_started_at, NOW()), last_error = '', @@ -1027,6 +1271,13 @@ export async function confirmPublicBinding(orderNoInput: unknown, taskIdInput: u }) } const session = await getBindingForTask(task, task.connector_session_id) + const comparison = compareBindingRole(task, session) + if (comparison.verdict === 'mismatch') { + throw createHttpError(comparison.message, { + statusCode: 409, + errorCode: 'semi_auto_binding_role_mismatch', + }) + } const binding = await updateBindingTask(task, session, 'customer') const updated = await loadTask(task.id) return { task: mapTask(updated), binding } @@ -1041,6 +1292,7 @@ export async function sendPublicHuyaSmsCode( const taskId = normalizeId(taskIdInput) const task = await loadTaskForOrder(orderNo, taskId) assertHuyaTask(task) + assertCustomerProfileReady(task) if (task.execution_status === 'completed' || task.execution_status === 'cancelled') { throw createHttpError('当前订单已结束,不能重新登录', { statusCode: 409, @@ -1190,6 +1442,7 @@ export async function loginPublicHuyaSms( const taskId = normalizeId(taskIdInput) const task = await loadTaskForOrder(orderNo, taskId) assertHuyaTask(task) + assertCustomerProfileReady(task) if (task.execution_status === 'completed' || task.execution_status === 'cancelled') { throw createHttpError('当前订单已结束,不能重新登录', { statusCode: 409, diff --git a/apps/backend/src/services/semi-auto/weibo-native/weibo-native-connector.ts b/apps/backend/src/services/semi-auto/weibo-native/weibo-native-connector.ts index e8711548..2af1a670 100644 --- a/apps/backend/src/services/semi-auto/weibo-native/weibo-native-connector.ts +++ b/apps/backend/src/services/semi-auto/weibo-native/weibo-native-connector.ts @@ -1076,8 +1076,10 @@ export class WeiboNativeConnector { status: 'confirmed', qrImage: '', qrExpiresAt: '', + qrUrl: '', bindGameAccount: account?.nickname || '', bindGameRole: account?.uid || '', + bindGameRoleId: account?.uid || '', bindGameChannel: '微博', hasExistingBinding: true, rebindRequested: false, diff --git a/apps/frontend/src/lib/http.ts b/apps/frontend/src/lib/http.ts index fb8e6802..284e0e19 100644 --- a/apps/frontend/src/lib/http.ts +++ b/apps/frontend/src/lib/http.ts @@ -138,6 +138,21 @@ function applySessionExpiryHeaders( } } +/** HTTP 状态码兜底文案:避免把英文 statusText(如 Not Found)原样抛给用户 */ +const HTTP_STATUS_MESSAGES: Record = { + 400: '请求参数有误', + 401: '登录状态已失效,请重新登录', + 403: '没有操作权限', + 404: '接口不存在,请刷新页面后重试', + 409: '数据已更新,请刷新后重试', + 422: '提交的数据不合法', + 429: '操作过于频繁,请稍后再试', + 500: '服务器开小差了,请稍后重试', + 502: '服务暂时不可用,请稍后重试', + 503: '服务维护中,请稍后重试', + 504: '请求超时,请稍后重试', +} + function resolveFallbackHttpMessage(error: unknown) { const message = String((error as { message?: string })?.message ?? '') @@ -149,6 +164,13 @@ function resolveFallbackHttpMessage(error: unknown) { return '网络连接错误' } + const status = Number((error as { response?: { status?: number } })?.response?.status || 0) + const statusMessage = status > 0 ? HTTP_STATUS_MESSAGES[status] : '' + + if (statusMessage) { + return statusMessage + } + if (typeof (error as { response?: { statusText?: string } })?.response?.statusText === 'string') { return String((error as { response: { statusText: string } }).response.statusText).trim() } diff --git a/apps/frontend/src/pages/admin/AdminSemiAutoTasksPage.tsx b/apps/frontend/src/pages/admin/AdminSemiAutoTasksPage.tsx index e367e2af..07daf332 100644 --- a/apps/frontend/src/pages/admin/AdminSemiAutoTasksPage.tsx +++ b/apps/frontend/src/pages/admin/AdminSemiAutoTasksPage.tsx @@ -54,6 +54,8 @@ const STATUS_COLORS: Record = { login_scanned: 'cyan', waiting_binding: 'gold', binding_confirm: 'orange', + binding_expired: 'red', + binding_failed: 'red', waiting_operator: 'volcano', credential_expired: 'red', processing: 'processing', @@ -67,6 +69,16 @@ const PLATFORM_LABELS: Record = { weibo: '微博', } +const BINDING_STATUS_LABELS: Record = { + not_started: '未开始', + qr_pending: '待扫码', + scanned: '已扫码', + role_ready: '待确认角色', + confirmed: '已确认', + failed: '失败', + expired: '已过期', +} + type CompleteFormValues = { note?: string externalOrderNo?: string @@ -344,6 +356,16 @@ export default function AdminSemiAutoTasksPage() { {task.displayStatus.label} {task.huyaUid ? `UID ${task.huyaUid}` : '未获取 UID'} + + {task.platform === 'huya' + ? `绑定:${BINDING_STATUS_LABELS[task.bindingStatus] || task.bindingStatus}` + : '微博登录即授权'} + + {task.platform === 'huya' && (task.bindGameRole || task.bindGameRoleId) ? ( + + {`角色:${task.bindGameRole || '-'}${task.bindGameRoleId ? `(${task.bindGameRoleId})` : '(无角色ID)'}`} + + ) : null} CK: {task.credentialStatus === 'valid' @@ -616,6 +638,24 @@ export default function AdminSemiAutoTasksPage() { {detail.task.loginStatus === 'authenticated' ? 'CK 已获取' : '等待客户登录'} + + {detail.task.platform === 'weibo' + ? '微博登录即授权' + : BINDING_STATUS_LABELS[detail.task.bindingStatus] || detail.task.bindingStatus} + + + {detail.task.bindGameRole + ? `${detail.task.bindGameRole}${detail.task.bindGameRoleId ? `(${detail.task.bindGameRoleId})` : '(无角色ID)'}` + : '-'} + + + {detail.task.customerGameRoleName + ? `${detail.task.customerGameRoleName}${detail.task.customerGameRoleId ? `(${detail.task.customerGameRoleId})` : ''}` + : '-'} + + + {detail.task.customerServerZone || '-'} + {detail.task.assignedAdminName || '未领取'} @@ -765,6 +805,7 @@ function taskNeedsCustomerReauth(task: SemiAutoTask) { function taskCanUseCredential(task: SemiAutoTask) { return ( task.loginStatus === 'authenticated' && + (task.platform === 'weibo' || task.bindingStatus === 'confirmed') && task.credentialReady && task.credentialStatus !== 'invalid' && task.credentialStatus !== 'error' diff --git a/apps/frontend/src/pages/customer-fulfillment/CustomerFulfillmentPage.tsx b/apps/frontend/src/pages/customer-fulfillment/CustomerFulfillmentPage.tsx index 3b1da320..e1212209 100644 --- a/apps/frontend/src/pages/customer-fulfillment/CustomerFulfillmentPage.tsx +++ b/apps/frontend/src/pages/customer-fulfillment/CustomerFulfillmentPage.tsx @@ -5,33 +5,47 @@ import { ReloadOutlined, SafetyCertificateOutlined, } from '@ant-design/icons' -import { App, Button, Image, Input, Spin, Tabs } from 'antd' +import { App, Alert, Button, Image, Input, Modal, Select, Space, Spin, Tabs } from 'antd' import QRCode from 'qrcode' -import { useCallback, useEffect, useMemo, useState, type ReactNode } from 'react' +import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react' import { useParams } from 'react-router' import { + confirmCustomerBinding, fetchCustomerFulfillment, loginCustomerHuyaSms, loginCustomerWeiboSms, markCustomerFulfillmentOpened, + pollCustomerBinding, pollCustomerLogin, pollCustomerWeiboQrLogin, + saveCustomerTaskProfile, sendCustomerHuyaSmsCode, sendCustomerWeiboSmsCode, + startCustomerBinding, startCustomerLogin, startCustomerWeiboQrLogin, verifyCustomerHuyaSmsChallenge, type CustomerHuyaChallengeSolution, type CustomerHuyaSmsChallenge, } from '@/services/customer-fulfillment' -import type { CustomerLoginInfo, CustomerSemiAutoTask } from '@/types/customer-fulfillment' +import type { + CustomerBindingInfo, + CustomerLoginInfo, + CustomerSemiAutoTask, +} from '@/types/customer-fulfillment' import { formatAdminDateTime } from '@/utils/admin-time' +import collectHero from '@/assets/claim/game-role-id-guide.jpg' import { runWeiboYidunChallenge } from '@/utils/weibo-yidun' import HuyaChallengeModal from './HuyaChallengeModal' const POLL_INTERVAL_MS = 2000 +const SERVER_ZONE_OPTIONS = ['苹果Q区', '苹果V区', '安卓Q区', '安卓V区'] + +/** antd v6 语义化 classNames:让区服下拉弹层用页面深色样式 */ +const SERVER_ZONE_SELECT_CLASS_NAMES = { popup: { root: 'customer-collect-dropdown' } } + export default function CustomerFulfillmentPage() { const { message } = App.useApp() const { orderNo: routeOrderNo } = useParams<{ orderNo?: string }>() @@ -43,6 +57,8 @@ export default function CustomerFulfillmentPage() { const [loginInfo, setLoginInfo] = useState(null) const [loginQrImage, setLoginQrImage] = useState('') const [loginMode, setLoginMode] = useState<'sms' | 'qr'>('sms') + // 扫码页点「改用手机号登录」时,即使登录状态仍是 qr_pending 也切回短信表单。 + const [showSmsFallback, setShowSmsFallback] = useState(false) const [mobile, setMobile] = useState('') const [smsCode, setSmsCode] = useState('') const [smsSending, setSmsSending] = useState(false) @@ -51,6 +67,21 @@ export default function CustomerFulfillmentPage() { const [smsMfaRequired, setSmsMfaRequired] = useState(false) const [huyaChallenge, setHuyaChallenge] = useState(null) const [huyaChallengeLoading, setHuyaChallengeLoading] = useState(false) + const [bindingInfo, setBindingInfo] = useState(null) + const [bindingLoading, setBindingLoading] = useState(false) + const [bindingConfirmOpen, setBindingConfirmOpen] = useState(false) + const [bindingSecondsLeft, setBindingSecondsLeft] = useState(0) + const [bindingQrImage, setBindingQrImage] = useState('') + const [profileRoleName, setProfileRoleName] = useState('') + const [profileRoleId, setProfileRoleId] = useState('') + const [profileServerZone, setProfileServerZone] = useState('') + const [profileSaving, setProfileSaving] = useState(false) + const [profileEditing, setProfileEditing] = useState(false) + const startingBindingRef = useRef(false) + const hydratingBindingRef = useRef(false) + const autoOpenedRoleRef = useRef('') + // Connector 重启或会话被回收后,绑定/确认接口会返回 huya_native_session_not_found。 + const [bindingSessionExpired, setBindingSessionExpired] = useState(false) const selectedTask = useMemo( () => tasks.find((task) => task.id === selectedTaskId) || tasks[0] || null, @@ -95,11 +126,18 @@ export default function CustomerFulfillmentPage() { useEffect(() => { if (!selectedTask) return setLoginMode('sms') + setShowSmsFallback(false) setMobile('') setSmsCode('') setSmsMfaRequired(false) setSmsCountdown(0) setHuyaChallenge(null) + setBindingInfo(null) + setBindingConfirmOpen(false) + startingBindingRef.current = false + hydratingBindingRef.current = false + autoOpenedRoleRef.current = '' + setBindingSessionExpired(false) }, [selectedTask?.id]) useEffect(() => { @@ -131,6 +169,19 @@ export default function CustomerFulfillmentPage() { setHuyaChallenge(null) }, [selectedTask?.id, selectedTask?.loginStatus]) + useEffect(() => { + if (!selectedTask) return + setProfileRoleName(selectedTask.customerGameRoleName || '') + setProfileRoleId(selectedTask.customerGameRoleId || '') + setProfileServerZone(selectedTask.customerServerZone || '') + setProfileEditing(false) + }, [ + selectedTask?.id, + selectedTask?.customerGameRoleName, + selectedTask?.customerGameRoleId, + selectedTask?.customerServerZone, + ]) + useEffect(() => { if (loginInfo?.qrImage) { setLoginQrImage(loginInfo.qrImage) @@ -178,6 +229,116 @@ export default function CustomerFulfillmentPage() { return () => window.clearInterval(timer) }, [orderNo, selectedTask?.id, selectedTask?.loginStatus, selectedTask?.platform]) + // 登录成功后自动进入绑定阶段;失败或过期时由客户点按钮重试,避免页面来回跳。 + useEffect(() => { + if (!selectedTask || !orderNo || selectedTask.platform !== 'huya') return + if (selectedTask.loginStatus !== 'authenticated') return + if (selectedTask.bindingStatus === 'confirmed') return + if (selectedTask.bindingStatus !== 'not_started' || startingBindingRef.current) return + startingBindingRef.current = true + void startCustomerBinding(orderNo, selectedTask.id) + .then((response) => { + setTasks((current) => + current.map((task) => (task.id === response.data.task.id ? response.data.task : task)), + ) + setBindingInfo(response.data.binding) + }) + .catch((error) => { + if (isHuyaSessionExpired(error)) { + setBindingSessionExpired(true) + return + } + message.error(error instanceof Error ? error.message : '创建绑定二维码失败') + }) + .finally(() => { + startingBindingRef.current = false + }) + }, [ + message, + orderNo, + selectedTask?.bindingStatus, + selectedTask?.id, + selectedTask?.loginStatus, + selectedTask?.platform, + ]) + + useEffect(() => { + if (!selectedTask || !orderNo || selectedTask.platform !== 'huya') return + if (!['qr_pending', 'scanned'].includes(selectedTask.bindingStatus)) return + const tick = async () => { + try { + const response = await pollCustomerBinding(orderNo, selectedTask.id) + setTasks((current) => + current.map((task) => (task.id === response.data.task.id ? response.data.task : task)), + ) + if (response.data.binding) setBindingInfo(response.data.binding) + } catch { + // 短暂轮询失败不打断客户页面,下一轮继续。 + } + } + const timer = window.setInterval(() => { + void tick() + }, POLL_INTERVAL_MS) + return () => window.clearInterval(timer) + }, [orderNo, selectedTask?.bindingStatus, selectedTask?.id, selectedTask?.platform]) + + // 进入 role_ready 时补一次绑定详情,保证确认弹窗能拿到两侧角色 ID。 + useEffect(() => { + if (!selectedTask || !orderNo || selectedTask.platform !== 'huya') return + if (selectedTask.bindingStatus !== 'role_ready' || bindingInfo || hydratingBindingRef.current) + return + hydratingBindingRef.current = true + void pollCustomerBinding(orderNo, selectedTask.id) + .then((response) => { + setTasks((current) => + current.map((task) => (task.id === response.data.task.id ? response.data.task : task)), + ) + if (response.data.binding) setBindingInfo(response.data.binding) + }) + .catch((error) => { + if (isHuyaSessionExpired(error)) setBindingSessionExpired(true) + }) + .finally(() => { + hydratingBindingRef.current = false + }) + }, [bindingInfo, orderNo, selectedTask?.bindingStatus, selectedTask?.id, selectedTask?.platform]) + + useEffect(() => { + if (!selectedTask || selectedTask.bindingStatus !== 'role_ready') return + if (!bindingInfo?.comparison) return + const key = `${selectedTask.id}:${bindingInfo.bindGameRoleId || ''}` + if (autoOpenedRoleRef.current === key) return + autoOpenedRoleRef.current = key + setBindingConfirmOpen(true) + }, [bindingInfo, selectedTask?.bindingStatus, selectedTask?.id]) + + useEffect(() => { + const url = bindingInfo?.qrUrl + if (!url) { + setBindingQrImage('') + return + } + void QRCode.toDataURL(url, { + width: 320, + margin: 2, + color: { dark: '#111827', light: '#ffffff' }, + }).then(setBindingQrImage) + }, [bindingInfo?.qrUrl]) + + useEffect(() => { + const expiresAt = bindingInfo?.qrExpiresAt ? new Date(bindingInfo.qrExpiresAt).getTime() : 0 + if (!expiresAt || Number.isNaN(expiresAt)) { + setBindingSecondsLeft(0) + return + } + const update = () => { + setBindingSecondsLeft(Math.max(0, Math.floor((expiresAt - Date.now()) / 1000))) + } + update() + const timer = window.setInterval(update, 1000) + return () => window.clearInterval(timer) + }, [bindingInfo?.qrExpiresAt]) + async function handleStartLogin() { if (!selectedTask) return setLoading(true) @@ -190,6 +351,7 @@ export default function CustomerFulfillmentPage() { current.map((task) => (task.id === response.data.task.id ? response.data.task : task)), ) setLoginInfo(response.data.login) + setBindingSessionExpired(false) } catch (error) { message.error(error instanceof Error ? error.message : '创建登录二维码失败') } finally { @@ -273,7 +435,7 @@ export default function CustomerFulfillmentPage() { ) setLoginInfo(response.data.login) setHuyaChallenge(null) - message.success(`${isWeibo ? '微博' : '虎牙'}登录成功,等待客服处理`) + message.success(isWeibo ? '微博登录成功,等待客服处理' : '登录成功,请继续绑定游戏角色') } catch (error) { const errorCode = (error as { errorCode?: string } | null)?.errorCode || '' if (errorCode === 'weibo_sms_mfa_required') { @@ -307,10 +469,217 @@ export default function CustomerFulfillmentPage() { } } + async function handleRefreshBinding(forceRebind: boolean) { + if (!selectedTask) return + setBindingLoading(true) + try { + const response = await startCustomerBinding(orderNo, selectedTask.id, { forceRebind }) + setTasks((current) => + current.map((task) => (task.id === response.data.task.id ? response.data.task : task)), + ) + setBindingInfo(response.data.binding) + setBindingConfirmOpen(false) + } catch (error) { + if (isHuyaSessionExpired(error)) { + setBindingSessionExpired(true) + setBindingConfirmOpen(false) + message.warning('虎牙登录会话已过期,请重新登录') + return + } + message.error(error instanceof Error ? error.message : '创建绑定二维码失败') + } finally { + setBindingLoading(false) + } + } + + async function handlePollBindingNow(openConfirm = false) { + if (!selectedTask) return + setBindingLoading(true) + try { + const response = await pollCustomerBinding(orderNo, selectedTask.id) + setTasks((current) => + current.map((task) => (task.id === response.data.task.id ? response.data.task : task)), + ) + if (response.data.binding) setBindingInfo(response.data.binding) + if (openConfirm || response.data.task.bindingStatus === 'role_ready') { + setBindingConfirmOpen(true) + } + } catch (error) { + if (isHuyaSessionExpired(error)) { + setBindingSessionExpired(true) + setBindingConfirmOpen(false) + message.warning('虎牙登录会话已过期,请重新登录') + return + } + message.error(error instanceof Error ? error.message : '刷新绑定状态失败') + } finally { + setBindingLoading(false) + } + } + + async function handleConfirmBinding() { + if (!selectedTask) return + setBindingLoading(true) + try { + const response = await confirmCustomerBinding(orderNo, selectedTask.id) + setTasks((current) => + current.map((task) => (task.id === response.data.task.id ? response.data.task : task)), + ) + setBindingInfo(response.data.binding) + setBindingConfirmOpen(false) + message.success('绑定已确认,等待客服处理') + } catch (error) { + if (isHuyaSessionExpired(error)) { + setBindingSessionExpired(true) + setBindingConfirmOpen(false) + message.warning('虎牙登录会话已过期,请重新登录') + return + } + message.error(error instanceof Error ? error.message : '确认绑定失败') + } finally { + setBindingLoading(false) + } + } + + async function handleSaveProfile() { + if (!selectedTask) return + if (!profileServerZone.trim() || !profileRoleId.trim() || !profileRoleName.trim()) { + message.warning('请完整填写区服、游戏编号和角色名') + return + } + if (!SERVER_ZONE_OPTIONS.includes(profileServerZone.trim())) { + message.warning('请选择区服') + return + } + setProfileSaving(true) + try { + const response = await saveCustomerTaskProfile(orderNo, selectedTask.id, { + roleName: profileRoleName.trim(), + roleId: profileRoleId.trim(), + serverZone: profileServerZone.trim(), + }) + setTasks((current) => + current.map((task) => (task.id === response.data.task.id ? response.data.task : task)), + ) + setProfileEditing(false) + try { + const bindingResponse = await pollCustomerBinding(orderNo, selectedTask.id) + if (bindingResponse.data.binding) setBindingInfo(bindingResponse.data.binding) + } catch { + // 绑定尚未开始时没有 binding,可忽略。 + } + message.success('角色资料已保存') + } catch (error) { + message.error(error instanceof Error ? error.message : '保存角色资料失败') + } finally { + setProfileSaving(false) + } + } + + async function handleCopyBindingLink() { + const url = bindingInfo?.qrUrl || '' + if (!url) { + message.warning('当前二维码不支持复制链接,请长按二维码保存图片') + return + } + try { + await navigator.clipboard.writeText(url) + message.success('二维码链接已复制') + } catch { + message.error('复制失败,请长按二维码保存图片') + } + } + const config = selectedTask?.semiAutoConfig || {} - const displayTitle = isWeibo ? '微博账号登录授权' : '虎牙账号登录授权' + const displayTitle = isWeibo ? '微博账号登录授权' : '绑定游戏角色' const loginQrVisible = - selectedTask && ['qr_pending', 'scanned'].includes(selectedTask.loginStatus) + Boolean(selectedTask) && ['qr_pending', 'scanned'].includes(selectedTask.loginStatus) + const showBindingStage = Boolean( + selectedTask && + selectedTask.platform === 'huya' && + selectedTask.loginStatus === 'authenticated' && + selectedTask.bindingStatus !== 'confirmed', + ) + const bindingQrVisible = ['not_started', 'qr_pending', 'scanned'].includes( + selectedTask?.bindingStatus || '', + ) + const bindingComparison = bindingInfo?.comparison || null + const bindingRoleId = bindingInfo?.bindGameRoleId || selectedTask?.bindGameRoleId || '' + // 虎牙 gameRole.roleId 是加密串,客户侧统一展示数值 UID(huyaUid)。 + const bindingPendingUid = (() => { + const comparisonId = String(bindingComparison?.boundRoleId || '').trim() + if (/^\d+$/.test(comparisonId)) return comparisonId + const huyaUid = String(selectedTask?.huyaUid || '').trim() + return /^\d+$/.test(huyaUid) ? huyaUid : comparisonId + })() + const bindingRoleName = bindingInfo?.bindGameRole || selectedTask?.bindGameRole || '' + const showProfileForm = showBindingStage && profileEditing + const bindingCustomerReady = Boolean( + bindingComparison?.customerRoleId || bindingComparison?.customerRoleName, + ) + const needsProfileCollection = Boolean( + selectedTask && + selectedTask.platform === 'huya' && + selectedTask.executionStatus !== 'completed' && + selectedTask.bindingStatus !== 'confirmed' && + (!selectedTask.customerServerZone || + !selectedTask.customerGameRoleId || + !selectedTask.customerGameRoleName), + ) + + const huyaLoginForm = ( +
+

请使用你的「虎牙」账号登录

+
+ setMobile(event.target.value)} + placeholder="请输入号码" + inputMode="numeric" + maxLength={11} + /> + +
+ setSmsCode(event.target.value)} + placeholder="6 位验证码" + maxLength={8} + inputMode="numeric" + onPressEnter={() => void handleLoginSms()} + /> + + +
+ ) if (loading) { return ( @@ -337,7 +706,7 @@ export default function CustomerFulfillmentPage() { if (selectedTask?.executionStatus === 'completed') { return ( - +
@@ -360,6 +729,17 @@ export default function CustomerFulfillmentPage() { ) } + if (needsProfileCollection && selectedTask) { + return ( + + setTasks((current) => current.map((item) => (item.id === task.id ? task : item))) + } + /> + ) + } + return (
@@ -383,98 +763,103 @@ export default function CustomerFulfillmentPage() {
) : null} - + {selectedTask?.loginStatus === 'waiting_login' || selectedTask?.loginStatus === 'failed' || - selectedTask?.loginStatus === 'expired' ? ( + selectedTask?.loginStatus === 'expired' || + (showSmsFallback && selectedTask?.loginStatus === 'qr_pending') ? (
- setLoginMode(key as 'sms' | 'qr')} - items={[ - { - key: 'sms', - label: '手机号登录', - children: ( -
-
- +86 - setMobile(event.target.value)} - placeholder={`请输入${isHuya ? '虎牙' : '微博'}绑定手机号`} - maxLength={11} - inputMode="numeric" - /> - -
- {isWeibo && smsMfaRequired ? ( -
- 请在安全验证弹窗中完成验证,通过后会继续发送短信验证码。 + {isWeibo ? ( + setLoginMode(key as 'sms' | 'qr')} + items={[ + { + key: 'sms', + label: '手机号登录', + children: ( +
+
+ +86 + setMobile(event.target.value)} + placeholder={`请输入${isHuya ? '虎牙' : '微博'}绑定手机号`} + maxLength={11} + inputMode="numeric" + /> +
- ) : null} -
- setSmsCode(event.target.value)} - placeholder="请输入短信验证码" - maxLength={8} - prefix={} - onPressEnter={() => void handleLoginSms()} - /> + {isWeibo && smsMfaRequired ? ( +
+ 请在安全验证弹窗中完成验证,通过后会继续发送短信验证码。 +
+ ) : null} +
+ setSmsCode(event.target.value)} + placeholder="请输入短信验证码" + maxLength={8} + prefix={} + onPressEnter={() => void handleLoginSms()} + /> + +
+ {isWeibo ? ( + + 如安全验证弹窗未出现,请检查浏览器是否拦截脚本。 + + ) : null} +
+ ), + }, + { + key: 'qr', + label: '扫码登录', + children: ( +
+

+ {config.loginInstructions || + `点击下方按钮后,使用${isHuya ? '虎牙' : '微博'} App 扫码并确认登录。`} +

- {isWeibo ? ( - - 如安全验证弹窗未出现,请检查浏览器是否拦截脚本。 - - ) : null} -
- ), - }, - { - key: 'qr', - label: '扫码登录', - children: ( -
-

- {config.loginInstructions || - `点击下方按钮后,使用${isHuya ? '虎牙' : '微博'} App 扫码并确认登录。`} -

- -
- ), - }, - ]} - /> + ), + }, + ]} + /> + ) : ( + huyaLoginForm + )}
) : null} - {loginQrVisible ? ( + {loginQrVisible && !showSmsFallback ? (
@@ -508,16 +893,226 @@ export default function CustomerFulfillmentPage() { ) : null} + {isWeibo ? null : ( + + )}
) : null} + {showBindingStage ? ( +
+
+

+ 绑定信息 (已登录虎牙账号) +

+
+ 登录账号 + + {bindingInfo?.bindGameAccount || selectedTask.bindGameAccount || '未获取'} + +
+
+ 绑定角色 + {bindingRoleName || '未识别到角色'} +
+
+ + {bindingSessionExpired ? ( + { + setBindingSessionExpired(false) + void handleStartLogin() + }} + > + 重新登录 + + } + /> + ) : null} + + {!bindingSessionExpired ? ( + !bindingRoleId ? ( +
+ 未获取到已绑定的角色ID,请重新扫码绑定 +
+ ) : ( +
+ 登录成功,请继续扫码绑定游戏角色 +
+ ) + ) : null} + + {showProfileForm && !bindingSessionExpired ? ( +
+

修改资料后会重新核对平台识别角色。

+ + setProfileRoleId(event.target.value)} + placeholder="游戏编号 / 角色 ID(必填,纯数字)" + maxLength={64} + inputMode="numeric" + /> + setProfileRoleName(event.target.value)} + placeholder="角色名(必填)" + maxLength={100} + /> + + +
+ ) : null} + + {bindingQrVisible && !bindingSessionExpired ? ( +
+

游戏角色绑定二维码

+ {bindingQrImage || bindingInfo?.qrImage ? ( + 游戏角色绑定二维码 + ) : ( +
+ + 正在生成绑定二维码... +
+ )} +

请使用微信APP扫码进行游戏角色绑定

+

手机端可长按二维码或截图保存图片再识别

+

+ {selectedTask?.bindingStatus === 'scanned' + ? '已扫码,等待角色生效' + : `建议 ${formatCountdown(bindingSecondsLeft)} 内完成扫码`} +

+
+ + +
+ +
+ ) : null} + + {selectedTask?.bindingStatus === 'expired' ? ( + void handleRefreshBinding(false)}> + 重新获取 + + } + /> + ) : null} + + {selectedTask?.bindingStatus === 'failed' ? ( + void handleRefreshBinding(false)}> + 重新获取 + + } + /> + ) : null} + + {selectedTask?.bindingStatus === 'role_ready' && !bindingSessionExpired ? ( + + + {!bindingRoleId ? ( + + ) : null} + + + + + + ) : null} +
+ ) : null} + {selectedTask?.loginStatus === 'authenticated' && + (isWeibo || selectedTask.bindingStatus === 'confirmed') && selectedTask.executionStatus !== 'completed' ? (
@@ -535,6 +1130,84 @@ export default function CustomerFulfillmentPage() {
) : null} + { + if (!bindingLoading) setBindingConfirmOpen(false) + }} + footer={ +
+
+ + +
+ {bindingComparison?.verdict === 'mismatch' ? ( +

两侧角色ID不一致,无法确认绑定

+ ) : bindingComparison?.verdict === 'unknown' ? ( +

两侧角色信息不完整,请联系客服核实

+ ) : null} +
+ } + destroyOnClose + > + +

检测到待确认的绑定角色,请核对两侧角色是否一致。

+
+
+
+ 您填写的角色 + +
+ {bindingComparison?.customerRoleName || '未填写'} + {bindingComparison?.customerRoleId || '未填写角色ID'} +
+
+
+ 待确认角色 + +
+ {bindingComparison?.boundRoleName || '未识别到角色'} + {bindingPendingUid || '未获取到角色ID'} +
+
+
+
+ void handleVerifyHuyaChallenge(solution)} /> - + {isWeibo ? : null}
) @@ -568,60 +1241,149 @@ function CustomerAuthFrame(input: {
-
- {input.platform === 'weibo' - ? '温馨提示:未成年人禁止下单' - : '温馨提示:请使用本人账号完成授权'} -
+ {input.platform === 'weibo' ? ( +
温馨提示:未成年人禁止下单
+ ) : null}
{input.children}
) } -function CustomerTaskFacts(input: { task: CustomerSemiAutoTask | null }) { - const task = input.task - if (!task) return null - const statusTone = - task.displayStatus.key === 'credential_expired' || task.displayStatus.key === 'failed' - ? 'is-danger' - : task.loginStatus === 'authenticated' - ? 'is-success' - : 'is-pending' - const showAccountDetails = ['authenticated', 'scanned'].includes(task.loginStatus) +function CustomerOrderCard({ task }: { task: CustomerSemiAutoTask }) { + const zone = task.customerServerZone + ? /区$/.test(task.customerServerZone) + ? task.customerServerZone + : `${task.customerServerZone}区` + : '' + const roleText = [zone, task.customerGameRoleName].filter(Boolean).join('-') || '未填写' return ( -
+
+

订单信息

- 订单号 - {task.orderNo} + 游戏名称 + 和平精英
- 商品 - - {task.productName || task.skuName} × {task.quantity} - + 角色名称 + {roleText}
- 平台 - {task.platformLabel || task.platform} + 购买物品 + {task.productName || task.skuName}
- {showAccountDetails && task.huyaUid ? ( -
- 平台账号 ID - {task.huyaUid} +
+ ) +} + +function CustomerCollectStep(input: { + task: CustomerSemiAutoTask + onSaved: (task: CustomerSemiAutoTask) => void +}) { + const { message } = App.useApp() + const [serverZone, setServerZone] = useState(input.task.customerServerZone || '') + const [roleId, setRoleId] = useState(input.task.customerGameRoleId || '') + const [roleName, setRoleName] = useState(input.task.customerGameRoleName || '') + const [saving, setSaving] = useState(false) + + async function submit() { + if (!serverZone.trim() || !roleId.trim() || !roleName.trim()) { + message.warning('请完整填写区服、游戏编号和角色名') + return + } + if (!SERVER_ZONE_OPTIONS.includes(serverZone.trim())) { + message.warning('请选择区服') + return + } + if (!/^\d+$/.test(roleId.trim())) { + message.warning('游戏编号只能是数字') + return + } + setSaving(true) + try { + const response = await saveCustomerTaskProfile(input.task.orderNo, input.task.id, { + roleName: roleName.trim(), + roleId: roleId.trim(), + serverZone: serverZone.trim(), + }) + input.onSaved(response.data.task) + message.success('资料已提交') + } catch (error) { + message.error(error instanceof Error ? error.message : '提交资料失败') + } finally { + setSaving(false) + } + } + + return ( +
+
+ +
+

温馨提示:未成年人禁止下单

+
+
+ +
{input.task.orderNo}
+ +
+
+ 商品 + {input.task.productName || input.task.skuName} +
+
+ 游戏 + 和平精英 +
+

填完资料记得截图联系客服。

- ) : null} - {showAccountDetails && task.platform === 'weibo' && task.platformNickname ? ( -
- 账号昵称 - {task.platformNickname} -
- ) : null} -
- 状态 - - {task.displayStatus.label} - + + + setRoleId(event.target.value)} + placeholder="请输入游戏编号" + maxLength={64} + inputMode="numeric" + /> + + + setRoleName(event.target.value)} + placeholder="请输入角色名" + maxLength={100} + /> + +
) @@ -635,8 +1397,20 @@ function CustomerPrivacyNote() { ) } +/** Connector 重启或会话被回收时后端返回该错误码,需要引导客户重新登录。 */ +function isHuyaSessionExpired(error: unknown) { + return (error as { errorCode?: string } | null)?.errorCode === 'huya_native_session_not_found' +} + function isValidMainlandMobile(value: string) { const digits = value.replace(/\D/g, '') if (!digits) return false return /^1\d{10}$/.test(digits) } + +function formatCountdown(seconds: number) { + const safe = Math.max(0, Math.floor(seconds)) + const minutes = Math.floor(safe / 60) + const rest = safe % 60 + return `${minutes}:${String(rest).padStart(2, '0')}` +} diff --git a/apps/frontend/src/services/customer-fulfillment.ts b/apps/frontend/src/services/customer-fulfillment.ts index b160b86f..036843a2 100644 --- a/apps/frontend/src/services/customer-fulfillment.ts +++ b/apps/frontend/src/services/customer-fulfillment.ts @@ -1,5 +1,9 @@ import { apiGet, apiPost } from '@/lib/http' -import type { CustomerLoginInfo, CustomerSemiAutoTask } from '@/types/customer-fulfillment' +import type { + CustomerBindingInfo, + CustomerLoginInfo, + CustomerSemiAutoTask, +} from '@/types/customer-fulfillment' export function fetchCustomerFulfillment(orderNo: string) { return apiGet( @@ -14,6 +18,17 @@ export function markCustomerFulfillmentOpened(orderNo: string, taskId: number) { ) } +export function saveCustomerTaskProfile( + orderNo: string, + taskId: number, + input: { roleName: string; roleId: string; serverZone: string }, +) { + return apiPost<{ task: CustomerSemiAutoTask }>( + `/api/v1/customer-fulfillment/${encodeURIComponent(orderNo)}/tasks/${taskId}/profile`, + input, + ) +} + export function startCustomerLogin(orderNo: string, taskId: number) { return apiPost<{ task: CustomerSemiAutoTask; login: CustomerLoginInfo }>( `/api/v1/customer-fulfillment/${encodeURIComponent(orderNo)}/tasks/${taskId}/login/start`, @@ -27,6 +42,30 @@ export function pollCustomerLogin(orderNo: string, taskId: number) { ) } +export function startCustomerBinding( + orderNo: string, + taskId: number, + options: { forceRebind?: boolean } = {}, +) { + return apiPost<{ task: CustomerSemiAutoTask; binding: CustomerBindingInfo }>( + `/api/v1/customer-fulfillment/${encodeURIComponent(orderNo)}/tasks/${taskId}/binding/start`, + options.forceRebind ? { forceRebind: true } : {}, + ) +} + +export function pollCustomerBinding(orderNo: string, taskId: number) { + return apiGet<{ task: CustomerSemiAutoTask; binding: CustomerBindingInfo | null }>( + `/api/v1/customer-fulfillment/${encodeURIComponent(orderNo)}/tasks/${taskId}/binding/status`, + ) +} + +export function confirmCustomerBinding(orderNo: string, taskId: number) { + return apiPost<{ task: CustomerSemiAutoTask; binding: CustomerBindingInfo }>( + `/api/v1/customer-fulfillment/${encodeURIComponent(orderNo)}/tasks/${taskId}/binding/confirm`, + {}, + ) +} + type CustomerHuyaChallengeBase = { image: string width: number diff --git a/apps/frontend/src/styles/client.css b/apps/frontend/src/styles/client.css index ede4a554..7fa58962 100644 --- a/apps/frontend/src/styles/client.css +++ b/apps/frontend/src/styles/client.css @@ -1437,54 +1437,47 @@ } .customer-auth-page { - --auth-accent: #ff8a00; - --auth-accent-hover: #ffa12f; - --auth-panel: #07142e; - --auth-panel-soft: #0d1d3d; - --auth-line: rgba(255, 255, 255, 0.11); - --auth-text: #f8fafc; - --auth-muted: #a6b0c3; + --auth-accent: #2f6fed; + --auth-accent-hover: #4a83ff; + --auth-panel: #232936; + --auth-panel-soft: #2a3140; + --auth-line: rgba(255, 255, 255, 0.08); + --auth-text: #f5f7fa; + --auth-muted: #9aa3b2; min-height: 100vh; display: flex; justify-content: center; overflow-x: hidden; - padding: clamp(20px, 4vw, 48px) 16px; + padding: 0; color: var(--auth-text); - background: #202124; + background: #232936; } .customer-auth-shell { - width: min(760px, 100%); + width: min(560px, 100%); min-width: 0; - align-self: flex-start; + align-self: stretch; overflow: hidden; - border: 1px solid rgba(255, 255, 255, 0.08); - border-radius: 8px; - background: var(--auth-panel); - box-shadow: 0 28px 70px rgba(0, 0, 0, 0.34); + border: none; + border-radius: 0; + background: transparent; + box-shadow: none; } .customer-auth-hero { - min-height: 176px; + min-height: auto; display: flex; align-items: center; - padding: 34px 38px; - background-image: - linear-gradient( - 90deg, - rgba(3, 18, 55, 0.97) 0%, - rgba(5, 23, 65, 0.83) 48%, - rgba(7, 20, 43, 0.45) 100% - ), - url('https://game.gtimg.cn/images/gp/web201908/inside_kv.jpg'); - background-position: center; - background-size: cover; + justify-content: center; + padding: 38px 16px 10px; + background: none; } .customer-auth-brand { display: flex; align-items: center; - gap: 18px; + justify-content: center; + gap: 0; min-width: 0; } @@ -1505,28 +1498,30 @@ .customer-auth-brand h1 { margin: 0; color: #fff; - font-size: clamp(18px, 2.3vw, 22px); - line-height: 1.3; - font-weight: 600; + font-size: 20px; + line-height: 1.4; + font-weight: 700; letter-spacing: 0; - white-space: nowrap; + text-align: center; + white-space: normal; overflow-wrap: anywhere; } .customer-auth-warning { - padding: 19px 24px; + padding: 6px 16px 10px; color: #ff6975; text-align: center; - font-size: 20px; - font-weight: 700; - background: #06122b; - border-bottom: 1px solid var(--auth-line); + font-size: 14px; + font-weight: 600; + background: transparent; + border-bottom: none; } .customer-auth-main { min-width: 0; + padding-bottom: 24px; color: var(--auth-text); - background: var(--auth-panel); + background: transparent; } .customer-auth-content-stack { @@ -1605,8 +1600,8 @@ .customer-auth-section { min-width: 0; - padding: 28px 26px 30px; - border-bottom: 1px solid var(--auth-line); + padding: 16px; + border-bottom: none; } .customer-auth-section-heading { @@ -1616,24 +1611,24 @@ } .customer-auth-section-icon { - width: 42px; - height: 42px; + width: 36px; + height: 36px; flex: none; display: grid; place-items: center; border: 1px solid rgba(255, 255, 255, 0.15); - border-radius: 7px; + border-radius: 8px; color: var(--auth-accent); - font-size: 22px; + font-size: 18px; background: rgba(255, 255, 255, 0.035); } .customer-auth-section-heading h2, .customer-auth-state h2 { - margin: 0 0 8px; + margin: 0 0 6px; color: #fff; - font-size: 23px; - line-height: 1.35; + font-size: 18px; + line-height: 1.4; font-weight: 700; } @@ -2081,6 +2076,607 @@ font-size: 12px; } +.customer-auth-binding { + display: flex; + flex-direction: column; + gap: 16px; +} + +.customer-auth-binding-tip { + color: #ffb454; + font-size: 13px; +} + +.customer-auth-profile, +.customer-auth-profile-summary { + padding: 14px; + border: 1px solid rgba(255, 255, 255, 0.14); + border-radius: 6px; + background: rgba(255, 255, 255, 0.04); +} + +.customer-auth-profile > p { + margin: 0 0 10px; + color: var(--auth-muted); + font-size: 13px; + line-height: 1.6; +} + +.customer-auth-profile-summary { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 10px; +} + +.customer-auth-profile-summary span { + color: var(--auth-muted); + font-size: 13px; +} + +.customer-auth-profile-summary strong { + color: #fff; + font-size: 15px; +} + +.customer-auth-profile-summary em { + color: var(--auth-muted); + font-style: normal; + font-size: 13px; +} + +/* 客户资料页(图 1) */ +.customer-collect-page { + min-height: 100vh; + background: #0b1220; + color: #e5e7eb; +} + +.customer-collect-hero { + position: relative; + height: 210px; + overflow: hidden; +} + +.customer-collect-hero-image { + width: 100%; + height: 100%; + object-fit: cover; + object-position: left center; + filter: saturate(0.9) brightness(0.72); +} + +.customer-collect-hero-mask { + position: absolute; + inset: 0; + background: linear-gradient(180deg, rgba(11, 18, 32, 0.1), rgba(11, 18, 32, 0.96)); +} + +.customer-collect-warning { + position: absolute; + left: 0; + right: 0; + bottom: 22px; + margin: 0; + text-align: center; + color: #f87171; + font-size: 17px; + font-weight: 600; +} + +.customer-collect-body { + max-width: 560px; + margin: 0 auto; + padding: 24px 20px 48px; + display: flex; + flex-direction: column; + gap: 12px; +} + +.customer-collect-label { + margin-top: 8px; + color: #e5e7eb; + font-size: 15px; + line-height: 1.4; +} + +.customer-collect-label span { + color: #f87171; +} + +.customer-collect-readonly { + height: 56px; + display: flex; + align-items: center; + padding: 0 16px; + border-radius: 12px; + background: #1b2436; + border: 1px solid #26344d; + color: #94a3b8; + font-size: 15px; +} + +.customer-collect-card { + margin: 10px 0; + padding: 16px; + border-radius: 12px; + border: 1px solid #1e2f4a; + background: #141d30; + display: flex; + flex-direction: column; + gap: 12px; +} + +.customer-collect-card > div { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 12px; + color: #cbd5e1; + font-size: 15px; + line-height: 1.5; +} + +.customer-collect-card > div > span { + flex: 0 0 auto; + white-space: nowrap; +} + +.customer-collect-card > div strong { + flex: 1 1 auto; + min-width: 0; + color: #fff; + font-weight: 600; + text-align: right; + overflow-wrap: anywhere; +} + +.customer-collect-card > p { + margin: 6px 0 0; + color: #fbbf24; + font-size: 13px; + text-align: center; +} + +.customer-collect-input.ant-input { + height: 56px; + border-radius: 12px; + background: #1b2436; + border-color: #26344d; + color: #fff; +} + +.customer-collect-input.ant-input::placeholder { + color: #64748b; +} + +.customer-collect-select.ant-select { + width: 100%; + height: 56px; + padding-inline: 16px; + align-items: center; + font-size: 15px; + border-radius: 12px; + border: 1px solid #26344d; + background: #1b2436; + color: #fff; + --ant-select-height: 56px; + --ant-select-border-radius: 12px; + --ant-select-border-color: #26344d; + --ant-select-background-color: #1b2436; + --ant-select-color: #fff; + --ant-select-hover-border-color: #3b4d6b; + --ant-select-active-border-color: #2563eb; + --ant-select-active-outline-color: rgba(37, 99, 235, 0.2); +} + +.customer-collect-select.ant-select:hover { + border-color: #3b4d6b; +} + +.customer-collect-select.ant-select.ant-select-focused { + border-color: #2563eb; + box-shadow: 0 0 0 2px rgba(37, 99, 235, 0.2); +} + +.customer-collect-select .ant-select-content { + align-items: center; +} + +.customer-collect-select .ant-select-selection-item { + color: #fff; + line-height: 1.5; +} + +.customer-collect-select .ant-select-placeholder { + color: #64748b; +} + +.customer-collect-select .ant-select-suffix { + color: #94a3b8; +} + +.ant-select-dropdown.customer-collect-dropdown { + padding: 6px; + border-radius: 12px; + background: #141d30; + box-shadow: 0 14px 34px rgba(2, 6, 23, 0.55); + --ant-select-option-active-bg: #1b2436; + --ant-select-option-selected-bg: #1e3a8a; + --ant-select-option-selected-color: #fff; +} + +.customer-collect-dropdown .ant-select-item { + border-radius: 8px; + color: #cbd5e1; +} + +.customer-collect-dropdown .ant-select-item-option-active { + background: #1b2436 !important; + color: #fff; +} + +.customer-collect-dropdown .ant-select-item-option-selected { + background: #1e3a8a !important; + color: #fff; + font-weight: 600; +} + +.customer-collect-page .customer-collect-submit.ant-btn { + height: 56px; + margin-top: 14px; + border-radius: 14px; + font-size: 17px; + font-weight: 600; + --ant-btn-bg-color: #2563eb; + --ant-btn-bg-color-hover: #1d4ed8; + --ant-btn-bg-color-active: #1e40af; + --ant-btn-text-color: #fff; + --ant-btn-text-color-hover: #fff; + --ant-btn-text-color-active: #fff; + --ant-btn-border-color: #2563eb; + --ant-btn-border-color-hover: #1d4ed8; + --ant-btn-border-color-active: #1e40af; + background: #2563eb !important; + border-color: #2563eb !important; + color: #fff !important; +} + +.customer-collect-page .customer-collect-submit.ant-btn:hover, +.customer-collect-page .customer-collect-submit.ant-btn:focus-visible { + background: #1d4ed8 !important; + border-color: #1d4ed8 !important; + color: #fff !important; +} + +/* 登录与绑定页(图 2-10) */ +.customer-login-form { + display: flex; + flex-direction: column; + gap: 12px; +} + +.customer-login-hint { + margin: 0 0 2px; + color: #d5dae3; + font-size: 16px; + line-height: 1.5; +} + +.customer-login-mobile-row { + display: flex; + align-items: stretch; + gap: 12px; +} + +.customer-login-mobile.ant-input { + flex: 1; + min-width: 0; + height: 52px; + padding: 0 16px; + border-radius: 8px; + border-color: #3a4150; + background: #1b2130; + color: #fff; + font-size: 15px; +} + +.customer-login-mobile.ant-input::placeholder { + color: #6b7482; +} + +.customer-login-code-button.ant-btn { + flex: none; + width: 118px; + height: 52px; + border-radius: 8px; + background: #3b82f6 !important; + border-color: #3b82f6 !important; + color: #fff !important; + font-size: 16px; +} + +.customer-login-code-input.ant-input { + height: 52px; + border-radius: 8px; + border-color: #3a4150; + background: #1b2130; + color: #fff; + text-align: center; + font-size: 15px; + letter-spacing: 6px; +} + +.customer-login-code-input.ant-input::placeholder { + color: #6b7482; +} + +.customer-login-submit.ant-btn { + height: 52px; + border-radius: 8px; + background: #0aa53a !important; + border-color: #0aa53a !important; + color: #fff !important; + font-size: 18px; + font-weight: 700; +} + +.customer-login-alt.ant-btn { + height: 52px; + border-radius: 8px; + background: transparent !important; + border-color: #3a4150 !important; + color: #cbd5e1 !important; + font-size: 16px; +} + +.customer-order-card { + margin: 10px 16px 0; + padding: 16px; + border: 1px solid #3a4150; + border-radius: 12px; + background: #212733; + display: flex; + flex-direction: column; + gap: 10px; +} + +.customer-order-card h3 { + margin: 0 0 4px; + color: #94a3b8; + font-size: 13px; + font-weight: 500; +} + +.customer-order-card > div { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 12px; + color: #cbd5e1; + font-size: 14px; + line-height: 1.5; +} + +.customer-order-card > div > span { + flex: 0 0 auto; + white-space: nowrap; + color: #9aa3b2; +} + +.customer-order-card > div strong { + flex: 1 1 auto; + min-width: 0; + color: #fff; + text-align: right; + overflow-wrap: anywhere; +} + +.customer-binding-stage { + display: flex; + flex-direction: column; + gap: 14px; + padding: 16px; +} + +.customer-binding-info { + padding: 16px; + border: 1px solid #3a4150; + border-radius: 12px; + background: #212733; + display: flex; + flex-direction: column; + gap: 10px; +} + +.customer-binding-info h3 { + margin: 0 0 4px; + color: #9aa3b2; + font-size: 13px; + font-weight: 500; +} + +.customer-binding-info h3 small { + color: #64748b; + font-weight: 400; +} + +.customer-binding-info > div { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 12px; + color: #cbd5e1; + font-size: 14px; + line-height: 1.5; +} + +.customer-binding-info > div > span { + flex: 0 0 auto; + white-space: nowrap; +} + +.customer-binding-info > div strong { + flex: 1 1 auto; + min-width: 0; + color: #fff; + text-align: right; + overflow-wrap: anywhere; +} + +.customer-binding-alert { + padding: 12px 14px; + border-radius: 8px; + border: 1px solid transparent; + font-size: 14px; +} + +.customer-binding-alert.is-warning { + color: #fbbf24; + border-color: #78350f; + background: rgba(120, 53, 15, 0.25); +} + +.customer-binding-alert.is-info { + color: #93c5fd; + border-color: #1e3a8a; + background: rgba(30, 58, 138, 0.3); +} + +.customer-binding-qr-card { + padding: 18px; + border-radius: 12px; + background: #fff; + color: #111827; + display: flex; + flex-direction: column; + align-items: center; + gap: 10px; +} + +.customer-binding-qr-card h3 { + margin: 0; + color: #6b7280; + font-size: 14px; + font-weight: 500; +} + +.customer-binding-qr-hint { + margin: 0; + color: #6b7280; + font-size: 13px; +} + +.customer-binding-qr-tip { + margin: 0; + color: #f59e0b; + font-size: 13px; +} + +.customer-binding-qr-countdown { + margin: 0; + color: #6b7280; + font-size: 13px; +} + +.customer-binding-qr-actions { + width: 100%; + margin-top: 4px; + display: grid; + grid-template-columns: 1fr 1fr; + gap: 10px; +} + +.customer-binding-qr-actions .ant-btn { + height: 40px; + border-radius: 8px; +} + +.customer-binding-next.ant-btn { + width: 100%; + height: 46px; + margin-top: 6px; + border-radius: 8px; + background: #2563eb !important; + border-color: #2563eb !important; + color: #fff !important; + font-weight: 600; +} + +.customer-binding-modal-footer { + display: flex; + flex-direction: column; + gap: 10px; +} + +.customer-binding-modal-actions { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 12px; +} + +.customer-binding-modal-actions .ant-btn { + height: 42px; + border-radius: 8px; +} + +.customer-binding-modal-error { + margin: 0; + color: #dc2626; + font-size: 13px; + text-align: center; +} + +.customer-binding-modal-warning { + margin: 0; + color: #d97706; + font-size: 13px; + text-align: center; +} + +.customer-binding-compare { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 12px; +} + +.customer-binding-compare-side { + display: flex; + flex-direction: column; + gap: 6px; + padding: 14px; + border: 1px solid rgba(15, 23, 42, 0.12); + border-radius: 6px; + background: rgba(15, 23, 42, 0.04); +} + +.customer-binding-compare-head { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + color: #64748b; + font-size: 13px; +} + +.customer-binding-compare-side strong { + color: #0f172a; + font-size: 16px; + word-break: break-all; +} + +.customer-binding-compare-side em { + color: #64748b; + font-style: normal; + font-size: 13px; +} + +@media (max-width: 480px) { + .customer-binding-compare { + grid-template-columns: minmax(0, 1fr); + } +} + .customer-auth-button-stack { width: min(100%, 580px); display: flex; @@ -2190,49 +2786,43 @@ @media (max-width: 640px) { .customer-auth-page { - height: 100dvh; - min-height: 0; - overflow: hidden; + height: auto; + min-height: 100vh; + overflow: visible; padding: 0; background: var(--auth-panel); } .customer-auth-shell { width: 100%; - height: 100%; - min-height: 0; - display: flex; - flex-direction: column; + height: auto; + display: block; border: 0; border-radius: 0; box-shadow: none; } .customer-auth-hero { - min-height: 116px; - flex: none; - padding: 20px 22px; - background-position: 58% center; + min-height: auto; + padding: 38px 16px 10px; + background: none; } .customer-auth-brand h1 { - font-size: 18px; + font-size: 20px; } .customer-auth-warning { - flex: none; - padding: 12px 14px; - font-size: 16px; + padding: 6px 16px 10px; + font-size: 14px; } .customer-auth-main { - flex: 1; - min-height: 0; - overflow: hidden; + overflow: visible; } .customer-auth-content-stack { - height: 100%; + height: auto; min-height: 0; } @@ -2257,7 +2847,7 @@ } .customer-auth-section { - padding: 14px 16px 10px; + padding: 16px; } .customer-auth-section-copy h2, diff --git a/apps/frontend/src/types/admin/semi-auto.ts b/apps/frontend/src/types/admin/semi-auto.ts index 1d9fbfdf..7ec570e6 100644 --- a/apps/frontend/src/types/admin/semi-auto.ts +++ b/apps/frontend/src/types/admin/semi-auto.ts @@ -13,6 +13,7 @@ export type SemiAutoTask = { platform: SemiAutoPlatform platformLabel: string loginStatus: string + bindingStatus: string executionStatus: string connectorMode: 'embedded' | 'external' | 'mock' displayStatus: SemiAutoDisplayStatus @@ -23,6 +24,13 @@ export type SemiAutoTask = { credentialUpdatedAt: string | null huyaUid: string platformNickname: string + bindGameAccount: string + bindGameRole: string + bindGameRoleId: string + bindGameChannel: string + customerGameRoleId: string + customerGameRoleName: string + customerServerZone: string targetQuantity: number completedQuantity: number assignedAdminUserId: number | null diff --git a/apps/frontend/src/types/customer-fulfillment.ts b/apps/frontend/src/types/customer-fulfillment.ts index 842f423a..1e3fbf20 100644 --- a/apps/frontend/src/types/customer-fulfillment.ts +++ b/apps/frontend/src/types/customer-fulfillment.ts @@ -1,3 +1,12 @@ +export type CustomerBindingComparison = { + verdict: 'match' | 'mismatch' | 'unknown' + customerRoleName: string + customerRoleId: string + boundRoleName: string + boundRoleId: string + message: string +} + export type CustomerSemiAutoTask = { id: number platform: 'huya' | 'weibo' @@ -8,10 +17,18 @@ export type CustomerSemiAutoTask = { skuCode: string quantity: number loginStatus: string + bindingStatus: string executionStatus: string displayStatus: { key: string; label: string } huyaUid: string platformNickname: string + bindGameAccount: string + bindGameRole: string + bindGameRoleId: string + bindGameChannel: string + customerGameRoleId: string + customerGameRoleName: string + customerServerZone: string completedAt: string | null completionNote: string semiAutoConfig: { @@ -28,3 +45,18 @@ export type CustomerLoginInfo = { expiresAt: string message: string } + +export type CustomerBindingInfo = { + status: string + qrImage: string + qrExpiresAt: string + qrUrl: string + bindGameAccount: string + bindGameRole: string + bindGameRoleId: string + bindGameChannel: string + hasExistingBinding: boolean + rebindRequested: boolean + message: string + comparison: CustomerBindingComparison +} From 19367bdfdfb2d1bead7e5174998f537685c666cf Mon Sep 17 00:00:00 2001 From: zhaoxing <2558691827@qq.com> Date: Mon, 16 Nov 2026 11:07:47 +0800 Subject: [PATCH 02/15] =?UTF-8?q?fix(semi-auto):=20=E5=AE=A2=E6=88=B7?= =?UTF-8?q?=E7=99=BB=E5=BD=95=E9=A1=B5=E5=88=B7=E6=96=B0=E9=BB=98=E8=AE=A4?= =?UTF-8?q?=E6=89=8B=E6=9C=BA=E5=8F=B7=E7=99=BB=E5=BD=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 进入页面即使 login_status=qr_pending 也先展示手机号+验证码 - 点改用二维码登录才切到二维码页,页面底部可切回手机号登录 --- .../customer-fulfillment/CustomerFulfillmentPage.tsx | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/apps/frontend/src/pages/customer-fulfillment/CustomerFulfillmentPage.tsx b/apps/frontend/src/pages/customer-fulfillment/CustomerFulfillmentPage.tsx index e1212209..d9c8e6e6 100644 --- a/apps/frontend/src/pages/customer-fulfillment/CustomerFulfillmentPage.tsx +++ b/apps/frontend/src/pages/customer-fulfillment/CustomerFulfillmentPage.tsx @@ -57,8 +57,6 @@ export default function CustomerFulfillmentPage() { const [loginInfo, setLoginInfo] = useState(null) const [loginQrImage, setLoginQrImage] = useState('') const [loginMode, setLoginMode] = useState<'sms' | 'qr'>('sms') - // 扫码页点「改用手机号登录」时,即使登录状态仍是 qr_pending 也切回短信表单。 - const [showSmsFallback, setShowSmsFallback] = useState(false) const [mobile, setMobile] = useState('') const [smsCode, setSmsCode] = useState('') const [smsSending, setSmsSending] = useState(false) @@ -126,7 +124,6 @@ export default function CustomerFulfillmentPage() { useEffect(() => { if (!selectedTask) return setLoginMode('sms') - setShowSmsFallback(false) setMobile('') setSmsCode('') setSmsMfaRequired(false) @@ -672,7 +669,6 @@ export default function CustomerFulfillmentPage() { className="customer-login-alt" onClick={() => { setLoginMode('qr') - setShowSmsFallback(false) void handleStartLogin() }} > @@ -768,7 +764,7 @@ export default function CustomerFulfillmentPage() { {selectedTask?.loginStatus === 'waiting_login' || selectedTask?.loginStatus === 'failed' || selectedTask?.loginStatus === 'expired' || - (showSmsFallback && selectedTask?.loginStatus === 'qr_pending') ? ( + (loginQrVisible && loginMode === 'sms') ? (
{isWeibo ? ( ) : null} - {loginQrVisible && !showSmsFallback ? ( + {loginQrVisible && loginMode === 'qr' ? (
@@ -905,7 +901,7 @@ export default function CustomerFulfillmentPage() { block size="large" className="customer-login-alt" - onClick={() => setShowSmsFallback(true)} + onClick={() => setLoginMode('sms')} > 改用手机号登录 From 5aa627a0ca42611dd314abc245644aefa3c757a5 Mon Sep 17 00:00:00 2001 From: zhaoxing <2558691827@qq.com> Date: Mon, 16 Nov 2026 13:30:26 +0800 Subject: [PATCH 03/15] =?UTF-8?q?fix(semi-auto):=20=E6=8D=A2=E7=BB=91?= =?UTF-8?q?=E6=9C=AA=E7=94=9F=E6=95=88=E5=8E=9F=E5=9B=A0=E4=B8=8E=207=20?= =?UTF-8?q?=E5=A4=A9=E5=86=B7=E5=8D=B4=E6=8F=90=E7=A4=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../semi-auto/huya-connector-client.ts | 5 + .../huya-native/huya-native-connector.ts | 154 +++++++++-- .../semi-auto/huya-native/huya-rpc.ts | 39 ++- .../huya-native/rebind-cooldown.test.ts | 45 ++++ .../semi-auto/semi-auto-binding-role.test.ts | 77 +++++- .../semi-auto/semi-auto-task-service.ts | 125 ++++++++- .../pages/admin/AdminSemiAutoTasksPage.tsx | 18 ++ .../CustomerFulfillmentPage.tsx | 247 ++++++++++++++---- apps/frontend/src/styles/client.css | 159 ++++++++++- .../src/types/customer-fulfillment.ts | 5 + 10 files changed, 781 insertions(+), 93 deletions(-) create mode 100644 apps/backend/src/services/semi-auto/huya-native/rebind-cooldown.test.ts diff --git a/apps/backend/src/services/semi-auto/huya-connector-client.ts b/apps/backend/src/services/semi-auto/huya-connector-client.ts index d2e06045..eeca2bae 100644 --- a/apps/backend/src/services/semi-auto/huya-connector-client.ts +++ b/apps/backend/src/services/semi-auto/huya-connector-client.ts @@ -102,6 +102,11 @@ export type ConnectorBindingSession = { bindGameChannel: string hasExistingBinding?: boolean rebindRequested?: boolean + rebindUnchanged?: boolean + rebindCooldownDays?: number + nextRebindAt?: string + platformChangeBindDay?: number + platformChangeBindTime?: number message: string } diff --git a/apps/backend/src/services/semi-auto/huya-native/huya-native-connector.ts b/apps/backend/src/services/semi-auto/huya-native/huya-native-connector.ts index a1dbc772..4bbe089d 100644 --- a/apps/backend/src/services/semi-auto/huya-native/huya-native-connector.ts +++ b/apps/backend/src/services/semi-auto/huya-native/huya-native-connector.ts @@ -52,6 +52,8 @@ const LOGIN_QR_TTL_MS = 5 * 60 * 1000 const SMS_LOGIN_TTL_MS = 5 * 60 * 1000 const CREDENTIAL_TTL_MS = 24 * 60 * 60 * 1000 const BINDING_QR_TTL_MS = 5 * 60 * 1000 +const REBIND_WINDOW_DAYS = 7 +const DAY_MS = 24 * 60 * 60 * 1000 const BROWSER_TICKET_TTL_MS = 2 * 60 * 1000 const MAX_SESSIONS = 500 const NATIVE_TICKET_PREFIX = 'native-ticket-' @@ -73,6 +75,11 @@ type NativeBindState = { hasExistingBinding: boolean rebindRequested: boolean rebindScanned: boolean + rebindUnchanged: boolean + rebindCooldownDays: number + nextRebindAt: string + changeBindTime: number + changeBindDay: number baselineRoleKey: string message: string } @@ -148,6 +155,11 @@ function defaultBindingState(): NativeBindState { hasExistingBinding: false, rebindRequested: false, rebindScanned: false, + rebindUnchanged: false, + rebindCooldownDays: 0, + nextRebindAt: '', + changeBindTime: 0, + changeBindDay: 0, baselineRoleKey: '', message: '', } @@ -157,6 +169,78 @@ function iso(value: number): string { return new Date(value).toISOString() } +function rebindDateLabel(value: string): string { + if (!value) return '' + const date = new Date(value) + if (Number.isNaN(date.getTime())) return '' + return new Intl.DateTimeFormat('zh-CN', { + timeZone: 'Asia/Shanghai', + year: 'numeric', + month: '2-digit', + day: '2-digit', + }).format(date) +} + +export type RebindCooldownInput = { + status?: number + changeBindDay?: number + accountData?: { changeBindTime?: number } | null +} + +/** + * 虎牙活动限制:每 7 个自然日允许换绑 1 次。 + * changeBindTime 为上次绑定/换绑时间(秒级 Unix 时间戳),changeBindDay 作为兜底剩余天数。 + */ +export function resolveRebindCooldown( + response: RebindCooldownInput | null | undefined, + now = Date.now(), +): { days: number; nextRebindAt: string } { + if (!response || (response.status !== undefined && response.status !== 200)) { + return { days: 0, nextRebindAt: '' } + } + const changeBindTime = Number(response.accountData?.changeBindTime || 0) + if (Number.isFinite(changeBindTime) && changeBindTime > 0) { + const changedAtMs = changeBindTime > 1e12 ? changeBindTime : changeBindTime * 1000 + const nextRebindMs = changedAtMs + REBIND_WINDOW_DAYS * DAY_MS + if (nextRebindMs > now) { + return { + days: Math.ceil((nextRebindMs - now) / DAY_MS), + nextRebindAt: iso(nextRebindMs), + } + } + } + const changeBindDay = Number(response.changeBindDay || 0) + if (Number.isFinite(changeBindDay) && changeBindDay > 0 && changeBindDay <= 30) { + const days = Math.round(changeBindDay) + return { days, nextRebindAt: iso(now + days * DAY_MS) } + } + return { days: 0, nextRebindAt: '' } +} + +function applyRebindMeta( + session: NativeSession, + response: HuyaBindResponse | null, + now: number, +): void { + const cooldown = resolveRebindCooldown(response, now) + session.binding.rebindCooldownDays = cooldown.days + session.binding.nextRebindAt = cooldown.nextRebindAt + session.binding.changeBindTime = Number(response?.accountData?.changeBindTime || 0) + session.binding.changeBindDay = Number(response?.changeBindDay || 0) +} + +function rebindUnchangedMessage( + roleName: string, + cooldownDays: number, + nextRebindAt: string, +): string { + const next = rebindDateLabel(nextRebindAt) + if (cooldownDays > 0) { + return `扫码后仍识别到原绑定角色「${roleName}」;本活动 7 天内只能换绑 1 次${next ? `,预计下次换绑:${next}` : ''}` + } + return `扫码后仍识别到原绑定角色「${roleName}」,请确认微信中选择的角色或重新换绑` +} + function extractInt(value: unknown): number { const parsed = Number.parseInt(String(value ?? '').trim(), 10) return Number.isFinite(parsed) && parsed > 0 ? parsed : 0 @@ -674,10 +758,17 @@ export class HuyaNativeConnector { const role = parseRole(roleResponse) const hasExistingBinding = hasExistingHuyaBinding(roleResponse) session.binding.hasExistingBinding = hasExistingBinding + applyRebindMeta(session, roleResponse, this.now()) if (role.role && !options.forceRebind) { this.markRoleReady(session, role, hasExistingBinding && !session.binding.rebindRequested) if (session.binding.rebindRequested) { - session.binding.message = '已识别待换绑角色,请确认换绑' + session.binding.message = session.binding.rebindUnchanged + ? rebindUnchangedMessage( + role.role, + session.binding.rebindCooldownDays, + session.binding.nextRebindAt, + ) + : '已识别待换绑角色,请确认换绑' } return this.bindingView(session) } @@ -700,11 +791,20 @@ export class HuyaNativeConnector { errorCode: 'huya_livelink_param_failed', }) } - const profile = await rpc.getUserProfile({ - uid: session.uid, - cookie: session.cookie, - targetUid: session.uid, - }) + let profile: Awaited> = null + try { + profile = await rpc.getUserProfile({ + uid: session.uid, + cookie: session.cookie, + targetUid: session.uid, + }) + } catch (error) { + // 资料接口结构可能随虎牙升级变化,失败时回退登录会话里的昵称/头像,不能阻断换绑二维码。 + logWarn('huya/bind/profile', '获取虎牙账号资料失败,回退登录昵称', { + uid: session.uid, + error: errorMessage(error), + }) + } const nickname = profile?.nick || profile?.passport || session.nickname session.nickname = nickname const avatar = profile?.avatar || '' @@ -732,6 +832,7 @@ export class HuyaNativeConnector { if (options.forceRebind) { session.binding.rebindRequested = true session.binding.rebindScanned = false + session.binding.rebindUnchanged = false session.binding.baselineRoleKey = bindingRoleKey(role) } session.binding.status = 'qr_pending' @@ -790,24 +891,30 @@ export class HuyaNativeConnector { const role = parseRole(response) const hasExistingBinding = hasExistingHuyaBinding(response) session.binding.hasExistingBinding = hasExistingBinding + applyRebindMeta(session, response, this.now()) if (role.role) { const rebindRequested = session.binding.rebindRequested const roleKey = bindingRoleKey(role) const changedRole = !session.binding.baselineRoleKey || roleKey !== session.binding.baselineRoleKey if (rebindRequested && !changedRole) { - if (qrCompleted) { - session.binding.rebindRequested = false - session.binding.rebindScanned = false - session.binding.baselineRoleKey = '' + if (qrCompleted || session.binding.rebindUnchanged) { + // 扫码完成但虎牙仍返回原角色:保留 rebind 状态,明确告知未换绑及冷却原因, + // 不能清空 rebindRequested,否则 confirmBinding 会误判为“使用已有绑定”。 + session.binding.rebindUnchanged = true this.markRoleReady(session, role, hasExistingBinding) - session.binding.message = '扫码后仍识别到原绑定角色,请确认使用或重新换绑' + session.binding.message = rebindUnchangedMessage( + role.role, + session.binding.rebindCooldownDays, + session.binding.nextRebindAt, + ) } else { session.binding.status = 'scanned' session.binding.message = '已扫码,正在等待换绑角色生效' } return this.bindingView(session) } + if (rebindRequested) session.binding.rebindUnchanged = false this.markRoleReady(session, role, hasExistingBinding && !rebindRequested) if (rebindRequested) { session.binding.message = '已识别换绑角色,请确认换绑' @@ -839,15 +946,24 @@ export class HuyaNativeConnector { }) } const rebindRequested = session.binding.rebindRequested + applyRebindMeta(session, response, this.now()) if ( rebindRequested && session.binding.baselineRoleKey && bindingRoleKey(role) === session.binding.baselineRoleKey ) { - throw createHttpError('换绑角色尚未生效,请稍后重试', { - statusCode: 409, - errorCode: 'huya_bind_rebind_not_ready', - }) + const cooldownDays = session.binding.rebindCooldownDays + const next = rebindDateLabel(session.binding.nextRebindAt) + throw createHttpError( + cooldownDays > 0 + ? `换绑未生效:平台仍返回原绑定角色「${role.role}」;本活动 7 天内只能换绑 1 次${next ? `,预计下次换绑:${next}` : ''}` + : `换绑未生效:平台仍返回原绑定角色「${role.role}」,请重新扫码选择正确角色`, + { + statusCode: 409, + errorCode: + cooldownDays > 0 ? 'huya_bind_rebind_cooldown' : 'huya_bind_rebind_not_ready', + }, + ) } const useExistingBinding = hasExistingHuyaBinding(response) && !rebindRequested if (!useExistingBinding) { @@ -869,6 +985,9 @@ export class HuyaNativeConnector { session.binding.hasExistingBinding = true session.binding.rebindRequested = false session.binding.rebindScanned = false + session.binding.rebindUnchanged = false + session.binding.rebindCooldownDays = 0 + session.binding.nextRebindAt = '' session.binding.baselineRoleKey = '' session.binding.message = useExistingBinding ? '当前虎牙账号已有绑定角色,已确认直接使用' @@ -1156,6 +1275,11 @@ export class HuyaNativeConnector { bindGameChannel: binding.channel, hasExistingBinding: binding.hasExistingBinding, rebindRequested: binding.rebindRequested, + rebindUnchanged: binding.rebindUnchanged, + rebindCooldownDays: binding.rebindCooldownDays, + nextRebindAt: binding.nextRebindAt, + platformChangeBindDay: binding.changeBindDay, + platformChangeBindTime: binding.changeBindTime, message: binding.message, } } diff --git a/apps/backend/src/services/semi-auto/huya-native/huya-rpc.ts b/apps/backend/src/services/semi-auto/huya-native/huya-rpc.ts index dae1c858..1135af87 100644 --- a/apps/backend/src/services/semi-auto/huya-native/huya-rpc.ts +++ b/apps/backend/src/services/semi-auto/huya-native/huya-rpc.ts @@ -401,6 +401,27 @@ function parseLiveLinkResponse(reader: TafReader): HuyaLiveLinkResponse { } } +function isProfileIntType(dataType: TafTypeValue): boolean { + return ( + dataType === TAF_TYPE.INT8 || + dataType === TAF_TYPE.INT16 || + dataType === TAF_TYPE.INT32 || + dataType === TAF_TYPE.INT64 || + dataType === TAF_TYPE.ZERO + ) +} + +function readProfileString(reader: TafReader, dataType: TafTypeValue): string { + if (dataType === TAF_TYPE.STRING1 || dataType === TAF_TYPE.STRING4) { + return reader.readStringValue(dataType) + } + + if (dataType === TAF_TYPE.ZERO) return '' + + reader.skipValue(dataType) + return '' +} + function parseProfile(reader: TafReader): HuyaUserProfile { let uid = 0 let nick = '' @@ -412,10 +433,20 @@ function parseProfile(reader: TafReader): HuyaUserProfile { break } reader.readHead() - if (tag === 0) uid = reader.readIntValue(dataType) - else if (tag === 1) nick = reader.readStringValue(dataType) - else if (tag === 2) avatar = reader.readStringValue(dataType) - else if (tag === 17) passport = reader.readStringValue(dataType) + if (dataType === TAF_TYPE.STRUCT_BEGIN) { + // 新版虎牙把资料包在 tag0 的嵌套结构里,直接解析内层结构。 + if (tag === 0) { + return reader.readStructBody((nested) => parseProfile(nested)) + } + reader.skipValue(dataType) + continue + } + if (tag === 0) { + if (isProfileIntType(dataType)) uid = reader.readIntValue(dataType) + else reader.skipValue(dataType) + } else if (tag === 1) nick = readProfileString(reader, dataType) + else if (tag === 2) avatar = readProfileString(reader, dataType) + else if (tag === 17) passport = readProfileString(reader, dataType) else reader.skipValue(dataType) } return { uid, nick, avatar, passport } diff --git a/apps/backend/src/services/semi-auto/huya-native/rebind-cooldown.test.ts b/apps/backend/src/services/semi-auto/huya-native/rebind-cooldown.test.ts new file mode 100644 index 00000000..0cbfb5d3 --- /dev/null +++ b/apps/backend/src/services/semi-auto/huya-native/rebind-cooldown.test.ts @@ -0,0 +1,45 @@ +import assert from 'node:assert/strict' +import test from 'node:test' + +import { resolveRebindCooldown } from './huya-native-connector.js' + +// 2026-11-16 12:12:24 +08:00,对应任务 34 的初次绑定时间。 +const NOW = Date.UTC(2026, 10, 16, 4, 12, 24) +const DAY_MS = 24 * 60 * 60 * 1000 + +test('换绑冷却:changeBindTime 为初次绑定时间时,下次换绑为 7 天后', () => { + const result = resolveRebindCooldown( + { + status: 200, + changeBindDay: 0, + accountData: { changeBindTime: Math.floor(NOW / 1000) }, + }, + NOW, + ) + assert.equal(result.days, 7) + assert.equal(result.nextRebindAt.slice(0, 10), '2026-11-23') +}) + +test('换绑冷却:changeBindTime 已超过 7 天时不再限制', () => { + const result = resolveRebindCooldown( + { + status: 200, + changeBindDay: 0, + accountData: { changeBindTime: Math.floor((NOW - 8 * DAY_MS) / 1000) }, + }, + NOW, + ) + assert.equal(result.days, 0) + assert.equal(result.nextRebindAt, '') +}) + +test('换绑冷却:changeBindTime 缺失时用 changeBindDay 兜底', () => { + const result = resolveRebindCooldown({ status: 200, changeBindDay: 3, accountData: {} }, NOW) + assert.equal(result.days, 3) + assert.equal(result.nextRebindAt.slice(0, 10), '2026-11-19') +}) + +test('换绑冷却:字段为空时不限制', () => { + const result = resolveRebindCooldown({ status: 200, changeBindDay: 0, accountData: {} }, NOW) + assert.deepEqual(result, { days: 0, nextRebindAt: '' }) +}) diff --git a/apps/backend/src/services/semi-auto/semi-auto-binding-role.test.ts b/apps/backend/src/services/semi-auto/semi-auto-binding-role.test.ts index 5ba3ea98..c545886b 100644 --- a/apps/backend/src/services/semi-auto/semi-auto-binding-role.test.ts +++ b/apps/backend/src/services/semi-auto/semi-auto-binding-role.test.ts @@ -2,11 +2,16 @@ import assert from 'node:assert/strict' import { describe, it } from 'node:test' import { resolveBindingRoleId } from './binding-role-id.js' -import { compareBindingRole, normalizeCustomerProfile } from './semi-auto-task-service.js' +import { + compareBindingRole, + detectServerZone, + normalizeCustomerProfile, +} from './semi-auto-task-service.js' -const task = (id: string, name: string, huyaUid = '') => ({ +const task = (id: string, name: string, huyaUid = '', zone = '') => ({ customer_game_id: id, customer_game_role: name, + customer_game_server_zone: zone, huya_uid: huyaUid, }) @@ -53,7 +58,75 @@ describe('待确认角色 UID 取数(huyaUid)', () => { }) }) +describe('区服解析', () => { + it('安卓 + 微信识别为安卓V区', () => { + assert.equal(detectServerZone('安卓(android) · 微信'), '安卓V区') + assert.equal(detectServerZone('微信用户 · 安卓(android) · 微信'), '安卓V区') + }) + + it('苹果 + QQ识别为苹果Q区', () => { + assert.equal(detectServerZone('苹果(iOS) · QQ'), '苹果Q区') + }) + + it('无法识别时返回空串', () => { + assert.equal(detectServerZone(''), '') + assert.equal(detectServerZone('微信用户'), '') + }) +}) + describe('客户填写角色与平台识别角色比对', () => { + it('区服、角色名称、角色 ID 都一致时允许确认', () => { + const result = compareBindingRole( + task('1199608910400', '大鲨鱼伊塞53', '1199608910400', '安卓V区'), + { + bindGameRole: '大鲨鱼伊塞53', + bindGameRoleId: '1199608910400', + bindGameChannel: '安卓(android) · 微信', + }, + ) + assert.equal(result.verdict, 'match') + assert.equal(result.customerZone, '安卓V区') + assert.equal(result.boundZone, '安卓V区') + assert.match(result.message, /区服/) + }) + + it('角色 ID 一致但角色名称不一致时禁止确认', () => { + const result = compareBindingRole(task('1199608910400', '123', '1199608910400', '安卓V区'), { + bindGameRole: '大鲨鱼伊塞53', + bindGameRoleId: '1199608910400', + bindGameChannel: '安卓(android) · 微信', + }) + assert.equal(result.verdict, 'mismatch') + assert.match(result.message, /名称/) + }) + + it('角色名称与 ID 一致但区服不一致时禁止确认', () => { + const result = compareBindingRole( + task('1199608910400', '大鲨鱼伊塞53', '1199608910400', '苹果Q区'), + { + bindGameRole: '大鲨鱼伊塞53', + bindGameRoleId: '1199608910400', + bindGameChannel: '安卓(android) · 微信', + }, + ) + assert.equal(result.verdict, 'mismatch') + assert.match(result.message, /区服/) + assert.equal(result.boundZone, '安卓V区') + }) + + it('渠道解析不出区服时跳过区服比对', () => { + const result = compareBindingRole( + task('1199608910400', '大鲨鱼伊塞53', '1199608910400', '苹果Q区'), + { + bindGameRole: '大鲨鱼伊塞53', + bindGameRoleId: '1199608910400', + bindGameChannel: '微信用户', + }, + ) + assert.equal(result.verdict, 'match') + assert.equal(result.boundZone, '') + }) + it('两侧角色 ID 一致时允许确认', () => { const result = compareBindingRole(task('1192083858', '巫师基尔斯84'), { bindGameRole: '巫师基尔斯84', diff --git a/apps/backend/src/services/semi-auto/semi-auto-task-service.ts b/apps/backend/src/services/semi-auto/semi-auto-task-service.ts index 5ee7a8da..1154077d 100644 --- a/apps/backend/src/services/semi-auto/semi-auto-task-service.ts +++ b/apps/backend/src/services/semi-auto/semi-auto-task-service.ts @@ -19,6 +19,7 @@ import { import { createHuyaBrowserTicket, createHuyaLoginSession, + confirmHuyaBinding, exportHuyaSessionCredential, getHuyaBinding, getHuyaLoginSession, @@ -954,6 +955,11 @@ function mapBindingUpdate(session: ConnectorBindingSession) { bindGameChannel: String(session.bindGameChannel || ''), hasExistingBinding: session.hasExistingBinding === true, rebindRequested: session.rebindRequested === true, + rebindUnchanged: session.rebindUnchanged === true, + rebindCooldownDays: Number(session.rebindCooldownDays || 0), + nextRebindAt: String(session.nextRebindAt || ''), + platformChangeBindDay: Number(session.platformChangeBindDay || 0), + platformChangeBindTime: Number(session.platformChangeBindTime || 0), message: String(session.message || ''), } } @@ -962,8 +968,10 @@ export type BindingRoleComparison = { verdict: 'match' | 'mismatch' | 'unknown' customerRoleName: string customerRoleId: string + customerZone: string boundRoleName: string boundRoleId: string + boundZone: string message: string } @@ -973,18 +981,53 @@ function normalizeRoleText(value: unknown): string { .toLowerCase() } +function normalizeServerZone(value: unknown): string { + const text = String(value ?? '').trim() + + if (!text) return '' + + return /区$/.test(text) ? text : `${text}区` +} + +/** + * 从虎牙渠道串解析区服,例如「安卓(android) · 微信」→ 安卓V区。 + * 解析不出平台或登录方式时返回空串,调用方跳过区服比对。 + */ +export function detectServerZone(channel: unknown): string { + const text = String(channel ?? '') + .replace(/\s+/g, '') + .toLowerCase() + + if (!text) return '' + + const platform = /苹果|ios/.test(text) ? '苹果' : /安卓|android/.test(text) ? '安卓' : '' + + if (!platform) return '' + + const login = /qq|q区/.test(text) ? 'Q' : /微信|wechat|v区/.test(text) ? 'V' : '' + + return login ? `${platform}${login}区` : '' +} + /** * 客户填写角色与平台识别角色必须一致才允许确认绑定。 * - * 两侧都有角色 ID 时以 ID 为准(截图里的“两侧角色 ID 不一致”); - * 任一侧缺 ID 时退回角色名比对;两边都取不到才判 unknown,转客服核对。 + * 区服、角色名、角色 ID 三项都要一致: + * ① 两侧都有 ID 时 ID 必须相等; + * ② 两侧都有角色名时名称必须相等(不能因为 ID 相同就放行改名); + * ③ 平台渠道能解析出区服且客户有填时,区服必须相等。 + * 任一侧缺某字段时跳过该字段比对;三项都取不到才判 unknown,转客服核对。 */ export function compareBindingRole( - task: Pick, - binding: { bindGameRole?: string; bindGameRoleId?: string }, + task: Pick< + TaskRow, + 'customer_game_id' | 'customer_game_role' | 'customer_game_server_zone' | 'huya_uid' + >, + binding: { bindGameRole?: string; bindGameRoleId?: string; bindGameChannel?: string }, ): BindingRoleComparison { const customerRoleName = String(task.customer_game_role || '').trim() const customerRoleId = String(task.customer_game_id || '').trim() + const customerZone = normalizeServerZone(task.customer_game_server_zone) const boundRoleName = String(binding.bindGameRole || '').trim() const rawBoundRoleId = String(binding.bindGameRoleId || '').trim() // 虎牙 gameRole.roleId 是 40 位加密串,客户填写的是数值游戏编号; @@ -995,17 +1038,46 @@ export function compareBindingRole( const boundRoleId = /^\d+$/.test(rawBoundRoleId) ? rawBoundRoleId : numericHuyaUid || rawBoundRoleId - const base = { customerRoleName, customerRoleId, boundRoleName, boundRoleId } - if (customerRoleId && boundRoleId) { - return customerRoleId === boundRoleId - ? { ...base, verdict: 'match', message: '两侧角色 ID 一致,可确认绑定' } - : { ...base, verdict: 'mismatch', message: '两侧角色 ID 不一致,无法确认绑定' } + const boundZone = detectServerZone(binding.bindGameChannel) + const base = { + customerRoleName, + customerRoleId, + customerZone, + boundRoleName, + boundRoleId, + boundZone, } - if (customerRoleName && boundRoleName) { - return normalizeRoleText(customerRoleName) === normalizeRoleText(boundRoleName) - ? { ...base, verdict: 'match', message: '两侧角色名称一致,可确认绑定' } - : { ...base, verdict: 'mismatch', message: '两侧角色名称不一致,无法确认绑定' } + + if (customerRoleId && boundRoleId && customerRoleId !== boundRoleId) { + return { ...base, verdict: 'mismatch', message: '两侧角色 ID 不一致,无法确认绑定' } } + + if ( + customerRoleName && + boundRoleName && + normalizeRoleText(customerRoleName) !== normalizeRoleText(boundRoleName) + ) { + return { ...base, verdict: 'mismatch', message: '两侧角色名称不一致,无法确认绑定' } + } + + if (customerZone && boundZone && customerZone !== boundZone) { + return { ...base, verdict: 'mismatch', message: '两侧区服不一致,无法确认绑定' } + } + + const matchedFields = [ + customerRoleId && boundRoleId ? '角色 ID' : '', + customerRoleName && boundRoleName ? '角色名称' : '', + customerZone && boundZone ? '区服' : '', + ].filter(Boolean) + + if (matchedFields.length > 0) { + return { + ...base, + verdict: 'match', + message: `两侧${matchedFields.join('、')}一致,可确认绑定`, + } + } + return { ...base, verdict: 'unknown', @@ -1065,6 +1137,12 @@ async function updateBindingTask( gameRoleId: mapped.bindGameRoleId, gameChannel: mapped.bindGameChannel, verdict: comparison.verdict, + rebindRequested: mapped.rebindRequested, + rebindUnchanged: mapped.rebindUnchanged, + rebindCooldownDays: mapped.rebindCooldownDays, + nextRebindAt: mapped.nextRebindAt, + changeBindDay: mapped.platformChangeBindDay, + changeBindTime: mapped.platformChangeBindTime, message: mapped.message, }, }) @@ -1080,6 +1158,11 @@ async function updateBindingTask( bindGameChannel: mapped.bindGameChannel, hasExistingBinding: mapped.hasExistingBinding, rebindRequested: mapped.rebindRequested, + rebindUnchanged: mapped.rebindUnchanged, + rebindCooldownDays: mapped.rebindCooldownDays, + nextRebindAt: mapped.nextRebindAt, + platformChangeBindDay: mapped.platformChangeBindDay, + platformChangeBindTime: mapped.platformChangeBindTime, message: mapped.message, comparison, } @@ -1271,6 +1354,15 @@ export async function confirmPublicBinding(orderNoInput: unknown, taskIdInput: u }) } const session = await getBindingForTask(task, task.connector_session_id) + if (task.platform === 'huya' && session.rebindUnchanged === true) { + throw createHttpError(session.message || '换绑未生效:平台仍返回原绑定角色,请重新扫码', { + statusCode: 409, + errorCode: + Number(session.rebindCooldownDays || 0) > 0 + ? 'semi_auto_binding_rebind_cooldown' + : 'semi_auto_binding_rebind_unchanged', + }) + } const comparison = compareBindingRole(task, session) if (comparison.verdict === 'mismatch') { throw createHttpError(comparison.message, { @@ -1278,7 +1370,12 @@ export async function confirmPublicBinding(orderNoInput: unknown, taskIdInput: u errorCode: 'semi_auto_binding_role_mismatch', }) } - const binding = await updateBindingTask(task, session, 'customer') + // 必须调用 Connector 完成确认,否则会话仍是 role_ready,数据库也会停在待确认。 + const confirmedSession = + task.platform === 'huya' + ? await confirmHuyaBinding(task.connector_session_id, task.connector_mode) + : session + const binding = await updateBindingTask(task, confirmedSession, 'customer') const updated = await loadTask(task.id) return { task: mapTask(updated), binding } } diff --git a/apps/frontend/src/pages/admin/AdminSemiAutoTasksPage.tsx b/apps/frontend/src/pages/admin/AdminSemiAutoTasksPage.tsx index 07daf332..6f65684d 100644 --- a/apps/frontend/src/pages/admin/AdminSemiAutoTasksPage.tsx +++ b/apps/frontend/src/pages/admin/AdminSemiAutoTasksPage.tsx @@ -727,6 +727,24 @@ export default function AdminSemiAutoTasksPage() { {formatAdminDateTime(event.createdAt)} · {event.actorType} {event.actorId ? ` ${event.actorId}` : ''} + {event.eventType === 'binding_status_changed' && event.detail?.message ? ( + 0 + ? 'warning' + : 'secondary' + } + > + {String(event.detail.message)} + {Number(event.detail.rebindCooldownDays || 0) > 0 && + event.detail.nextRebindAt + ? ` · 下次可换绑 ${formatAdminDateTime( + String(event.detail.nextRebindAt), + )}` + : ''} + + ) : null} ), }))} diff --git a/apps/frontend/src/pages/customer-fulfillment/CustomerFulfillmentPage.tsx b/apps/frontend/src/pages/customer-fulfillment/CustomerFulfillmentPage.tsx index d9c8e6e6..c060d488 100644 --- a/apps/frontend/src/pages/customer-fulfillment/CustomerFulfillmentPage.tsx +++ b/apps/frontend/src/pages/customer-fulfillment/CustomerFulfillmentPage.tsx @@ -1,5 +1,6 @@ import { CheckCircleFilled, + ExclamationCircleOutlined, LoadingOutlined, QrcodeOutlined, ReloadOutlined, @@ -303,6 +304,8 @@ export default function CustomerFulfillmentPage() { useEffect(() => { if (!selectedTask || selectedTask.bindingStatus !== 'role_ready') return if (!bindingInfo?.comparison) return + // 换绑后仍是原角色时只展示失败原因,不能自动弹出确认框。 + if (bindingInfo.rebindUnchanged) return const key = `${selectedTask.id}:${bindingInfo.bindGameRoleId || ''}` if (autoOpenedRoleRef.current === key) return autoOpenedRoleRef.current = key @@ -494,13 +497,44 @@ export default function CustomerFulfillmentPage() { setBindingLoading(true) try { const response = await pollCustomerBinding(orderNo, selectedTask.id) - setTasks((current) => - current.map((task) => (task.id === response.data.task.id ? response.data.task : task)), - ) - if (response.data.binding) setBindingInfo(response.data.binding) - if (openConfirm || response.data.task.bindingStatus === 'role_ready') { + const nextTask = response.data.task + const nextBinding = response.data.binding + setTasks((current) => current.map((task) => (task.id === nextTask.id ? nextTask : task))) + if (nextBinding) setBindingInfo(nextBinding) + if (nextTask.bindingStatus === 'role_ready') { + if (nextBinding?.rebindUnchanged) { + setBindingConfirmOpen(false) + message.warning(nextBinding.message || '换绑未生效,请查看下方原因') + return + } setBindingConfirmOpen(true) + return } + if (nextTask.bindingStatus === 'confirmed') { + setBindingConfirmOpen(false) + message.success('绑定已确认,等待客服处理') + return + } + // 弹窗内点「刷新」:角色不再是待确认状态时收起弹窗,避免展示过期比对。 + if (openConfirm) setBindingConfirmOpen(false) + const detail = nextBinding?.message || '' + if (nextTask.bindingStatus === 'scanned') { + message.info(detail || '已扫码,正在等待虎牙平台换绑生效,请稍后再点击刷新') + return + } + if (nextTask.bindingStatus === 'qr_pending') { + message.warning('还没有检测到扫码记录,请使用微信扫码完成绑定后再点击') + return + } + if (nextTask.bindingStatus === 'expired') { + message.warning('绑定二维码已过期,请点击「刷新二维码」重新获取') + return + } + if (nextTask.bindingStatus === 'failed') { + message.error(detail || '识别绑定角色失败,请点击「刷新二维码」重试') + return + } + message.info(detail || '绑定状态还没有更新,请稍后再试') } catch (error) { if (isHuyaSessionExpired(error)) { setBindingSessionExpired(true) @@ -595,7 +629,8 @@ export default function CustomerFulfillmentPage() { selectedTask && selectedTask.platform === 'huya' && selectedTask.loginStatus === 'authenticated' && - selectedTask.bindingStatus !== 'confirmed', + selectedTask.executionStatus !== 'completed' && + selectedTask.executionStatus !== 'cancelled', ) const bindingQrVisible = ['not_started', 'qr_pending', 'scanned'].includes( selectedTask?.bindingStatus || '', @@ -610,6 +645,11 @@ export default function CustomerFulfillmentPage() { return /^\d+$/.test(huyaUid) ? huyaUid : comparisonId })() const bindingRoleName = bindingInfo?.bindGameRole || selectedTask?.bindGameRole || '' + const rebindUnchanged = bindingInfo?.rebindUnchanged === true + const rebindCooldownDays = Number(bindingInfo?.rebindCooldownDays || 0) + const nextRebindText = bindingInfo?.nextRebindAt + ? formatAdminDateTime(bindingInfo.nextRebindAt) + : '' const showProfileForm = showBindingStage && profileEditing const bindingCustomerReady = Boolean( bindingComparison?.customerRoleId || bindingComparison?.customerRoleName, @@ -949,59 +989,76 @@ export default function CustomerFulfillmentPage() { ) : null} {!bindingSessionExpired ? ( - !bindingRoleId ? ( -
- 未获取到已绑定的角色ID,请重新扫码绑定 -
- ) : ( + rebindUnchanged ? ( +
换绑未生效,请查看下方原因
+ ) : selectedTask?.bindingStatus === 'role_ready' ? ( +
已识别绑定角色,请核对后确认
+ ) : selectedTask?.bindingStatus === 'confirmed' || bindingRoleId ? (
登录成功,请继续扫码绑定游戏角色
+ ) : ( +
+ 未获取到已绑定的角色ID,请重新扫码绑定 +
) ) : null} {showProfileForm && !bindingSessionExpired ? (

修改资料后会重新核对平台识别角色。

- +
+ setProfileRoleId(event.target.value)} - placeholder="游戏编号 / 角色 ID(必填,纯数字)" + placeholder="请输入游戏编号" maxLength={64} inputMode="numeric" /> + setProfileRoleName(event.target.value)} - placeholder="角色名(必填)" + placeholder="请输入角色名" maxLength={100} /> - +
) : null} {bindingQrVisible && !bindingSessionExpired ? (

游戏角色绑定二维码

- {bindingQrImage || bindingInfo?.qrImage ? ( + {bindingInfo?.qrImage || bindingQrImage ? ( 游戏角色绑定二维码 )}

请使用微信APP扫码进行游戏角色绑定

-

手机端可长按二维码或截图保存图片再识别

+

+ {selectedTask?.bindingStatus === 'scanned' + ? '请在微信中完成角色绑定确认,再点击下方按钮进入下一步' + : '扫码后请在微信确认框中核对目标角色;本活动 7 天内只能换绑 1 次'} +

+ {rebindCooldownDays > 0 ? ( +

+ 平台提示:预计下次可换绑 + {nextRebindText ? ` ${nextRebindText}` : '需等待 7 天'};本次扫码可能不会生效。 +

+ ) : null}

{selectedTask?.bindingStatus === 'scanned' - ? '已扫码,等待角色生效' + ? bindingInfo?.message || '已扫码,等待角色生效' : `建议 ${formatCountdown(bindingSecondsLeft)} 内完成扫码`}

@@ -1031,6 +1098,7 @@ export default function CustomerFulfillmentPage() { block size="large" className="customer-binding-next" + loading={bindingLoading} onClick={() => void handlePollBindingNow()} > 已扫码绑定,点击进入下一步 @@ -1070,15 +1138,41 @@ export default function CustomerFulfillmentPage() { {selectedTask?.bindingStatus === 'role_ready' && !bindingSessionExpired ? ( - - {!bindingRoleId ? ( + {rebindUnchanged ? ( + + + 扫码已完成,但平台仍返回原绑定角色: + {bindingRoleName || '未识别到角色'} + + {rebindCooldownDays > 0 ? ( + + 原因:本活动 7 天内只能换绑 1 次 + {nextRebindText ? `,预计下次可换绑:${nextRebindText}` : ''}。 + + ) : ( + + 请在微信确认框中核对目标角色后重新换绑;如持续失败请联系客服。 + + )} + + } + /> + ) : ( + + )} + {!bindingPendingUid && !rebindUnchanged ? ( ) : null} - - - - + {rebindUnchanged ? ( +
+ + +
+ ) : ( +
+ + +
+ )} ) : null} + + {selectedTask?.bindingStatus === 'confirmed' ? ( +
+

绑定状态需要平台人工核实,请联系客服处理

+ +
+ ) : null}
) : null} - {selectedTask?.loginStatus === 'authenticated' && - (isWeibo || selectedTask.bindingStatus === 'confirmed') && + {isWeibo && + selectedTask?.loginStatus === 'authenticated' && selectedTask.executionStatus !== 'completed' ? (
@@ -1127,7 +1268,9 @@ export default function CustomerFulfillmentPage() { ) : null} { if (!bindingLoading) setBindingConfirmOpen(false) @@ -1152,7 +1295,9 @@ export default function CustomerFulfillmentPage() {
{bindingComparison?.verdict === 'mismatch' ? ( -

两侧角色ID不一致,无法确认绑定

+

+ {bindingComparison?.message || '两侧角色信息不一致,无法确认绑定'} +

) : bindingComparison?.verdict === 'unknown' ? (

两侧角色信息不完整,请联系客服核实

) : null} diff --git a/apps/frontend/src/styles/client.css b/apps/frontend/src/styles/client.css index 7fa58962..a4101b0d 100644 --- a/apps/frontend/src/styles/client.css +++ b/apps/frontend/src/styles/client.css @@ -1855,7 +1855,7 @@ } .customer-auth-page .ant-btn-primary { - color: #111827; + color: #fff; border-color: var(--auth-accent); background: var(--auth-accent); font-weight: 700; @@ -1863,7 +1863,7 @@ } .customer-auth-page .ant-btn-primary:hover { - color: #111827 !important; + color: #fff !important; border-color: var(--auth-accent-hover) !important; background: var(--auth-accent-hover) !important; } @@ -2087,7 +2087,13 @@ font-size: 13px; } -.customer-auth-profile, +.customer-auth-profile { + padding: 16px; + border: 1px solid #3a4150; + border-radius: 12px; + background: #212733; +} + .customer-auth-profile-summary { padding: 14px; border: 1px solid rgba(255, 255, 255, 0.14); @@ -2096,12 +2102,22 @@ } .customer-auth-profile > p { - margin: 0 0 10px; - color: var(--auth-muted); + margin: 0 0 12px; + color: #9aa3b2; font-size: 13px; line-height: 1.6; } +.customer-profile-form { + display: flex; + flex-direction: column; + gap: 12px; +} + +.customer-profile-form .customer-collect-label { + margin-top: 2px; +} + .customer-auth-profile-summary { display: flex; flex-wrap: wrap; @@ -2322,7 +2338,8 @@ font-weight: 600; } -.customer-collect-page .customer-collect-submit.ant-btn { +.customer-collect-page .customer-collect-submit.ant-btn, +.customer-auth-profile .customer-collect-submit.ant-btn { height: 56px; margin-top: 14px; border-radius: 14px; @@ -2343,7 +2360,9 @@ } .customer-collect-page .customer-collect-submit.ant-btn:hover, -.customer-collect-page .customer-collect-submit.ant-btn:focus-visible { +.customer-collect-page .customer-collect-submit.ant-btn:focus-visible, +.customer-auth-profile .customer-collect-submit.ant-btn:hover, +.customer-auth-profile .customer-collect-submit.ant-btn:focus-visible { background: #1d4ed8 !important; border-color: #1d4ed8 !important; color: #fff !important; @@ -2479,6 +2498,114 @@ padding: 16px; } +/* antd Alert 在绑定阶段统一走深色卡片,避免浅色块破坏整体深色风格 */ +.customer-binding-stage .ant-alert { + align-items: flex-start; + padding: 12px 14px; + border: 1px solid #3a4150; + border-radius: 12px; + background: #212733; +} + +.customer-binding-stage .ant-alert .ant-alert-message { + color: #e2e8f0; + font-size: 14px; + font-weight: 600; +} + +.customer-binding-stage .ant-alert .ant-alert-description { + color: #cbd5e1; + font-size: 13px; + line-height: 1.6; +} + +.customer-binding-stage .ant-alert-warning { + border-color: #78350f; + background: rgba(120, 53, 15, 0.22); +} + +.customer-binding-stage .ant-alert-warning .ant-alert-icon, +.customer-binding-stage .ant-alert-warning .ant-alert-message { + color: #fbbf24; +} + +.customer-binding-stage .ant-alert-warning .ant-alert-description { + color: #fcd34d; +} + +.customer-binding-stage .ant-alert-error { + border-color: #7f1d1d; + background: rgba(127, 29, 29, 0.24); +} + +.customer-binding-stage .ant-alert-error .ant-alert-icon, +.customer-binding-stage .ant-alert-error .ant-alert-message { + color: #fca5a5; +} + +.customer-binding-stage .ant-alert-error .ant-alert-description { + color: #fecaca; +} + +.customer-binding-stage .ant-alert-success { + border-color: #065f46; + background: rgba(6, 78, 59, 0.28); +} + +.customer-binding-stage .ant-alert-success .ant-alert-icon, +.customer-binding-stage .ant-alert-success .ant-alert-message { + color: #6ee7b7; +} + +.customer-binding-stage .ant-alert-success .ant-alert-description { + color: #a7f3d0; +} + +.customer-binding-role-actions { + display: flex; + flex-direction: column; + gap: 12px; + width: 100%; +} + +.customer-binding-role-actions .customer-binding-confirm.ant-btn { + height: 56px; + border-radius: 14px; + background: #2563eb !important; + border-color: #2563eb !important; + color: #fff !important; + font-size: 17px; + font-weight: 600; +} + +.customer-binding-role-actions .customer-binding-confirm.ant-btn:hover, +.customer-binding-role-actions .customer-binding-confirm.ant-btn:focus-visible { + background: #1d4ed8 !important; + border-color: #1d4ed8 !important; + color: #fff !important; +} + +.customer-binding-role-actions .customer-binding-rebind.ant-btn { + height: 56px; + border-radius: 14px; + background: transparent !important; + border-color: #3a4150 !important; + color: #cbd5e1 !important; + font-size: 16px; + font-weight: 500; +} + +.customer-binding-role-actions .customer-binding-rebind.ant-btn .anticon { + color: #f59e0b; +} + +.customer-binding-role-actions .customer-binding-rebind.ant-btn:hover, +.customer-binding-role-actions .customer-binding-rebind.ant-btn:focus-visible { + background: rgba(245, 158, 11, 0.08) !important; + border-color: #b45309 !important; + color: #fbbf24 !important; +} + .customer-binding-info { padding: 16px; border: 1px solid #3a4150; @@ -2543,6 +2670,24 @@ background: rgba(30, 58, 138, 0.3); } +.customer-binding-verify { + padding: 18px; + border: 1px solid #3a4150; + border-radius: 12px; + background: transparent; + display: flex; + flex-direction: column; + gap: 16px; + text-align: center; +} + +.customer-binding-verify p { + margin: 0; + color: #e5e7eb; + font-size: 16px; + line-height: 1.6; +} + .customer-binding-qr-card { padding: 18px; border-radius: 12px; diff --git a/apps/frontend/src/types/customer-fulfillment.ts b/apps/frontend/src/types/customer-fulfillment.ts index 1e3fbf20..849b100f 100644 --- a/apps/frontend/src/types/customer-fulfillment.ts +++ b/apps/frontend/src/types/customer-fulfillment.ts @@ -57,6 +57,11 @@ export type CustomerBindingInfo = { bindGameChannel: string hasExistingBinding: boolean rebindRequested: boolean + rebindUnchanged: boolean + rebindCooldownDays: number + nextRebindAt: string + platformChangeBindDay?: number + platformChangeBindTime?: number message: string comparison: CustomerBindingComparison } From ad59c87e1393dc402badec720a311c84e11c0862 Mon Sep 17 00:00:00 2001 From: zhaoxing <2558691827@qq.com> Date: Mon, 16 Nov 2026 14:00:17 +0800 Subject: [PATCH 04/15] =?UTF-8?q?fix(semi-auto):=20=E6=89=AB=E7=A0=81?= =?UTF-8?q?=E5=90=8E=E4=B8=BB=E5=8A=A8=E6=8F=90=E4=BA=A4=E6=8D=A2=E7=BB=91?= =?UTF-8?q?=E5=B9=B6=E9=80=8F=E5=87=BA=E8=99=8E=E7=89=99=E5=A4=B1=E8=B4=A5?= =?UTF-8?q?=E5=8E=9F=E5=9B=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/routes/customer-fulfillment.ts | 11 + .../semi-auto/huya-connector-client.test.ts | 41 ++++ .../semi-auto/huya-connector-client.ts | 18 ++ .../huya-native/huya-native-connector.ts | 191 +++++++++++++--- .../semi-auto/semi-auto-task-service.ts | 43 +++- .../pages/admin/AdminSemiAutoTasksPage.tsx | 8 +- .../CustomerFulfillmentPage.tsx | 215 +++++++++++++++--- .../src/services/customer-fulfillment.ts | 7 + .../src/types/customer-fulfillment.ts | 4 + 9 files changed, 475 insertions(+), 63 deletions(-) diff --git a/apps/backend/src/routes/customer-fulfillment.ts b/apps/backend/src/routes/customer-fulfillment.ts index 98507025..d3de6671 100644 --- a/apps/backend/src/routes/customer-fulfillment.ts +++ b/apps/backend/src/routes/customer-fulfillment.ts @@ -16,6 +16,7 @@ import { startPublicBinding, startPublicLogin, startPublicWeiboQrLogin, + submitPublicRebind, verifyPublicHuyaSmsChallenge, } from '../services/semi-auto/semi-auto-task-service.js' import { createRateLimitMiddleware, getParamRateLimitKey } from '../middleware/rate-limit.js' @@ -106,6 +107,16 @@ router.get( }), ) +router.post( + '/:orderNo/tasks/:taskId/binding/rebind', + writeLimit, + createRouteHandler((req) => submitPublicRebind(req.params.orderNo, req.params.taskId), { + successMessage: '换绑请求已提交', + errorMessage: '提交换绑失败', + scope: '[customer-fulfillment/:orderNo/tasks/:taskId/binding/rebind]', + }), +) + router.post( '/:orderNo/tasks/:taskId/binding/confirm', writeLimit, diff --git a/apps/backend/src/services/semi-auto/huya-connector-client.test.ts b/apps/backend/src/services/semi-auto/huya-connector-client.test.ts index a5205482..9ce63da9 100644 --- a/apps/backend/src/services/semi-auto/huya-connector-client.test.ts +++ b/apps/backend/src/services/semi-auto/huya-connector-client.test.ts @@ -202,3 +202,44 @@ test('重新扫码换绑会向 Connector 传递 force_rebind', async () => { globalThis.fetch = originalFetch } }) + +test('提交换绑复用 Connector confirm 端点并携带 rebind 标记', async () => { + const originalFetch = globalThis.fetch + let requestUrl = '' + let requestBody: Record = {} + globalThis.fetch = (async (url: string | URL | Request, init?: RequestInit) => { + requestUrl = String(url) + requestBody = JSON.parse(String(init?.body || '{}')) as Record + return new Response( + JSON.stringify({ + sessionId: 'session-1', + status: 'scanned', + qrImage: '', + qrExpiresAt: '', + qrUrl: '', + bindGameAccount: '微信用户', + bindGameRole: '大鲨鱼伊塞53', + bindGameRoleId: '1199608910400', + bindGameChannel: '安卓(android) · 微信', + rebindRequested: true, + rebindUnchanged: false, + rebindConfirmState: 'accepted', + rebindConfirmMessage: '', + message: '虎牙已受理换绑,正在等待角色生效', + }), + { status: 200, headers: { 'Content-Type': 'application/json' } }, + ) + }) as typeof fetch + try { + const session = await connector.submitHuyaRebind('session-1', 'external') + assert.equal( + requestUrl, + 'http://connector.test/api/internal/huya-semi-auto/sessions/session-1/binding/confirm', + ) + assert.deepEqual(requestBody, { rebind: true }) + assert.equal(session.rebindConfirmState, 'accepted') + assert.equal(session.rebindRequested, true) + } finally { + globalThis.fetch = originalFetch + } +}) diff --git a/apps/backend/src/services/semi-auto/huya-connector-client.ts b/apps/backend/src/services/semi-auto/huya-connector-client.ts index eeca2bae..58e56bbf 100644 --- a/apps/backend/src/services/semi-auto/huya-connector-client.ts +++ b/apps/backend/src/services/semi-auto/huya-connector-client.ts @@ -103,6 +103,8 @@ export type ConnectorBindingSession = { hasExistingBinding?: boolean rebindRequested?: boolean rebindUnchanged?: boolean + rebindConfirmState?: 'idle' | 'submitting' | 'accepted' | 'rejected' + rebindConfirmMessage?: string rebindCooldownDays?: number nextRebindAt?: string platformChangeBindDay?: number @@ -429,6 +431,22 @@ export async function confirmHuyaBinding( ) } +/** + * 扫码后由项目侧主动向虎牙提交换绑确认。 + * 外部 Connector 暂未提供独立端点时复用 confirm 端点(语义一致,幂等)。 + */ +export async function submitHuyaRebind( + sessionId: string, + mode: SemiAutoConnectorMode = defaultSemiAutoConnectorMode(), +): Promise { + if (mode === 'embedded') return huyaNativeConnector.submitRebind(sessionId) + return callConnector( + `/api/internal/huya-semi-auto/sessions/${encodeURIComponent(sessionId)}/binding/confirm`, + { method: 'POST', body: { rebind: true } }, + mode, + ) +} + export async function createHuyaBrowserTicket( input: { sessionId: string diff --git a/apps/backend/src/services/semi-auto/huya-native/huya-native-connector.ts b/apps/backend/src/services/semi-auto/huya-native/huya-native-connector.ts index 4bbe089d..8744bf0b 100644 --- a/apps/backend/src/services/semi-auto/huya-native/huya-native-connector.ts +++ b/apps/backend/src/services/semi-auto/huya-native/huya-native-connector.ts @@ -54,6 +54,8 @@ const CREDENTIAL_TTL_MS = 24 * 60 * 60 * 1000 const BINDING_QR_TTL_MS = 5 * 60 * 1000 const REBIND_WINDOW_DAYS = 7 const DAY_MS = 24 * 60 * 60 * 1000 +// 提交换绑后给虎牙留的生效时间;期间前端继续轮询,不提前判失败。 +const REBIND_EFFECT_WINDOW_MS = 60 * 1000 const BROWSER_TICKET_TTL_MS = 2 * 60 * 1000 const MAX_SESSIONS = 500 const NATIVE_TICKET_PREFIX = 'native-ticket-' @@ -76,6 +78,10 @@ type NativeBindState = { rebindRequested: boolean rebindScanned: boolean rebindUnchanged: boolean + rebindConfirmState: 'idle' | 'submitting' | 'accepted' | 'rejected' + rebindConfirmMessage: string + rebindConfirmAt: number + rebindEffectDeadlineMs: number rebindCooldownDays: number nextRebindAt: string changeBindTime: number @@ -156,6 +162,10 @@ function defaultBindingState(): NativeBindState { rebindRequested: false, rebindScanned: false, rebindUnchanged: false, + rebindConfirmState: 'idle', + rebindConfirmMessage: '', + rebindConfirmAt: 0, + rebindEffectDeadlineMs: 0, rebindCooldownDays: 0, nextRebindAt: '', changeBindTime: 0, @@ -188,8 +198,9 @@ export type RebindCooldownInput = { } /** - * 虎牙活动限制:每 7 个自然日允许换绑 1 次。 - * changeBindTime 为上次绑定/换绑时间(秒级 Unix 时间戳),changeBindDay 作为兜底剩余天数。 + * 虎牙活动提示:每 7 个自然日允许换绑 1 次。 + * 这里计算的是「本次绑定后预计下次可换绑时间」,只用于文案展示, + * 不能作为本次提交换绑的前置拦截;是否允许以 confirmBindActAccount 的返回为准。 */ export function resolveRebindCooldown( response: RebindCooldownInput | null | undefined, @@ -229,16 +240,16 @@ function applyRebindMeta( session.binding.changeBindDay = Number(response?.changeBindDay || 0) } -function rebindUnchangedMessage( +function rebindFailureMessage( roleName: string, - cooldownDays: number, + platformMessage: string, nextRebindAt: string, ): string { + // 优先展示虎牙原始原因(例如「7 天内只能换绑 1 次」),不要本地编造失败原因。 + const raw = readString(platformMessage) + if (raw) return `换绑未成功:${raw}` const next = rebindDateLabel(nextRebindAt) - if (cooldownDays > 0) { - return `扫码后仍识别到原绑定角色「${roleName}」;本活动 7 天内只能换绑 1 次${next ? `,预计下次换绑:${next}` : ''}` - } - return `扫码后仍识别到原绑定角色「${roleName}」,请确认微信中选择的角色或重新换绑` + return `换绑已提交,但平台仍返回原绑定角色「${roleName}」${next ? `,预计下次换绑:${next}` : ''};请稍后刷新或重新提交换绑` } function extractInt(value: unknown): number { @@ -763,9 +774,9 @@ export class HuyaNativeConnector { this.markRoleReady(session, role, hasExistingBinding && !session.binding.rebindRequested) if (session.binding.rebindRequested) { session.binding.message = session.binding.rebindUnchanged - ? rebindUnchangedMessage( + ? rebindFailureMessage( role.role, - session.binding.rebindCooldownDays, + session.binding.rebindConfirmMessage, session.binding.nextRebindAt, ) : '已识别待换绑角色,请确认换绑' @@ -833,6 +844,10 @@ export class HuyaNativeConnector { session.binding.rebindRequested = true session.binding.rebindScanned = false session.binding.rebindUnchanged = false + session.binding.rebindConfirmState = 'idle' + session.binding.rebindConfirmMessage = '' + session.binding.rebindConfirmAt = 0 + session.binding.rebindEffectDeadlineMs = 0 session.binding.baselineRoleKey = bindingRoleKey(role) } session.binding.status = 'qr_pending' @@ -847,6 +862,40 @@ export class HuyaNativeConnector { }) } + /** + * 扫码完成后由项目侧替客户点「确认绑定」。 + * confirmBindActAccount 确认的是虎牙侧已选中的角色,必须在读取新角色之前调用; + * 若客户已在虎牙弹窗里点过确认,重复调用是幂等的。 + */ + private async submitRebindLocked(session: NativeSession, rpc: HuyaRpcClient): Promise { + const { bindActId, outerActId } = configValues() + const now = this.now() + session.binding.rebindConfirmState = 'submitting' + session.binding.rebindConfirmMessage = '' + session.binding.rebindConfirmAt = now + try { + const confirmed = await rpc.confirmBindActAccount({ + uid: session.uid, + cookie: session.cookie, + bindActId, + outerActId, + }) + if (confirmed && confirmed.status === 200) { + session.binding.rebindConfirmState = 'accepted' + session.binding.rebindEffectDeadlineMs = now + REBIND_EFFECT_WINDOW_MS + session.binding.message = '虎牙已受理换绑,正在等待角色生效' + return + } + session.binding.rebindConfirmState = 'rejected' + session.binding.rebindConfirmMessage = confirmed?.msg || '虎牙未接受本次换绑' + session.binding.message = `虎牙未接受本次换绑:${session.binding.rebindConfirmMessage}` + } catch (error) { + session.binding.rebindConfirmState = 'rejected' + session.binding.rebindConfirmMessage = errorMessage(error) + session.binding.message = `提交换绑失败:${session.binding.rebindConfirmMessage}` + } + } + async pollBinding(sessionId: string): Promise { return this.withLock(sessionId, async () => { const session = this.requireAuthenticatedSession(sessionId) @@ -865,7 +914,9 @@ export class HuyaNativeConnector { } if (qrStatus.isScan) { session.binding.status = 'scanned' - session.binding.message = '已扫码,等待绑定完成' + session.binding.message = session.binding.rebindRequested + ? '已扫码,请在虎牙确认框中选中目标角色' + : '已扫码,等待绑定完成' } if (qrStatus.isScan || qrStatus.isCompleted) { session.binding.rebindScanned = true @@ -877,6 +928,15 @@ export class HuyaNativeConnector { return this.bindingView(session) } const rpc = new HuyaRpcClient({ fetchImpl: this.fetchImpl, timeoutMs: this.rpcTimeoutMs }) + // 小程序流程结束后立即由项目侧提交换绑,不再等角色自己变化。 + if ( + session.binding.rebindRequested && + session.binding.rebindScanned && + qrCompleted && + session.binding.rebindConfirmState === 'idle' + ) { + await this.submitRebindLocked(session, rpc) + } const response = await rpc.checkUserBindGameAccount({ uid: session.uid, cookie: session.cookie, @@ -898,20 +958,36 @@ export class HuyaNativeConnector { const changedRole = !session.binding.baselineRoleKey || roleKey !== session.binding.baselineRoleKey if (rebindRequested && !changedRole) { - if (qrCompleted || session.binding.rebindUnchanged) { - // 扫码完成但虎牙仍返回原角色:保留 rebind 状态,明确告知未换绑及冷却原因, - // 不能清空 rebindRequested,否则 confirmBinding 会误判为“使用已有绑定”。 + if (session.binding.rebindConfirmState === 'rejected') { + // 虎牙明确拒绝:保留 rebind 状态并展示虎牙原文,不能清空 rebindRequested。 session.binding.rebindUnchanged = true this.markRoleReady(session, role, hasExistingBinding) - session.binding.message = rebindUnchangedMessage( + session.binding.message = rebindFailureMessage( role.role, - session.binding.rebindCooldownDays, + session.binding.rebindConfirmMessage, session.binding.nextRebindAt, ) - } else { - session.binding.status = 'scanned' - session.binding.message = '已扫码,正在等待换绑角色生效' + return this.bindingView(session) } + if (session.binding.rebindConfirmState === 'accepted') { + if (this.now() < session.binding.rebindEffectDeadlineMs) { + session.binding.status = 'scanned' + session.binding.message = '虎牙已受理换绑,正在等待角色生效' + } else { + session.binding.rebindUnchanged = true + this.markRoleReady(session, role, hasExistingBinding) + session.binding.message = rebindFailureMessage( + role.role, + session.binding.rebindConfirmMessage, + session.binding.nextRebindAt, + ) + } + return this.bindingView(session) + } + session.binding.status = 'scanned' + session.binding.message = qrCompleted + ? '扫码已完成,请点击「已选好角色,提交换绑」' + : '已扫码,请在虎牙确认框中选中目标角色' return this.bindingView(session) } if (rebindRequested) session.binding.rebindUnchanged = false @@ -932,6 +1008,11 @@ export class HuyaNativeConnector { const session = this.requireAuthenticatedSession(sessionId) const { bindActId, outerActId } = configValues() const rpc = new HuyaRpcClient({ fetchImpl: this.fetchImpl, timeoutMs: this.rpcTimeoutMs }) + const rebindRequested = session.binding.rebindRequested + if (rebindRequested && session.binding.rebindConfirmState !== 'accepted') { + // 客户点确认前再兜底提交一次,避免小程序扫码后项目没来得及自动提交。 + await this.submitRebindLocked(session, rpc) + } const response = await rpc.checkUserBindGameAccount({ uid: session.uid, cookie: session.cookie, @@ -945,28 +1026,30 @@ export class HuyaNativeConnector { errorCode: 'huya_bind_role_not_ready', }) } - const rebindRequested = session.binding.rebindRequested applyRebindMeta(session, response, this.now()) if ( rebindRequested && session.binding.baselineRoleKey && bindingRoleKey(role) === session.binding.baselineRoleKey ) { - const cooldownDays = session.binding.rebindCooldownDays - const next = rebindDateLabel(session.binding.nextRebindAt) + // 只有虎牙实际未生效时才拦截;冷却原因以虎牙返回的原文为准。 throw createHttpError( - cooldownDays > 0 - ? `换绑未生效:平台仍返回原绑定角色「${role.role}」;本活动 7 天内只能换绑 1 次${next ? `,预计下次换绑:${next}` : ''}` - : `换绑未生效:平台仍返回原绑定角色「${role.role}」,请重新扫码选择正确角色`, + rebindFailureMessage( + role.role, + session.binding.rebindConfirmMessage, + session.binding.nextRebindAt, + ), { statusCode: 409, errorCode: - cooldownDays > 0 ? 'huya_bind_rebind_cooldown' : 'huya_bind_rebind_not_ready', + session.binding.rebindConfirmState === 'rejected' + ? 'huya_bind_rebind_rejected' + : 'huya_bind_rebind_not_effective', }, ) } const useExistingBinding = hasExistingHuyaBinding(response) && !rebindRequested - if (!useExistingBinding) { + if (!useExistingBinding && session.binding.rebindConfirmState !== 'accepted') { const confirmed = await rpc.confirmBindActAccount({ uid: session.uid, cookie: session.cookie, @@ -986,6 +1069,10 @@ export class HuyaNativeConnector { session.binding.rebindRequested = false session.binding.rebindScanned = false session.binding.rebindUnchanged = false + session.binding.rebindConfirmState = 'idle' + session.binding.rebindConfirmMessage = '' + session.binding.rebindConfirmAt = 0 + session.binding.rebindEffectDeadlineMs = 0 session.binding.rebindCooldownDays = 0 session.binding.nextRebindAt = '' session.binding.baselineRoleKey = '' @@ -998,6 +1085,54 @@ export class HuyaNativeConnector { }) } + /** 客户手动点击「已选好角色,提交换绑」时调用。 */ + async submitRebind(sessionId: string): Promise { + return this.withLock(sessionId, async () => { + const session = this.requireAuthenticatedSession(sessionId) + if (!session.binding.rebindRequested) { + throw createHttpError('当前没有待换绑的角色,请重新扫码换绑', { + statusCode: 409, + errorCode: 'huya_bind_rebind_not_requested', + }) + } + const { bindActId, outerActId } = configValues() + const rpc = new HuyaRpcClient({ fetchImpl: this.fetchImpl, timeoutMs: this.rpcTimeoutMs }) + await this.submitRebindLocked(session, rpc) + const response = await rpc.checkUserBindGameAccount({ + uid: session.uid, + cookie: session.cookie, + bindActId, + outerActId, + }) + if (response && response.status === 200) { + const role = parseRole(response) + applyRebindMeta(session, response, this.now()) + if (role.role) { + const changedRole = + !session.binding.baselineRoleKey || + bindingRoleKey(role) !== session.binding.baselineRoleKey + if (changedRole) { + session.binding.rebindUnchanged = false + this.markRoleReady(session, role, false) + session.binding.message = '已识别换绑角色,请确认换绑' + } else if (session.binding.rebindConfirmState === 'rejected') { + session.binding.rebindUnchanged = true + this.markRoleReady(session, role, hasExistingHuyaBinding(response)) + session.binding.message = rebindFailureMessage( + role.role, + session.binding.rebindConfirmMessage, + session.binding.nextRebindAt, + ) + } else { + session.binding.status = 'scanned' + session.binding.message = '虎牙已受理换绑,正在等待角色生效' + } + } + } + return this.bindingView(session) + }) + } + async createBrowserTicket(input: { sessionId: string targetUrl?: string @@ -1276,6 +1411,8 @@ export class HuyaNativeConnector { hasExistingBinding: binding.hasExistingBinding, rebindRequested: binding.rebindRequested, rebindUnchanged: binding.rebindUnchanged, + rebindConfirmState: binding.rebindConfirmState, + rebindConfirmMessage: binding.rebindConfirmMessage, rebindCooldownDays: binding.rebindCooldownDays, nextRebindAt: binding.nextRebindAt, platformChangeBindDay: binding.changeBindDay, diff --git a/apps/backend/src/services/semi-auto/semi-auto-task-service.ts b/apps/backend/src/services/semi-auto/semi-auto-task-service.ts index 1154077d..ba18ee7e 100644 --- a/apps/backend/src/services/semi-auto/semi-auto-task-service.ts +++ b/apps/backend/src/services/semi-auto/semi-auto-task-service.ts @@ -27,6 +27,7 @@ import { revokeHuyaSession, sendHuyaSmsCode, startHuyaBinding, + submitHuyaRebind, consumeHuyaBrowserTicket, verifyHuyaSmsChallenge, type ConnectorBindingSession, @@ -956,6 +957,8 @@ function mapBindingUpdate(session: ConnectorBindingSession) { hasExistingBinding: session.hasExistingBinding === true, rebindRequested: session.rebindRequested === true, rebindUnchanged: session.rebindUnchanged === true, + rebindConfirmState: session.rebindConfirmState || 'idle', + rebindConfirmMessage: String(session.rebindConfirmMessage || ''), rebindCooldownDays: Number(session.rebindCooldownDays || 0), nextRebindAt: String(session.nextRebindAt || ''), platformChangeBindDay: Number(session.platformChangeBindDay || 0), @@ -1139,6 +1142,8 @@ async function updateBindingTask( verdict: comparison.verdict, rebindRequested: mapped.rebindRequested, rebindUnchanged: mapped.rebindUnchanged, + rebindConfirmState: mapped.rebindConfirmState, + rebindConfirmMessage: mapped.rebindConfirmMessage, rebindCooldownDays: mapped.rebindCooldownDays, nextRebindAt: mapped.nextRebindAt, changeBindDay: mapped.platformChangeBindDay, @@ -1159,6 +1164,8 @@ async function updateBindingTask( hasExistingBinding: mapped.hasExistingBinding, rebindRequested: mapped.rebindRequested, rebindUnchanged: mapped.rebindUnchanged, + rebindConfirmState: mapped.rebindConfirmState, + rebindConfirmMessage: mapped.rebindConfirmMessage, rebindCooldownDays: mapped.rebindCooldownDays, nextRebindAt: mapped.nextRebindAt, platformChangeBindDay: mapped.platformChangeBindDay, @@ -1358,8 +1365,8 @@ export async function confirmPublicBinding(orderNoInput: unknown, taskIdInput: u throw createHttpError(session.message || '换绑未生效:平台仍返回原绑定角色,请重新扫码', { statusCode: 409, errorCode: - Number(session.rebindCooldownDays || 0) > 0 - ? 'semi_auto_binding_rebind_cooldown' + session.rebindConfirmState === 'rejected' + ? 'semi_auto_binding_rebind_rejected' : 'semi_auto_binding_rebind_unchanged', }) } @@ -1380,6 +1387,38 @@ export async function confirmPublicBinding(orderNoInput: unknown, taskIdInput: u return { task: mapTask(updated), binding } } +/** + * 客户在微信里选好目标角色后,由项目侧主动向虎牙提交换绑确认。 + * 与「确认绑定」不同,这一步只提交换绑,不把任务标记为已确认。 + */ +export async function submitPublicRebind(orderNoInput: unknown, taskIdInput: unknown) { + const orderNo = normalizeOrderNo(orderNoInput) + const taskId = normalizeId(taskIdInput) + const task = await loadTaskForOrder(orderNo, taskId) + if (task.execution_status === 'completed' || task.execution_status === 'cancelled') { + throw createHttpError('当前订单已结束,不能提交换绑', { + statusCode: 409, + errorCode: 'semi_auto_task_closed', + }) + } + if (task.platform !== 'huya') { + throw createHttpError('当前平台不需要换绑游戏角色', { + statusCode: 409, + errorCode: 'semi_auto_rebind_not_supported', + }) + } + if (!task.connector_session_id || task.login_status !== 'authenticated') { + throw createHttpError('请先完成平台登录', { + statusCode: 409, + errorCode: 'semi_auto_login_required', + }) + } + const session = await submitHuyaRebind(task.connector_session_id, task.connector_mode) + const binding = await updateBindingTask(task, session, 'customer') + const updated = await loadTask(task.id) + return { task: mapTask(updated), binding } +} + export async function sendPublicHuyaSmsCode( orderNoInput: unknown, taskIdInput: unknown, diff --git a/apps/frontend/src/pages/admin/AdminSemiAutoTasksPage.tsx b/apps/frontend/src/pages/admin/AdminSemiAutoTasksPage.tsx index 6f65684d..fea9e891 100644 --- a/apps/frontend/src/pages/admin/AdminSemiAutoTasksPage.tsx +++ b/apps/frontend/src/pages/admin/AdminSemiAutoTasksPage.tsx @@ -731,7 +731,7 @@ export default function AdminSemiAutoTasksPage() { 0 + event.detail.rebindConfirmState === 'rejected' ? 'warning' : 'secondary' } @@ -745,6 +745,12 @@ export default function AdminSemiAutoTasksPage() { : ''} ) : null} + {event.eventType === 'binding_status_changed' && + event.detail?.rebindConfirmMessage ? ( + + 虎牙返回:{String(event.detail.rebindConfirmMessage)} + + ) : null} ), }))} diff --git a/apps/frontend/src/pages/customer-fulfillment/CustomerFulfillmentPage.tsx b/apps/frontend/src/pages/customer-fulfillment/CustomerFulfillmentPage.tsx index c060d488..93af3c9d 100644 --- a/apps/frontend/src/pages/customer-fulfillment/CustomerFulfillmentPage.tsx +++ b/apps/frontend/src/pages/customer-fulfillment/CustomerFulfillmentPage.tsx @@ -26,6 +26,7 @@ import { startCustomerBinding, startCustomerLogin, startCustomerWeiboQrLogin, + submitCustomerRebind, verifyCustomerHuyaSmsChallenge, type CustomerHuyaChallengeSolution, type CustomerHuyaSmsChallenge, @@ -306,6 +307,8 @@ export default function CustomerFulfillmentPage() { if (!bindingInfo?.comparison) return // 换绑后仍是原角色时只展示失败原因,不能自动弹出确认框。 if (bindingInfo.rebindUnchanged) return + // 平台角色与已填资料不一致时先引导同步资料,不能直接弹确认框。 + if (bindingInfo.comparison.verdict === 'mismatch') return const key = `${selectedTask.id}:${bindingInfo.bindGameRoleId || ''}` if (autoOpenedRoleRef.current === key) return autoOpenedRoleRef.current = key @@ -504,7 +507,18 @@ export default function CustomerFulfillmentPage() { if (nextTask.bindingStatus === 'role_ready') { if (nextBinding?.rebindUnchanged) { setBindingConfirmOpen(false) - message.warning(nextBinding.message || '换绑未生效,请查看下方原因') + if (nextBinding.rebindConfirmState === 'rejected') { + message.error(nextBinding.message || '虎牙未接受本次换绑') + } else { + message.warning(nextBinding.message || '换绑未生效,请查看下方原因') + } + return + } + if (nextBinding?.comparison?.verdict === 'mismatch') { + setBindingConfirmOpen(false) + message.warning( + nextBinding.comparison.message || '平台角色与已填资料不一致,请先同步资料', + ) return } setBindingConfirmOpen(true) @@ -519,7 +533,11 @@ export default function CustomerFulfillmentPage() { if (openConfirm) setBindingConfirmOpen(false) const detail = nextBinding?.message || '' if (nextTask.bindingStatus === 'scanned') { - message.info(detail || '已扫码,正在等待虎牙平台换绑生效,请稍后再点击刷新') + if (nextBinding?.rebindConfirmState === 'accepted') { + message.info('虎牙已受理换绑,正在等待角色生效') + return + } + message.info(detail || '已扫码,请选好角色后点「已选好角色,提交换绑」') return } if (nextTask.bindingStatus === 'qr_pending') { @@ -548,6 +566,69 @@ export default function CustomerFulfillmentPage() { } } + async function handleSubmitRebind() { + if (!selectedTask) return + setBindingLoading(true) + try { + const response = await submitCustomerRebind(orderNo, selectedTask.id) + const nextTask = response.data.task + const nextBinding = response.data.binding + setTasks((current) => current.map((task) => (task.id === nextTask.id ? nextTask : task))) + if (nextBinding) setBindingInfo(nextBinding) + setBindingConfirmOpen(false) + if (nextBinding?.rebindUnchanged || nextBinding?.rebindConfirmState === 'rejected') { + message.error(nextBinding.message || '虎牙未接受本次换绑') + return + } + if (nextTask.bindingStatus === 'role_ready') { + message.success('换绑已生效,请核对角色后确认绑定') + return + } + message.info('已向虎牙提交换绑,正在等待角色生效') + } catch (error) { + if (isHuyaSessionExpired(error)) { + setBindingSessionExpired(true) + setBindingConfirmOpen(false) + message.warning('虎牙登录会话已过期,请重新登录') + return + } + message.error(error instanceof Error ? error.message : '提交换绑失败') + } finally { + setBindingLoading(false) + } + } + + async function handleSyncBindingProfile() { + if (!selectedTask) return + const comparison = bindingInfo?.comparison + if (!comparison) return + const roleName = comparison.boundRoleName + const roleId = comparison.boundRoleId + const serverZone = comparison.boundZone + if (!roleName || !roleId || !/^\d+$/.test(roleId) || !serverZone) { + message.warning('平台角色信息不完整,请点「修改资料」手动填写') + return + } + setProfileSaving(true) + try { + const response = await saveCustomerTaskProfile(orderNo, selectedTask.id, { + roleName, + roleId, + serverZone, + }) + setTasks((current) => + current.map((task) => (task.id === response.data.task.id ? response.data.task : task)), + ) + const bindingResponse = await pollCustomerBinding(orderNo, selectedTask.id) + if (bindingResponse.data.binding) setBindingInfo(bindingResponse.data.binding) + message.success('资料已按平台角色同步,请核对后确认绑定') + } catch (error) { + message.error(error instanceof Error ? error.message : '同步角色资料失败') + } finally { + setProfileSaving(false) + } + } + async function handleConfirmBinding() { if (!selectedTask) return setBindingLoading(true) @@ -646,10 +727,16 @@ export default function CustomerFulfillmentPage() { })() const bindingRoleName = bindingInfo?.bindGameRole || selectedTask?.bindGameRole || '' const rebindUnchanged = bindingInfo?.rebindUnchanged === true - const rebindCooldownDays = Number(bindingInfo?.rebindCooldownDays || 0) + const rebindConfirmState = bindingInfo?.rebindConfirmState || 'idle' + const rebindRejected = rebindConfirmState === 'rejected' + const rebindAccepted = rebindConfirmState === 'accepted' const nextRebindText = bindingInfo?.nextRebindAt ? formatAdminDateTime(bindingInfo.nextRebindAt) : '' + const comparisonMismatch = + selectedTask?.bindingStatus === 'role_ready' && + !rebindUnchanged && + bindingComparison?.verdict === 'mismatch' const showProfileForm = showBindingStage && profileEditing const bindingCustomerReady = Boolean( bindingComparison?.customerRoleId || bindingComparison?.customerRoleName, @@ -990,7 +1077,11 @@ export default function CustomerFulfillmentPage() { {!bindingSessionExpired ? ( rebindUnchanged ? ( -
换绑未生效,请查看下方原因
+
+ {rebindRejected + ? '虎牙未接受本次换绑,请查看下方原因' + : '换绑未生效,请查看下方原因'} +
) : selectedTask?.bindingStatus === 'role_ready' ? (
已识别绑定角色,请核对后确认
) : selectedTask?.bindingStatus === 'confirmed' || bindingRoleId ? ( @@ -1072,13 +1163,16 @@ export default function CustomerFulfillmentPage() {

请使用微信APP扫码进行游戏角色绑定

{selectedTask?.bindingStatus === 'scanned' - ? '请在微信中完成角色绑定确认,再点击下方按钮进入下一步' - : '扫码后请在微信确认框中核对目标角色;本活动 7 天内只能换绑 1 次'} + ? rebindAccepted + ? '已向虎牙提交换绑,正在等待角色生效,请稍候刷新。' + : bindingInfo?.rebindRequested + ? '扫码后请在虎牙弹窗中选中目标角色;选好后点下方「已选好角色,提交换绑」。' + : '请在微信中完成角色绑定确认,再点击下方按钮进入下一步。' + : '扫码后请在微信确认框中核对目标角色。'}

- {rebindCooldownDays > 0 ? ( + {nextRebindText ? (

- 平台提示:预计下次可换绑 - {nextRebindText ? ` ${nextRebindText}` : '需等待 7 天'};本次扫码可能不会生效。 + 本次换绑成功后,下次可换绑:{nextRebindText}。

) : null}

@@ -1094,15 +1188,29 @@ export default function CustomerFulfillmentPage() { 刷新二维码

- + {selectedTask?.bindingStatus === 'scanned' && + bindingInfo?.rebindRequested && + !rebindAccepted ? ( + + ) : ( + + )}
) : null} @@ -1140,24 +1248,21 @@ export default function CustomerFulfillmentPage() { {rebindUnchanged ? ( - 扫码已完成,但平台仍返回原绑定角色: + 平台仍返回原绑定角色: {bindingRoleName || '未识别到角色'} - {rebindCooldownDays > 0 ? ( - - 原因:本活动 7 天内只能换绑 1 次 - {nextRebindText ? `,预计下次可换绑:${nextRebindText}` : ''}。 - + {bindingInfo?.rebindConfirmMessage ? ( + 虎牙原因:{bindingInfo.rebindConfirmMessage} + ) : nextRebindText ? ( + 预计下次可换绑:{nextRebindText}。 ) : ( - - 请在微信确认框中核对目标角色后重新换绑;如持续失败请联系客服。 - + 请核对虎牙弹窗中选中的目标角色后重新提交。 )} } @@ -1172,6 +1277,28 @@ export default function CustomerFulfillmentPage() { .join(' · ')} /> )} + {comparisonMismatch && bindingComparison ? ( + + + 平台角色:{bindingComparison.boundZone || '区服未知'} ·{' '} + {bindingComparison.boundRoleName || '角色未知'}(ID{' '} + {bindingComparison.boundRoleId || '未知'}) + + + 已填资料:{bindingComparison.customerZone || '区服未填'} ·{' '} + {bindingComparison.customerRoleName || '角色未填'}(ID{' '} + {bindingComparison.customerRoleId || '未填'}) + + 三项一致后才能提交确认;可一键同步平台角色。 + + } + /> + ) : null} {!bindingPendingUid && !rebindUnchanged ? ( void handleRefreshBinding(true)} + onClick={() => void handleSubmitRebind()} > - 重新扫码换绑 + 重新提交换绑 +
+ ) : comparisonMismatch ? ( +
+ +
) : ( diff --git a/apps/frontend/src/services/customer-fulfillment.ts b/apps/frontend/src/services/customer-fulfillment.ts index 036843a2..fb8f912f 100644 --- a/apps/frontend/src/services/customer-fulfillment.ts +++ b/apps/frontend/src/services/customer-fulfillment.ts @@ -66,6 +66,13 @@ export function confirmCustomerBinding(orderNo: string, taskId: number) { ) } +export function submitCustomerRebind(orderNo: string, taskId: number) { + return apiPost<{ task: CustomerSemiAutoTask; binding: CustomerBindingInfo }>( + `/api/v1/customer-fulfillment/${encodeURIComponent(orderNo)}/tasks/${taskId}/binding/rebind`, + {}, + ) +} + type CustomerHuyaChallengeBase = { image: string width: number diff --git a/apps/frontend/src/types/customer-fulfillment.ts b/apps/frontend/src/types/customer-fulfillment.ts index 849b100f..711b622a 100644 --- a/apps/frontend/src/types/customer-fulfillment.ts +++ b/apps/frontend/src/types/customer-fulfillment.ts @@ -2,8 +2,10 @@ export type CustomerBindingComparison = { verdict: 'match' | 'mismatch' | 'unknown' customerRoleName: string customerRoleId: string + customerZone: string boundRoleName: string boundRoleId: string + boundZone: string message: string } @@ -58,6 +60,8 @@ export type CustomerBindingInfo = { hasExistingBinding: boolean rebindRequested: boolean rebindUnchanged: boolean + rebindConfirmState: 'idle' | 'submitting' | 'accepted' | 'rejected' + rebindConfirmMessage: string rebindCooldownDays: number nextRebindAt: string platformChangeBindDay?: number From 64281aefb028e7fd6626a0122ef214d0fb99511d Mon Sep 17 00:00:00 2001 From: zhaoxing <2558691827@qq.com> Date: Mon, 16 Nov 2026 14:46:17 +0800 Subject: [PATCH 05/15] =?UTF-8?q?fix(semi-auto):=20=E6=8D=A2=E7=BB=91?= =?UTF-8?q?=E5=A4=B1=E8=B4=A5=E5=8D=A1=E9=80=8F=E5=87=BA=E8=99=8E=E7=89=99?= =?UTF-8?q?=E5=8E=9F=E5=9B=A0=E4=B8=8E=E4=B8=8B=E6=AC=A1=E6=8D=A2=E7=BB=91?= =?UTF-8?q?=E6=97=B6=E9=97=B4=EF=BC=8C=E4=BC=9A=E8=AF=9D=E8=BF=87=E6=9C=9F?= =?UTF-8?q?=E5=8F=AF=E8=BF=94=E5=9B=9E=E7=99=BB=E5=BD=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1) 下次换绑时间改按虎牙日界口径:changeBindTime 是绑定日次日 00:00,(日界 + changeBindDay - 1) 天;11-16 绑定 → 2026-11-23,与虎牙绑定页一致(原 +7 天会显示 11-24)。 2) 客户页换绑失败卡同时展示虎牙原文原因、预计下次可换绑时间与「每 7 个自然日可换绑 1 次」规则。 3) 绑定会话失效时给出整行「返回登录」入口;二维码加载失败可重试;告警标题统一为亮色不再黑字;提交类按钮统一 56px 蓝色主按钮。 --- .../huya-native/huya-native-connector.ts | 16 ++- .../huya-native/rebind-cooldown.test.ts | 12 ++ .../CustomerFulfillmentPage.tsx | 124 +++++++++++++----- apps/frontend/src/styles/client.css | 88 +++++++++++-- 4 files changed, 194 insertions(+), 46 deletions(-) diff --git a/apps/backend/src/services/semi-auto/huya-native/huya-native-connector.ts b/apps/backend/src/services/semi-auto/huya-native/huya-native-connector.ts index 8744bf0b..18f54be0 100644 --- a/apps/backend/src/services/semi-auto/huya-native/huya-native-connector.ts +++ b/apps/backend/src/services/semi-auto/huya-native/huya-native-connector.ts @@ -209,10 +209,18 @@ export function resolveRebindCooldown( if (!response || (response.status !== undefined && response.status !== 200)) { return { days: 0, nextRebindAt: '' } } + const changeBindDay = Number(response.changeBindDay || 0) + const hasPlatformWindow = + Number.isFinite(changeBindDay) && changeBindDay > 0 && changeBindDay <= 30 + const windowDays = hasPlatformWindow ? Math.round(changeBindDay) : REBIND_WINDOW_DAYS const changeBindTime = Number(response.accountData?.changeBindTime || 0) if (Number.isFinite(changeBindTime) && changeBindTime > 0) { const changedAtMs = changeBindTime > 1e12 ? changeBindTime : changeBindTime * 1000 - const nextRebindMs = changedAtMs + REBIND_WINDOW_DAYS * DAY_MS + // 虎牙把「本次绑定日」记成次日 00:00 的日界:11-16 绑定 → changeBindTime = 2026-11-17 00:00, + // 配合 changeBindDay = 7,绑定页提示「预计下次换绑时间 2026/11/23」。 + // 因此下次可换绑 = 日界 + (窗口天数 - 1) 天;不能用 +7 天,否则会显示成 11-24。 + const offsetDays = hasPlatformWindow ? Math.max(windowDays - 1, 0) : REBIND_WINDOW_DAYS + const nextRebindMs = changedAtMs + offsetDays * DAY_MS if (nextRebindMs > now) { return { days: Math.ceil((nextRebindMs - now) / DAY_MS), @@ -220,10 +228,8 @@ export function resolveRebindCooldown( } } } - const changeBindDay = Number(response.changeBindDay || 0) - if (Number.isFinite(changeBindDay) && changeBindDay > 0 && changeBindDay <= 30) { - const days = Math.round(changeBindDay) - return { days, nextRebindAt: iso(now + days * DAY_MS) } + if (hasPlatformWindow) { + return { days: windowDays, nextRebindAt: iso(now + windowDays * DAY_MS) } } return { days: 0, nextRebindAt: '' } } diff --git a/apps/backend/src/services/semi-auto/huya-native/rebind-cooldown.test.ts b/apps/backend/src/services/semi-auto/huya-native/rebind-cooldown.test.ts index 0cbfb5d3..f99df006 100644 --- a/apps/backend/src/services/semi-auto/huya-native/rebind-cooldown.test.ts +++ b/apps/backend/src/services/semi-auto/huya-native/rebind-cooldown.test.ts @@ -20,6 +20,18 @@ test('换绑冷却:changeBindTime 为初次绑定时间时,下次换绑为 7 assert.equal(result.nextRebindAt.slice(0, 10), '2026-11-23') }) +test('换绑冷却:按虎牙日界推算(11-16 绑定 → 11-23 才能换绑)', () => { + // 实测 task 34:changeBindTime = 1794844800 = 2026-11-17 00:00 +08:00,changeBindDay = 7。 + const now = Date.UTC(2026, 10, 16, 6, 31) // 2026-11-16 14:31 +08:00 + const result = resolveRebindCooldown( + { status: 200, changeBindDay: 7, accountData: { changeBindTime: 1794844800 } }, + now, + ) + assert.equal(result.days, 7) + // 2026-11-23 00:00 +08:00,与虎牙绑定页「预计下次换绑时间 2026/11/23」一致。 + assert.equal(result.nextRebindAt, '2026-11-22T16:00:00.000Z') +}) + test('换绑冷却:changeBindTime 已超过 7 天时不再限制', () => { const result = resolveRebindCooldown( { diff --git a/apps/frontend/src/pages/customer-fulfillment/CustomerFulfillmentPage.tsx b/apps/frontend/src/pages/customer-fulfillment/CustomerFulfillmentPage.tsx index 93af3c9d..726e089b 100644 --- a/apps/frontend/src/pages/customer-fulfillment/CustomerFulfillmentPage.tsx +++ b/apps/frontend/src/pages/customer-fulfillment/CustomerFulfillmentPage.tsx @@ -82,6 +82,7 @@ export default function CustomerFulfillmentPage() { const autoOpenedRoleRef = useRef('') // Connector 重启或会话被回收后,绑定/确认接口会返回 huya_native_session_not_found。 const [bindingSessionExpired, setBindingSessionExpired] = useState(false) + const [bindingLoadError, setBindingLoadError] = useState('') const selectedTask = useMemo( () => tasks.find((task) => task.id === selectedTaskId) || tasks[0] || null, @@ -137,6 +138,7 @@ export default function CustomerFulfillmentPage() { hydratingBindingRef.current = false autoOpenedRoleRef.current = '' setBindingSessionExpired(false) + setBindingLoadError('') }, [selectedTask?.id]) useEffect(() => { @@ -241,13 +243,16 @@ export default function CustomerFulfillmentPage() { current.map((task) => (task.id === response.data.task.id ? response.data.task : task)), ) setBindingInfo(response.data.binding) + setBindingLoadError('') }) .catch((error) => { if (isHuyaSessionExpired(error)) { setBindingSessionExpired(true) return } - message.error(error instanceof Error ? error.message : '创建绑定二维码失败') + const detail = error instanceof Error ? error.message : '创建绑定二维码失败' + setBindingLoadError(detail) + message.error(detail) }) .finally(() => { startingBindingRef.current = false @@ -263,6 +268,7 @@ export default function CustomerFulfillmentPage() { useEffect(() => { if (!selectedTask || !orderNo || selectedTask.platform !== 'huya') return + if (bindingSessionExpired) return if (!['qr_pending', 'scanned'].includes(selectedTask.bindingStatus)) return const tick = async () => { try { @@ -271,19 +277,35 @@ export default function CustomerFulfillmentPage() { current.map((task) => (task.id === response.data.task.id ? response.data.task : task)), ) if (response.data.binding) setBindingInfo(response.data.binding) - } catch { - // 短暂轮询失败不打断客户页面,下一轮继续。 + setBindingLoadError('') + } catch (error) { + if (isHuyaSessionExpired(error)) { + setBindingSessionExpired(true) + setBindingConfirmOpen(false) + return + } + // 非会话错误不要静默:二维码区域会展示可重试的错误,避免一直转圈。 + setBindingLoadError(error instanceof Error ? error.message : '刷新绑定状态失败') } } + // 先立即请求一次,会话已失效时不必等 3 秒轮询。 + void tick() const timer = window.setInterval(() => { void tick() }, POLL_INTERVAL_MS) return () => window.clearInterval(timer) - }, [orderNo, selectedTask?.bindingStatus, selectedTask?.id, selectedTask?.platform]) + }, [ + bindingSessionExpired, + orderNo, + selectedTask?.bindingStatus, + selectedTask?.id, + selectedTask?.platform, + ]) // 进入 role_ready 时补一次绑定详情,保证确认弹窗能拿到两侧角色 ID。 useEffect(() => { if (!selectedTask || !orderNo || selectedTask.platform !== 'huya') return + if (bindingSessionExpired) return if (selectedTask.bindingStatus !== 'role_ready' || bindingInfo || hydratingBindingRef.current) return hydratingBindingRef.current = true @@ -293,14 +315,26 @@ export default function CustomerFulfillmentPage() { current.map((task) => (task.id === response.data.task.id ? response.data.task : task)), ) if (response.data.binding) setBindingInfo(response.data.binding) + setBindingLoadError('') }) .catch((error) => { - if (isHuyaSessionExpired(error)) setBindingSessionExpired(true) + if (isHuyaSessionExpired(error)) { + setBindingSessionExpired(true) + return + } + setBindingLoadError(error instanceof Error ? error.message : '刷新绑定状态失败') }) .finally(() => { hydratingBindingRef.current = false }) - }, [bindingInfo, orderNo, selectedTask?.bindingStatus, selectedTask?.id, selectedTask?.platform]) + }, [ + bindingInfo, + bindingSessionExpired, + orderNo, + selectedTask?.bindingStatus, + selectedTask?.id, + selectedTask?.platform, + ]) useEffect(() => { if (!selectedTask || selectedTask.bindingStatus !== 'role_ready') return @@ -355,6 +389,11 @@ export default function CustomerFulfillmentPage() { ) setLoginInfo(response.data.login) setBindingSessionExpired(false) + setBindingLoadError('') + setBindingInfo(null) + setBindingConfirmOpen(false) + setBindingSecondsLeft(0) + window.scrollTo({ top: 0, behavior: 'smooth' }) } catch (error) { message.error(error instanceof Error ? error.message : '创建登录二维码失败') } finally { @@ -481,6 +520,7 @@ export default function CustomerFulfillmentPage() { current.map((task) => (task.id === response.data.task.id ? response.data.task : task)), ) setBindingInfo(response.data.binding) + setBindingLoadError('') setBindingConfirmOpen(false) } catch (error) { if (isHuyaSessionExpired(error)) { @@ -489,7 +529,9 @@ export default function CustomerFulfillmentPage() { message.warning('虎牙登录会话已过期,请重新登录') return } - message.error(error instanceof Error ? error.message : '创建绑定二维码失败') + const detail = error instanceof Error ? error.message : '创建绑定二维码失败' + setBindingLoadError(detail) + message.error(detail) } finally { setBindingLoading(false) } @@ -504,6 +546,7 @@ export default function CustomerFulfillmentPage() { const nextBinding = response.data.binding setTasks((current) => current.map((task) => (task.id === nextTask.id ? nextTask : task))) if (nextBinding) setBindingInfo(nextBinding) + setBindingLoadError('') if (nextTask.bindingStatus === 'role_ready') { if (nextBinding?.rebindUnchanged) { setBindingConfirmOpen(false) @@ -560,7 +603,9 @@ export default function CustomerFulfillmentPage() { message.warning('虎牙登录会话已过期,请重新登录') return } - message.error(error instanceof Error ? error.message : '刷新绑定状态失败') + const detail = error instanceof Error ? error.message : '刷新绑定状态失败' + setBindingLoadError(detail) + message.error(detail) } finally { setBindingLoading(false) } @@ -575,6 +620,7 @@ export default function CustomerFulfillmentPage() { const nextBinding = response.data.binding setTasks((current) => current.map((task) => (task.id === nextTask.id ? nextTask : task))) if (nextBinding) setBindingInfo(nextBinding) + setBindingLoadError('') setBindingConfirmOpen(false) if (nextBinding?.rebindUnchanged || nextBinding?.rebindConfirmState === 'rejected') { message.error(nextBinding.message || '虎牙未接受本次换绑') @@ -592,7 +638,9 @@ export default function CustomerFulfillmentPage() { message.warning('虎牙登录会话已过期,请重新登录') return } - message.error(error instanceof Error ? error.message : '提交换绑失败') + const detail = error instanceof Error ? error.message : '提交换绑失败' + setBindingLoadError(detail) + message.error(detail) } finally { setBindingLoading(false) } @@ -1056,23 +1104,21 @@ export default function CustomerFulfillmentPage() {
{bindingSessionExpired ? ( - { - setBindingSessionExpired(false) - void handleStartLogin() - }} - > - 重新登录 - - } - /> +
+

虎牙登录会话已过期

+

+ 请返回登录重新扫码,已填写的订单资料和绑定状态不会丢失。 +

+ +
) : null} {!bindingSessionExpired ? ( @@ -1154,6 +1200,19 @@ export default function CustomerFulfillmentPage() { width={260} preview={false} /> + ) : bindingLoadError ? ( +
+

绑定二维码加载失败

+ {bindingLoadError} +
+ + +
+
) : (
@@ -1259,11 +1318,16 @@ export default function CustomerFulfillmentPage() { {bindingInfo?.rebindConfirmMessage ? ( 虎牙原因:{bindingInfo.rebindConfirmMessage} - ) : nextRebindText ? ( - 预计下次可换绑:{nextRebindText}。 - ) : ( + ) : null} + {nextRebindText ? 预计下次可换绑:{nextRebindText} : null} + {Number(bindingInfo?.platformChangeBindDay || 0) > 0 ? ( + + 虎牙规则:每 {bindingInfo?.platformChangeBindDay} 个自然日可换绑 1 次 + + ) : null} + {!bindingInfo?.rebindConfirmMessage && !nextRebindText ? ( 请核对虎牙弹窗中选中的目标角色后重新提交。 - )} + ) : null} } /> diff --git a/apps/frontend/src/styles/client.css b/apps/frontend/src/styles/client.css index a4101b0d..a45756e8 100644 --- a/apps/frontend/src/styles/client.css +++ b/apps/frontend/src/styles/client.css @@ -2431,13 +2431,20 @@ } .customer-login-submit.ant-btn { - height: 52px; - border-radius: 8px; - background: #0aa53a !important; - border-color: #0aa53a !important; + height: 56px; + border-radius: 14px; + background: #2563eb !important; + border-color: #2563eb !important; + color: #fff !important; + font-size: 17px; + font-weight: 600; +} + +.customer-login-submit.ant-btn:hover, +.customer-login-submit.ant-btn:focus-visible { + background: #1d4ed8 !important; + border-color: #1d4ed8 !important; color: #fff !important; - font-size: 18px; - font-weight: 700; } .customer-login-alt.ant-btn { @@ -2498,6 +2505,53 @@ padding: 16px; } +.customer-binding-session-card { + display: flex; + flex-direction: column; + gap: 10px; + padding: 18px; + border: 1px solid #78350f; + border-radius: 12px; + background: rgba(120, 53, 15, 0.22); +} + +.customer-binding-session-title { + margin: 0; + color: #fbbf24; + font-size: 16px; + font-weight: 700; +} + +.customer-binding-session-desc { + margin: 0 0 4px; + color: #fcd34d; + font-size: 13px; + line-height: 1.6; +} + +.customer-binding-qr-error { + display: flex; + flex-direction: column; + align-items: center; + gap: 10px; + padding: 24px 12px; + text-align: center; +} + +.customer-binding-qr-error p { + margin: 0; + color: #fca5a5; + font-size: 15px; + font-weight: 600; +} + +.customer-binding-qr-error span { + color: #cbd5e1; + font-size: 13px; + line-height: 1.6; + overflow-wrap: anywhere; +} + /* antd Alert 在绑定阶段统一走深色卡片,避免浅色块破坏整体深色风格 */ .customer-binding-stage .ant-alert { align-items: flex-start; @@ -2513,6 +2567,14 @@ font-weight: 600; } +/* antd v6 的标题节点是 .ant-alert-title(v5 为 .ant-alert-message) */ +.customer-binding-stage .ant-alert .ant-alert-title { + color: #e2e8f0; + font-size: 14px; + font-weight: 600; + line-height: 1.5; +} + .customer-binding-stage .ant-alert .ant-alert-description { color: #cbd5e1; font-size: 13px; @@ -2525,7 +2587,8 @@ } .customer-binding-stage .ant-alert-warning .ant-alert-icon, -.customer-binding-stage .ant-alert-warning .ant-alert-message { +.customer-binding-stage .ant-alert-warning .ant-alert-message, +.customer-binding-stage .ant-alert-warning .ant-alert-title { color: #fbbf24; } @@ -2539,7 +2602,8 @@ } .customer-binding-stage .ant-alert-error .ant-alert-icon, -.customer-binding-stage .ant-alert-error .ant-alert-message { +.customer-binding-stage .ant-alert-error .ant-alert-message, +.customer-binding-stage .ant-alert-error .ant-alert-title { color: #fca5a5; } @@ -2553,7 +2617,8 @@ } .customer-binding-stage .ant-alert-success .ant-alert-icon, -.customer-binding-stage .ant-alert-success .ant-alert-message { +.customer-binding-stage .ant-alert-success .ant-alert-message, +.customer-binding-stage .ant-alert-success .ant-alert-title { color: #6ee7b7; } @@ -2739,12 +2804,13 @@ .customer-binding-next.ant-btn { width: 100%; - height: 46px; + height: 56px; margin-top: 6px; - border-radius: 8px; + border-radius: 14px; background: #2563eb !important; border-color: #2563eb !important; color: #fff !important; + font-size: 17px; font-weight: 600; } From f371cc2c8dab7c2b0bf246c666e90a9c02d107ed Mon Sep 17 00:00:00 2001 From: zhaoxing <2558691827@qq.com> Date: Mon, 16 Nov 2026 16:31:56 +0800 Subject: [PATCH 06/15] =?UTF-8?q?feat(semi-auto):=20=E9=A6=96=E6=AC=A1?= =?UTF-8?q?=E7=BB=91=E5=AE=9A=E8=87=AA=E5=8A=A8=E6=8F=90=E4=BA=A4=E5=B9=B6?= =?UTF-8?q?=E7=94=B1=E5=AE=A2=E6=88=B7=E6=9C=AC=E5=9C=B0=E7=A1=AE=E8=AE=A4?= =?UTF-8?q?=EF=BC=8C=E7=BB=9F=E4=B8=80=E5=AE=A2=E6=88=B7=E9=A1=B5=E6=8E=A7?= =?UTF-8?q?=E4=BB=B6=E5=B0=BA=E5=AF=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1) 首次绑定(isBindAccount/isBindRole 任一为 0)扫码完成后自动调 confirmBindActAccount,新增 bindConfirmState/bindConfirmMessage,失败透出虎牙原文并提示重新扫码。 2) 确认绑定改为纯本地流转:不再调用 confirmBindActAccount,也不再重复查角色;换绑被虎牙拒绝时需 acceptExistingRole 二次确认「仍使用原角色」。新增 bindingSnapshot 只读快照。 3) 客户页资料收集去掉顶部大图,只保留温馨提示;输入框/选择器 48px、主按钮 52px、次级按钮 48px,登录/绑定/资料页统一。 4) 修正已确认/已过期/绑定失败状态仍显示「登录成功,请继续扫码绑定游戏角色」的横幅错误,改为按 bindingStatus 显式映射,确认后只保留「等待客服核实」卡片。 --- .../src/routes/customer-fulfillment.ts | 16 +- .../semi-auto/huya-connector-client.ts | 28 +- .../binding-confirm-decision.test.ts | 96 +++++++ .../huya-native/huya-native-connector.ts | 262 +++++++++++++----- .../semi-auto/semi-auto-task-service.ts | 45 ++- .../CustomerFulfillmentPage.tsx | 121 +++++--- .../src/services/customer-fulfillment.ts | 8 +- apps/frontend/src/styles/client.css | 69 +++-- .../src/types/customer-fulfillment.ts | 2 + 9 files changed, 490 insertions(+), 157 deletions(-) create mode 100644 apps/backend/src/services/semi-auto/huya-native/binding-confirm-decision.test.ts diff --git a/apps/backend/src/routes/customer-fulfillment.ts b/apps/backend/src/routes/customer-fulfillment.ts index d3de6671..2343308d 100644 --- a/apps/backend/src/routes/customer-fulfillment.ts +++ b/apps/backend/src/routes/customer-fulfillment.ts @@ -120,11 +120,17 @@ router.post( router.post( '/:orderNo/tasks/:taskId/binding/confirm', writeLimit, - createRouteHandler((req) => confirmPublicBinding(req.params.orderNo, req.params.taskId), { - successMessage: '绑定已确认', - errorMessage: '确认账号绑定失败', - scope: '[customer-fulfillment/:orderNo/tasks/:taskId/binding/confirm]', - }), + createRouteHandler( + (req) => + confirmPublicBinding(req.params.orderNo, req.params.taskId, { + acceptExistingRole: req.body?.acceptExistingRole === true, + }), + { + successMessage: '绑定已确认', + errorMessage: '确认账号绑定失败', + scope: '[customer-fulfillment/:orderNo/tasks/:taskId/binding/confirm]', + }, + ), ) router.get( diff --git a/apps/backend/src/services/semi-auto/huya-connector-client.ts b/apps/backend/src/services/semi-auto/huya-connector-client.ts index 58e56bbf..bae6640b 100644 --- a/apps/backend/src/services/semi-auto/huya-connector-client.ts +++ b/apps/backend/src/services/semi-auto/huya-connector-client.ts @@ -105,6 +105,8 @@ export type ConnectorBindingSession = { rebindUnchanged?: boolean rebindConfirmState?: 'idle' | 'submitting' | 'accepted' | 'rejected' rebindConfirmMessage?: string + bindConfirmState?: 'idle' | 'submitting' | 'accepted' | 'rejected' + bindConfirmMessage?: string rebindCooldownDays?: number nextRebindAt?: string platformChangeBindDay?: number @@ -419,14 +421,34 @@ export async function getHuyaBinding( ) } -export async function confirmHuyaBinding( +/** + * 只读绑定快照:不触发虎牙查询,供「确认绑定」这类本地动作使用。 + * 外部 Connector 没有独立快照端点,只能复用 GET(由 Connector 侧决定是否访问虎牙)。 + */ +export async function getHuyaBindingSnapshot( sessionId: string, mode: SemiAutoConnectorMode = defaultSemiAutoConnectorMode(), ): Promise { - if (mode === 'embedded') return huyaNativeConnector.confirmBinding(sessionId) + if (mode === 'embedded') return huyaNativeConnector.bindingSnapshot(sessionId) + return callConnector( + `/api/internal/huya-semi-auto/sessions/${encodeURIComponent(sessionId)}/binding`, + {}, + mode, + ) +} + +export async function confirmHuyaBinding( + sessionId: string, + mode: SemiAutoConnectorMode = defaultSemiAutoConnectorMode(), + options: { acceptExistingRole?: boolean } = {}, +): Promise { + if (mode === 'embedded') return huyaNativeConnector.confirmBinding(sessionId, options) return callConnector( `/api/internal/huya-semi-auto/sessions/${encodeURIComponent(sessionId)}/binding/confirm`, - { method: 'POST', body: {} }, + { + method: 'POST', + body: options.acceptExistingRole ? { acceptExistingRole: true } : {}, + }, mode, ) } diff --git a/apps/backend/src/services/semi-auto/huya-native/binding-confirm-decision.test.ts b/apps/backend/src/services/semi-auto/huya-native/binding-confirm-decision.test.ts new file mode 100644 index 00000000..e3c3c3ff --- /dev/null +++ b/apps/backend/src/services/semi-auto/huya-native/binding-confirm-decision.test.ts @@ -0,0 +1,96 @@ +import assert from 'node:assert/strict' +import test from 'node:test' + +import { resolveBindingConfirmDecision, shouldSubmitFirstBind } from './huya-native-connector.js' + +test('确认绑定:识别到角色即可本地确认,不需要虎牙接口', () => { + assert.equal( + resolveBindingConfirmDecision({ status: 'role_ready', role: '大鲨鱼伊塞53' }), + 'confirm', + ) +}) + +test('确认绑定:换绑被虎牙拒绝时必须由客户二选一', () => { + assert.equal( + resolveBindingConfirmDecision({ + status: 'role_ready', + role: '大鲨鱼伊塞53', + rebindRequested: true, + rebindUnchanged: true, + }), + 'needs_rebind_decision', + ) +}) + +test('确认绑定:客户确认仍使用原角色后放行', () => { + assert.equal( + resolveBindingConfirmDecision( + { + status: 'role_ready', + role: '大鲨鱼伊塞53', + rebindRequested: true, + rebindUnchanged: true, + }, + { acceptExistingRole: true }, + ), + 'confirm', + ) +}) + +test('确认绑定:换绑还在进行中(未判定失败)不拦截确认', () => { + assert.equal( + resolveBindingConfirmDecision({ + status: 'role_ready', + role: '大鲨鱼伊塞53', + rebindRequested: true, + }), + 'confirm', + ) +}) + +test('确认绑定:没有角色或状态不对时不能确认', () => { + assert.equal(resolveBindingConfirmDecision({ status: 'role_ready', role: '' }), 'not_ready') + assert.equal( + resolveBindingConfirmDecision({ status: 'qr_pending', role: '大鲨鱼伊塞53' }), + 'not_ready', + ) + assert.equal( + resolveBindingConfirmDecision({ status: 'confirmed', role: '大鲨鱼伊塞53' }), + 'confirm', + ) +}) + +test('首次绑定:没有绑定角色且扫码完成才提交虎牙绑定', () => { + assert.equal(shouldSubmitFirstBind({}, { qrCompleted: true, scanned: true }), true) + assert.equal(shouldSubmitFirstBind({}, { qrCompleted: false, scanned: true }), false) + assert.equal(shouldSubmitFirstBind({}, { qrCompleted: true, scanned: false }), false) +}) + +test('首次绑定:已有绑定角色或正在换绑时不提交绑定', () => { + assert.equal( + shouldSubmitFirstBind({ hasExistingBinding: true }, { qrCompleted: true, scanned: true }), + false, + ) + assert.equal( + shouldSubmitFirstBind( + { rebindRequested: true, hasExistingBinding: false }, + { qrCompleted: true, scanned: true }, + ), + false, + ) +}) + +test('首次绑定:同一张码只提交一次', () => { + assert.equal( + shouldSubmitFirstBind({ bindConfirmState: 'accepted' }, { qrCompleted: true, scanned: true }), + false, + ) + assert.equal( + shouldSubmitFirstBind({ bindConfirmState: 'rejected' }, { qrCompleted: true, scanned: true }), + false, + ) + assert.equal( + shouldSubmitFirstBind({ bindConfirmState: 'submitting' }, { qrCompleted: true, scanned: true }), + false, + ) +}) diff --git a/apps/backend/src/services/semi-auto/huya-native/huya-native-connector.ts b/apps/backend/src/services/semi-auto/huya-native/huya-native-connector.ts index 18f54be0..65d30ecf 100644 --- a/apps/backend/src/services/semi-auto/huya-native/huya-native-connector.ts +++ b/apps/backend/src/services/semi-auto/huya-native/huya-native-connector.ts @@ -82,6 +82,11 @@ type NativeBindState = { rebindConfirmMessage: string rebindConfirmAt: number rebindEffectDeadlineMs: number + /** 首次绑定(账号还没有绑定角色)时,扫码后由项目侧提交 confirmBindActAccount 的状态。 */ + bindConfirmState: 'idle' | 'submitting' | 'accepted' | 'rejected' + bindConfirmMessage: string + bindConfirmAt: number + bindEffectDeadlineMs: number rebindCooldownDays: number nextRebindAt: string changeBindTime: number @@ -166,6 +171,10 @@ function defaultBindingState(): NativeBindState { rebindConfirmMessage: '', rebindConfirmAt: 0, rebindEffectDeadlineMs: 0, + bindConfirmState: 'idle', + bindConfirmMessage: '', + bindConfirmAt: 0, + bindEffectDeadlineMs: 0, rebindCooldownDays: 0, nextRebindAt: '', changeBindTime: 0, @@ -234,6 +243,54 @@ export function resolveRebindCooldown( return { days: 0, nextRebindAt: '' } } +export type BindingConfirmDecision = 'confirm' | 'needs_rebind_decision' | 'not_ready' + +/** + * 客户点「确认绑定」时只做本地流转:角色已识别即可确认,不调用任何虎牙接口。 + * 唯一需要客户决定的情况是「换绑被虎牙拒绝、平台仍返回原角色」: + * 要么重新扫码换绑,要么显式确认继续使用原绑定角色。 + */ +export function resolveBindingConfirmDecision( + binding: { + status?: string + role?: string + rebindRequested?: boolean + rebindUnchanged?: boolean + }, + options: { acceptExistingRole?: boolean } = {}, +): BindingConfirmDecision { + const role = String(binding.role || '').trim() + const status = String(binding.status || '') + if (!role || (status !== 'role_ready' && status !== 'confirmed')) return 'not_ready' + if ( + binding.rebindRequested === true && + binding.rebindUnchanged === true && + options.acceptExistingRole !== true + ) { + return 'needs_rebind_decision' + } + return 'confirm' +} + +/** + * 首次绑定:账号还没有绑定角色(isBindAccount / isBindRole 任一为 0)时, + * 扫码完成后必须由项目侧调用 confirmBindActAccount 完成绑定,再读取角色做本地比对。 + * 已经有绑定角色、也没发起换绑时不需要任何平台写接口。 + */ +export function shouldSubmitFirstBind( + binding: { + rebindRequested?: boolean + hasExistingBinding?: boolean + bindConfirmState?: string + }, + input: { qrCompleted: boolean; scanned: boolean }, +): boolean { + if (!input.qrCompleted || !input.scanned) return false + if (binding.rebindRequested === true) return false + if (binding.hasExistingBinding === true) return false + return (binding.bindConfirmState || 'idle') === 'idle' +} + function applyRebindMeta( session: NativeSession, response: HuyaBindResponse | null, @@ -861,9 +918,17 @@ export class HuyaNativeConnector { session.binding.qrUrl = urls.qrUrl session.binding.qrToken = mini.token session.binding.expiresAtMs = this.now() + BINDING_QR_TTL_MS + if (!options.forceRebind) { + // 新的绑定码:清掉上一次绑定提交状态,等这次扫码完成后再提交。 + session.binding.bindConfirmState = 'idle' + session.binding.bindConfirmMessage = '' + session.binding.bindConfirmAt = 0 + session.binding.bindEffectDeadlineMs = 0 + session.binding.rebindScanned = false + } session.binding.message = options.forceRebind ? '请使用虎牙 App 扫码选择需要换绑的游戏角色' - : '请使用虎牙 App 扫码绑定游戏角色' + : '该虎牙账号还没有绑定游戏角色,请用虎牙 App 扫码完成绑定' return this.bindingView(session) }) } @@ -902,6 +967,39 @@ export class HuyaNativeConnector { } } + /** + * 首次绑定:账号还没有绑定角色时,扫码完成后由项目侧替客户点「绑定」。 + * 与换绑共用 confirmBindActAccount,只是状态记录在 bindConfirmState,避免和换绑失败混淆。 + */ + private async submitBindLocked(session: NativeSession, rpc: HuyaRpcClient): Promise { + const { bindActId, outerActId } = configValues() + const now = this.now() + session.binding.bindConfirmState = 'submitting' + session.binding.bindConfirmMessage = '' + session.binding.bindConfirmAt = now + try { + const confirmed = await rpc.confirmBindActAccount({ + uid: session.uid, + cookie: session.cookie, + bindActId, + outerActId, + }) + if (confirmed && confirmed.status === 200) { + session.binding.bindConfirmState = 'accepted' + session.binding.bindEffectDeadlineMs = now + REBIND_EFFECT_WINDOW_MS + session.binding.message = '已向虎牙提交绑定,正在等待角色生效' + return + } + session.binding.bindConfirmState = 'rejected' + session.binding.bindConfirmMessage = confirmed?.msg || '虎牙未接受本次绑定' + session.binding.message = `虎牙未接受本次绑定:${session.binding.bindConfirmMessage}` + } catch (error) { + session.binding.bindConfirmState = 'rejected' + session.binding.bindConfirmMessage = errorMessage(error) + session.binding.message = `提交绑定失败:${session.binding.bindConfirmMessage}` + } + } + async pollBinding(sessionId: string): Promise { return this.withLock(sessionId, async () => { const session = this.requireAuthenticatedSession(sessionId) @@ -913,7 +1011,11 @@ export class HuyaNativeConnector { timeoutMs: this.rpcTimeoutMs, }) if (qrStatus) { - if (qrStatus.isExpired || qrStatus.isFailure) { + // 平台已受理(绑定/换绑)时二维码会先过期,此时要等角色生效,不能直接判过期。 + const waitingPlatformEffect = + session.binding.rebindConfirmState === 'accepted' || + session.binding.bindConfirmState === 'accepted' + if ((qrStatus.isExpired || qrStatus.isFailure) && !waitingPlatformEffect) { session.binding.status = 'expired' session.binding.message = '绑定二维码已过期,请重新获取' return this.bindingView(session) @@ -943,6 +1045,15 @@ export class HuyaNativeConnector { ) { await this.submitRebindLocked(session, rpc) } + // 首次绑定:账号还没有绑定角色时,扫码完成后由项目侧主动提交绑定。 + if ( + shouldSubmitFirstBind(session.binding, { + qrCompleted, + scanned: session.binding.rebindScanned, + }) + ) { + await this.submitBindLocked(session, rpc) + } const response = await rpc.checkUserBindGameAccount({ uid: session.uid, cookie: session.cookie, @@ -1001,92 +1112,103 @@ export class HuyaNativeConnector { if (rebindRequested) { session.binding.message = '已识别换绑角色,请确认换绑' } + } else if ( + !session.binding.rebindRequested && + session.binding.bindConfirmState === 'rejected' + ) { + session.binding.status = 'failed' + session.binding.message = `虎牙未接受本次绑定:${session.binding.bindConfirmMessage}` + } else if ( + !session.binding.rebindRequested && + session.binding.bindConfirmState === 'accepted' + ) { + if (this.now() < session.binding.bindEffectDeadlineMs) { + session.binding.status = 'scanned' + session.binding.message = '已向虎牙提交绑定,正在等待角色生效' + } else { + session.binding.status = 'failed' + session.binding.message = '虎牙已受理绑定,但未返回角色,请重新扫码绑定' + } } else if (!['scanned', 'expired', 'failed'].includes(session.binding.status)) { session.binding.status = 'qr_pending' - session.binding.message = '等待扫码绑定游戏角色' + session.binding.message = '该虎牙账号还没有绑定游戏角色,请扫码完成绑定' } return this.bindingView(session) }) } - async confirmBinding(sessionId: string): Promise { + /** 只读绑定状态快照:不访问虎牙,供「确认绑定」这类纯本地动作使用。 */ + async bindingSnapshot(sessionId: string): Promise { + return this.withLock(sessionId, async () => + this.bindingView(this.requireAuthenticatedSession(sessionId)), + ) + } + + /** + * 客户点「确认绑定」:只做本地状态流转,不调用虎牙接口。 + * 虎牙侧的绑定已由扫码(小程序/弹窗)完成,确认绑定只是核对三项后落库; + * 需要调用虎牙接口的地方只有「换绑确认」(submitRebind / pollBinding 自动提交)。 + */ + async confirmBinding( + sessionId: string, + options: { acceptExistingRole?: boolean } = {}, + ): Promise { return this.withLock(sessionId, async () => { const session = this.requireAuthenticatedSession(sessionId) - const { bindActId, outerActId } = configValues() - const rpc = new HuyaRpcClient({ fetchImpl: this.fetchImpl, timeoutMs: this.rpcTimeoutMs }) - const rebindRequested = session.binding.rebindRequested - if (rebindRequested && session.binding.rebindConfirmState !== 'accepted') { - // 客户点确认前再兜底提交一次,避免小程序扫码后项目没来得及自动提交。 - await this.submitRebindLocked(session, rpc) - } - const response = await rpc.checkUserBindGameAccount({ - uid: session.uid, - cookie: session.cookie, - bindActId, - outerActId, - }) - const role = parseRole(response) - if (!response || response.status !== 200 || !role.role) { + const binding = session.binding + const decision = resolveBindingConfirmDecision(binding, options) + if (decision === 'not_ready') { throw createHttpError('尚未识别到可确认的绑定角色', { statusCode: 409, errorCode: 'huya_bind_role_not_ready', }) } - applyRebindMeta(session, response, this.now()) - if ( - rebindRequested && - session.binding.baselineRoleKey && - bindingRoleKey(role) === session.binding.baselineRoleKey - ) { - // 只有虎牙实际未生效时才拦截;冷却原因以虎牙返回的原文为准。 + const rebindRequested = binding.rebindRequested + const acceptExistingRole = options.acceptExistingRole === true + if (decision === 'needs_rebind_decision') { + const reason = readString(binding.rebindConfirmMessage) throw createHttpError( - rebindFailureMessage( - role.role, - session.binding.rebindConfirmMessage, - session.binding.nextRebindAt, - ), - { - statusCode: 409, - errorCode: - session.binding.rebindConfirmState === 'rejected' - ? 'huya_bind_rebind_rejected' - : 'huya_bind_rebind_not_effective', - }, + `${ + reason + ? `换绑未成功:${reason}。` + : `换绑未成功:平台仍返回原绑定角色「${binding.role}」。` + }请重新扫码换绑,或确认继续使用原绑定角色`, + { statusCode: 409, errorCode: 'huya_bind_rebind_decision_required' }, ) } - const useExistingBinding = hasExistingHuyaBinding(response) && !rebindRequested - if (!useExistingBinding && session.binding.rebindConfirmState !== 'accepted') { - const confirmed = await rpc.confirmBindActAccount({ - uid: session.uid, - cookie: session.cookie, - bindActId, - outerActId, - }) - if (!confirmed || confirmed.status !== 200) { - throw createHttpError(confirmed?.msg || '确认虎牙绑定失败', { - statusCode: 409, - errorCode: 'huya_bind_confirm_failed', - }) - } + const role = { + account: binding.account, + role: binding.role, + roleId: binding.roleId, + channel: binding.channel, } + const useExistingBinding = + binding.hasExistingBinding === true && (!rebindRequested || acceptExistingRole) this.markRoleReady(session, role, useExistingBinding) - session.binding.status = 'confirmed' - session.binding.hasExistingBinding = true - session.binding.rebindRequested = false - session.binding.rebindScanned = false - session.binding.rebindUnchanged = false - session.binding.rebindConfirmState = 'idle' - session.binding.rebindConfirmMessage = '' - session.binding.rebindConfirmAt = 0 - session.binding.rebindEffectDeadlineMs = 0 - session.binding.rebindCooldownDays = 0 - session.binding.nextRebindAt = '' - session.binding.baselineRoleKey = '' - session.binding.message = useExistingBinding - ? '当前虎牙账号已有绑定角色,已确认直接使用' - : rebindRequested - ? '虎牙角色换绑已确认' - : '虎牙角色绑定已确认' + binding.status = 'confirmed' + binding.hasExistingBinding = true + binding.rebindRequested = false + binding.rebindScanned = false + binding.rebindUnchanged = false + binding.rebindConfirmState = 'idle' + binding.rebindConfirmMessage = '' + binding.rebindConfirmAt = 0 + binding.rebindEffectDeadlineMs = 0 + binding.bindConfirmState = 'idle' + binding.bindConfirmMessage = '' + binding.bindConfirmAt = 0 + binding.bindEffectDeadlineMs = 0 + binding.rebindCooldownDays = 0 + binding.nextRebindAt = '' + binding.baselineRoleKey = '' + binding.message = + rebindRequested && acceptExistingRole + ? '本次换绑未生效,已按原绑定角色确认' + : useExistingBinding + ? '当前虎牙账号已有绑定角色,已确认直接使用' + : rebindRequested + ? '虎牙角色换绑已确认' + : '虎牙角色绑定已确认' return this.bindingView(session) }) } @@ -1419,6 +1541,8 @@ export class HuyaNativeConnector { rebindUnchanged: binding.rebindUnchanged, rebindConfirmState: binding.rebindConfirmState, rebindConfirmMessage: binding.rebindConfirmMessage, + bindConfirmState: binding.bindConfirmState, + bindConfirmMessage: binding.bindConfirmMessage, rebindCooldownDays: binding.rebindCooldownDays, nextRebindAt: binding.nextRebindAt, platformChangeBindDay: binding.changeBindDay, diff --git a/apps/backend/src/services/semi-auto/semi-auto-task-service.ts b/apps/backend/src/services/semi-auto/semi-auto-task-service.ts index ba18ee7e..97a75624 100644 --- a/apps/backend/src/services/semi-auto/semi-auto-task-service.ts +++ b/apps/backend/src/services/semi-auto/semi-auto-task-service.ts @@ -22,6 +22,7 @@ import { confirmHuyaBinding, exportHuyaSessionCredential, getHuyaBinding, + getHuyaBindingSnapshot, getHuyaLoginSession, loginHuyaSms, revokeHuyaSession, @@ -959,6 +960,8 @@ function mapBindingUpdate(session: ConnectorBindingSession) { rebindUnchanged: session.rebindUnchanged === true, rebindConfirmState: session.rebindConfirmState || 'idle', rebindConfirmMessage: String(session.rebindConfirmMessage || ''), + bindConfirmState: session.bindConfirmState || 'idle', + bindConfirmMessage: String(session.bindConfirmMessage || ''), rebindCooldownDays: Number(session.rebindCooldownDays || 0), nextRebindAt: String(session.nextRebindAt || ''), platformChangeBindDay: Number(session.platformChangeBindDay || 0), @@ -1144,6 +1147,8 @@ async function updateBindingTask( rebindUnchanged: mapped.rebindUnchanged, rebindConfirmState: mapped.rebindConfirmState, rebindConfirmMessage: mapped.rebindConfirmMessage, + bindConfirmState: mapped.bindConfirmState, + bindConfirmMessage: mapped.bindConfirmMessage, rebindCooldownDays: mapped.rebindCooldownDays, nextRebindAt: mapped.nextRebindAt, changeBindDay: mapped.platformChangeBindDay, @@ -1166,6 +1171,8 @@ async function updateBindingTask( rebindUnchanged: mapped.rebindUnchanged, rebindConfirmState: mapped.rebindConfirmState, rebindConfirmMessage: mapped.rebindConfirmMessage, + bindConfirmState: mapped.bindConfirmState, + bindConfirmMessage: mapped.bindConfirmMessage, rebindCooldownDays: mapped.rebindCooldownDays, nextRebindAt: mapped.nextRebindAt, platformChangeBindDay: mapped.platformChangeBindDay, @@ -1341,7 +1348,11 @@ export async function pollPublicBinding(orderNoInput: unknown, taskIdInput: unkn return { task: mapTask(updated), binding } } -export async function confirmPublicBinding(orderNoInput: unknown, taskIdInput: unknown) { +export async function confirmPublicBinding( + orderNoInput: unknown, + taskIdInput: unknown, + options: { acceptExistingRole?: boolean } = {}, +) { const orderNo = normalizeOrderNo(orderNoInput) const taskId = normalizeId(taskIdInput) const task = await loadTaskForOrder(orderNo, taskId) @@ -1360,15 +1371,27 @@ export async function confirmPublicBinding(orderNoInput: unknown, taskIdInput: u errorCode: 'semi_auto_binding_not_ready', }) } - const session = await getBindingForTask(task, task.connector_session_id) - if (task.platform === 'huya' && session.rebindUnchanged === true) { - throw createHttpError(session.message || '换绑未生效:平台仍返回原绑定角色,请重新扫码', { - statusCode: 409, - errorCode: - session.rebindConfirmState === 'rejected' - ? 'semi_auto_binding_rebind_rejected' - : 'semi_auto_binding_rebind_unchanged', - }) + // 确认绑定是纯本地动作:虎牙侧只读内存快照,不再触发角色查询或换绑提交。 + const session = + task.platform === 'huya' + ? await getHuyaBindingSnapshot(task.connector_session_id, task.connector_mode) + : await getBindingForTask(task, task.connector_session_id) + if ( + task.platform === 'huya' && + session.rebindUnchanged === true && + options.acceptExistingRole !== true + ) { + // 换绑被虎牙拒绝时不直接放行,要求客户二选一:重新扫码换绑 / 仍使用原角色。 + const reason = String(session.rebindConfirmMessage || '').trim() + throw createHttpError( + `${ + reason ? `换绑未成功:${reason}。` : '换绑未生效:平台仍返回原绑定角色。' + }请重新扫码换绑,或确认继续使用原绑定角色「${session.bindGameRole || '原角色'}」`, + { + statusCode: 409, + errorCode: 'semi_auto_binding_rebind_decision_required', + }, + ) } const comparison = compareBindingRole(task, session) if (comparison.verdict === 'mismatch') { @@ -1380,7 +1403,7 @@ export async function confirmPublicBinding(orderNoInput: unknown, taskIdInput: u // 必须调用 Connector 完成确认,否则会话仍是 role_ready,数据库也会停在待确认。 const confirmedSession = task.platform === 'huya' - ? await confirmHuyaBinding(task.connector_session_id, task.connector_mode) + ? await confirmHuyaBinding(task.connector_session_id, task.connector_mode, options) : session const binding = await updateBindingTask(task, confirmedSession, 'customer') const updated = await loadTask(task.id) diff --git a/apps/frontend/src/pages/customer-fulfillment/CustomerFulfillmentPage.tsx b/apps/frontend/src/pages/customer-fulfillment/CustomerFulfillmentPage.tsx index 726e089b..62b2ed5a 100644 --- a/apps/frontend/src/pages/customer-fulfillment/CustomerFulfillmentPage.tsx +++ b/apps/frontend/src/pages/customer-fulfillment/CustomerFulfillmentPage.tsx @@ -37,7 +37,6 @@ import type { CustomerSemiAutoTask, } from '@/types/customer-fulfillment' import { formatAdminDateTime } from '@/utils/admin-time' -import collectHero from '@/assets/claim/game-role-id-guide.jpg' import { runWeiboYidunChallenge } from '@/utils/weibo-yidun' import HuyaChallengeModal from './HuyaChallengeModal' @@ -49,7 +48,7 @@ const SERVER_ZONE_OPTIONS = ['苹果Q区', '苹果V区', '安卓Q区', '安卓V const SERVER_ZONE_SELECT_CLASS_NAMES = { popup: { root: 'customer-collect-dropdown' } } export default function CustomerFulfillmentPage() { - const { message } = App.useApp() + const { message, modal } = App.useApp() const { orderNo: routeOrderNo } = useParams<{ orderNo?: string }>() const orderNo = String(routeOrderNo || '').trim() const [loading, setLoading] = useState(true) @@ -677,17 +676,23 @@ export default function CustomerFulfillmentPage() { } } - async function handleConfirmBinding() { + async function handleConfirmBinding(acceptExistingRole = false) { if (!selectedTask) return setBindingLoading(true) try { - const response = await confirmCustomerBinding(orderNo, selectedTask.id) + const response = await confirmCustomerBinding( + orderNo, + selectedTask.id, + acceptExistingRole ? { acceptExistingRole: true } : {}, + ) setTasks((current) => current.map((task) => (task.id === response.data.task.id ? response.data.task : task)), ) setBindingInfo(response.data.binding) setBindingConfirmOpen(false) - message.success('绑定已确认,等待客服处理') + message.success( + acceptExistingRole ? '已按原绑定角色确认,等待客服处理' : '绑定已确认,等待客服处理', + ) } catch (error) { if (isHuyaSessionExpired(error)) { setBindingSessionExpired(true) @@ -701,6 +706,21 @@ export default function CustomerFulfillmentPage() { } } + /** 换绑被虎牙拒绝时的二次确认:客户可以选择继续使用原绑定角色。 */ + function handleAcceptExistingRole() { + if (!selectedTask || bindingLoading) return + const reason = String(bindingInfo?.rebindConfirmMessage || '').trim() + modal.confirm({ + title: '仍使用原绑定角色?', + content: `本次换绑未成功${reason ? `(${reason})` : ''},平台仍返回原绑定角色「${ + bindingRoleName || '当前角色' + }」。确认后本次换绑作废,直接使用该角色继续履约。`, + okText: '仍使用原角色', + cancelText: '先不确认', + onOk: () => handleConfirmBinding(true), + }) + } + async function handleSaveProfile() { if (!selectedTask) return if (!profileServerZone.trim() || !profileRoleId.trim() || !profileRoleName.trim()) { @@ -778,6 +798,42 @@ export default function CustomerFulfillmentPage() { const rebindConfirmState = bindingInfo?.rebindConfirmState || 'idle' const rebindRejected = rebindConfirmState === 'rejected' const rebindAccepted = rebindConfirmState === 'accepted' + const bindConfirmState = bindingInfo?.bindConfirmState || 'idle' + const bindConfirmRejected = bindConfirmState === 'rejected' + const bindConfirmPending = bindConfirmState === 'submitting' || bindConfirmState === 'accepted' + // 还没有绑定角色时,二维码区域已经说明了原因,不再重复提示「缺角色ID」。 + const showMissingRoleIdWarning = + !bindingPendingUid && !rebindUnchanged && bindingInfo?.hasExistingBinding !== false + // 绑定阶段顶部状态条:按 bindingStatus 显式映射,已确认/已过期/失败不再显示(各自有卡片)。 + const bindingBanner = (() => { + if (bindingSessionExpired) return null + if (rebindUnchanged) { + return { + tone: 'is-warning', + text: rebindRejected ? '虎牙未接受本次换绑,请查看下方原因' : '换绑未生效,请查看下方原因', + } + } + if (selectedTask?.bindingStatus === 'role_ready') { + return { tone: 'is-info', text: '已识别绑定角色,请核对后确认' } + } + if ( + selectedTask?.bindingStatus === 'confirmed' || + selectedTask?.bindingStatus === 'expired' || + selectedTask?.bindingStatus === 'failed' + ) { + return null + } + if (bindingInfo?.hasExistingBinding === false) { + return { + tone: 'is-info', + text: '登录成功,该虎牙账号还没有绑定游戏角色,请扫码完成绑定', + } + } + if (!bindingRoleId) { + return { tone: 'is-warning', text: '未获取到已绑定的角色ID,请重新扫码绑定' } + } + return null + })() const nextRebindText = bindingInfo?.nextRebindAt ? formatAdminDateTime(bindingInfo.nextRebindAt) : '' @@ -1121,24 +1177,10 @@ export default function CustomerFulfillmentPage() {
) : null} - {!bindingSessionExpired ? ( - rebindUnchanged ? ( -
- {rebindRejected - ? '虎牙未接受本次换绑,请查看下方原因' - : '换绑未生效,请查看下方原因'} -
- ) : selectedTask?.bindingStatus === 'role_ready' ? ( -
已识别绑定角色,请核对后确认
- ) : selectedTask?.bindingStatus === 'confirmed' || bindingRoleId ? ( -
- 登录成功,请继续扫码绑定游戏角色 -
- ) : ( -
- 未获取到已绑定的角色ID,请重新扫码绑定 -
- ) + {bindingBanner ? ( +
+ {bindingBanner.text} +
) : null} {showProfileForm && !bindingSessionExpired ? ( @@ -1219,14 +1261,20 @@ export default function CustomerFulfillmentPage() { 正在生成绑定二维码... )} -

请使用微信APP扫码进行游戏角色绑定

+

+ {bindingInfo?.hasExistingBinding === false + ? '该虎牙账号还没有绑定游戏角色,请用微信扫码完成绑定' + : '请使用微信APP扫码进行游戏角色绑定'} +

{selectedTask?.bindingStatus === 'scanned' ? rebindAccepted ? '已向虎牙提交换绑,正在等待角色生效,请稍候刷新。' - : bindingInfo?.rebindRequested - ? '扫码后请在虎牙弹窗中选中目标角色;选好后点下方「已选好角色,提交换绑」。' - : '请在微信中完成角色绑定确认,再点击下方按钮进入下一步。' + : bindConfirmPending + ? '已向虎牙提交绑定,正在等待角色生效,请稍候刷新。' + : bindingInfo?.rebindRequested + ? '扫码后请在虎牙弹窗中选中目标角色;选好后点下方「已选好角色,提交换绑」。' + : '请在微信中完成角色绑定确认,再点击下方按钮进入下一步。' : '扫码后请在微信确认框中核对目标角色。'}

{nextRebindText ? ( @@ -1267,7 +1315,9 @@ export default function CustomerFulfillmentPage() { loading={bindingLoading} onClick={() => void handlePollBindingNow()} > - {rebindAccepted ? '刷新绑定状态' : '已扫码绑定,点击进入下一步'} + {rebindAccepted || bindConfirmPending + ? '刷新绑定状态' + : '已扫码绑定,点击进入下一步'} )} @@ -1291,7 +1341,7 @@ export default function CustomerFulfillmentPage() { ) : null} - {!bindingPendingUid && !rebindUnchanged ? ( + {showMissingRoleIdWarning ? ( 重新扫码换绑 + ) : comparisonMismatch ? (
@@ -1672,8 +1731,6 @@ function CustomerCollectStep(input: { return (
- -

温馨提示:未成年人禁止下单

diff --git a/apps/frontend/src/services/customer-fulfillment.ts b/apps/frontend/src/services/customer-fulfillment.ts index fb8f912f..fa11097e 100644 --- a/apps/frontend/src/services/customer-fulfillment.ts +++ b/apps/frontend/src/services/customer-fulfillment.ts @@ -59,10 +59,14 @@ export function pollCustomerBinding(orderNo: string, taskId: number) { ) } -export function confirmCustomerBinding(orderNo: string, taskId: number) { +export function confirmCustomerBinding( + orderNo: string, + taskId: number, + options: { acceptExistingRole?: boolean } = {}, +) { return apiPost<{ task: CustomerSemiAutoTask; binding: CustomerBindingInfo }>( `/api/v1/customer-fulfillment/${encodeURIComponent(orderNo)}/tasks/${taskId}/binding/confirm`, - {}, + options.acceptExistingRole ? { acceptExistingRole: true } : {}, ) } diff --git a/apps/frontend/src/styles/client.css b/apps/frontend/src/styles/client.css index a45756e8..43abfd1f 100644 --- a/apps/frontend/src/styles/client.css +++ b/apps/frontend/src/styles/client.css @@ -2149,30 +2149,12 @@ } .customer-collect-hero { - position: relative; - height: 210px; - overflow: hidden; -} - -.customer-collect-hero-image { - width: 100%; - height: 100%; - object-fit: cover; - object-position: left center; - filter: saturate(0.9) brightness(0.72); -} - -.customer-collect-hero-mask { - position: absolute; - inset: 0; - background: linear-gradient(180deg, rgba(11, 18, 32, 0.1), rgba(11, 18, 32, 0.96)); + padding: 42px 20px 6px; + text-align: center; + background: linear-gradient(180deg, #0f1a2d, #0b1220); } .customer-collect-warning { - position: absolute; - left: 0; - right: 0; - bottom: 22px; margin: 0; text-align: center; color: #f87171; @@ -2201,7 +2183,7 @@ } .customer-collect-readonly { - height: 56px; + height: 48px; display: flex; align-items: center; padding: 0 16px; @@ -2255,7 +2237,7 @@ } .customer-collect-input.ant-input { - height: 56px; + height: 48px; border-radius: 12px; background: #1b2436; border-color: #26344d; @@ -2268,7 +2250,7 @@ .customer-collect-select.ant-select { width: 100%; - height: 56px; + height: 48px; padding-inline: 16px; align-items: center; font-size: 15px; @@ -2276,7 +2258,7 @@ border: 1px solid #26344d; background: #1b2436; color: #fff; - --ant-select-height: 56px; + --ant-select-height: 48px; --ant-select-border-radius: 12px; --ant-select-border-color: #26344d; --ant-select-background-color: #1b2436; @@ -2340,7 +2322,7 @@ .customer-collect-page .customer-collect-submit.ant-btn, .customer-auth-profile .customer-collect-submit.ant-btn { - height: 56px; + height: 52px; margin-top: 14px; border-radius: 14px; font-size: 17px; @@ -2391,7 +2373,7 @@ .customer-login-mobile.ant-input { flex: 1; min-width: 0; - height: 52px; + height: 48px; padding: 0 16px; border-radius: 8px; border-color: #3a4150; @@ -2407,7 +2389,7 @@ .customer-login-code-button.ant-btn { flex: none; width: 118px; - height: 52px; + height: 48px; border-radius: 8px; background: #3b82f6 !important; border-color: #3b82f6 !important; @@ -2416,7 +2398,7 @@ } .customer-login-code-input.ant-input { - height: 52px; + height: 48px; border-radius: 8px; border-color: #3a4150; background: #1b2130; @@ -2431,7 +2413,7 @@ } .customer-login-submit.ant-btn { - height: 56px; + height: 52px; border-radius: 14px; background: #2563eb !important; border-color: #2563eb !important; @@ -2448,7 +2430,7 @@ } .customer-login-alt.ant-btn { - height: 52px; + height: 48px; border-radius: 8px; background: transparent !important; border-color: #3a4150 !important; @@ -2634,7 +2616,7 @@ } .customer-binding-role-actions .customer-binding-confirm.ant-btn { - height: 56px; + height: 52px; border-radius: 14px; background: #2563eb !important; border-color: #2563eb !important; @@ -2651,7 +2633,7 @@ } .customer-binding-role-actions .customer-binding-rebind.ant-btn { - height: 56px; + height: 48px; border-radius: 14px; background: transparent !important; border-color: #3a4150 !important; @@ -2671,6 +2653,23 @@ color: #fbbf24 !important; } +.customer-binding-role-actions .customer-binding-accept.ant-btn { + height: 46px; + border-radius: 12px; + background: transparent !important; + border-color: transparent !important; + color: #94a3b8 !important; + font-size: 15px; + font-weight: 500; +} + +.customer-binding-role-actions .customer-binding-accept.ant-btn:hover, +.customer-binding-role-actions .customer-binding-accept.ant-btn:focus-visible { + background: rgba(148, 163, 184, 0.1) !important; + border-color: transparent !important; + color: #e2e8f0 !important; +} + .customer-binding-info { padding: 16px; border: 1px solid #3a4150; @@ -2804,7 +2803,7 @@ .customer-binding-next.ant-btn { width: 100%; - height: 56px; + height: 52px; margin-top: 6px; border-radius: 14px; background: #2563eb !important; @@ -2897,7 +2896,7 @@ .customer-auth-button-stack .ant-btn, .customer-auth-form > .ant-btn { - height: 50px; + height: 52px; font-size: 17px; } diff --git a/apps/frontend/src/types/customer-fulfillment.ts b/apps/frontend/src/types/customer-fulfillment.ts index 711b622a..312b020d 100644 --- a/apps/frontend/src/types/customer-fulfillment.ts +++ b/apps/frontend/src/types/customer-fulfillment.ts @@ -62,6 +62,8 @@ export type CustomerBindingInfo = { rebindUnchanged: boolean rebindConfirmState: 'idle' | 'submitting' | 'accepted' | 'rejected' rebindConfirmMessage: string + bindConfirmState?: 'idle' | 'submitting' | 'accepted' | 'rejected' + bindConfirmMessage?: string rebindCooldownDays: number nextRebindAt: string platformChangeBindDay?: number From 08e753ec944f2a92a9de7c752c82a66b07800bd4 Mon Sep 17 00:00:00 2001 From: zhaoxing <2558691827@qq.com> Date: Mon, 16 Nov 2026 17:26:35 +0800 Subject: [PATCH 07/15] =?UTF-8?q?feat(semi-auto):=20=E6=96=B0=E5=A2=9E?= =?UTF-8?q?=E5=B1=A5=E7=BA=A6=E5=8E=86=E5=8F=B2=E4=B8=8E=E5=85=A8=E9=93=BE?= =?UTF-8?q?=E8=B7=AF=E6=8A=A5=E6=96=87=E7=95=99=E7=97=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 运营端历史抽屉展示状态流转与全链路报文:客户/运营接口入站 + 虎牙 WUP/livelink、外部 Connector 出站;轮询按状态变化采样,Cookie/Token/短信验证码不落库,报文保留 180 天。同步收敛登录/绑定事件,避免轮询重复写时间线。 --- .../migrations/170_semi_auto_trace_logs.sql | 33 ++ apps/backend/src/index.ts | 3 + .../backend/src/middleware/semi-auto-trace.ts | 248 +++++++++ apps/backend/src/routes/admin/semi-auto.ts | 24 + .../src/routes/customer-fulfillment.ts | 10 + .../semi-auto/huya-connector-client.ts | 32 +- .../semi-auto/huya-native/huya-rpc.ts | 327 +++++++++--- .../semi-auto/semi-auto-task-service.ts | 162 ++++-- .../src/services/semi-auto/semi-auto-trace.ts | 326 ++++++++++++ .../admin/SemiAutoTaskHistoryDrawer.tsx | 501 ++++++++++++++++++ .../pages/admin/AdminSemiAutoTasksPage.tsx | 16 + apps/frontend/src/services/admin/semi-auto.ts | 8 + apps/frontend/src/types/admin/semi-auto.ts | 59 +++ 13 files changed, 1648 insertions(+), 101 deletions(-) create mode 100644 apps/backend/src/db/migrations/170_semi_auto_trace_logs.sql create mode 100644 apps/backend/src/middleware/semi-auto-trace.ts create mode 100644 apps/backend/src/services/semi-auto/semi-auto-trace.ts create mode 100644 apps/frontend/src/components/admin/SemiAutoTaskHistoryDrawer.tsx diff --git a/apps/backend/src/db/migrations/170_semi_auto_trace_logs.sql b/apps/backend/src/db/migrations/170_semi_auto_trace_logs.sql new file mode 100644 index 00000000..3bc07fea --- /dev/null +++ b/apps/backend/src/db/migrations/170_semi_auto_trace_logs.sql @@ -0,0 +1,33 @@ +-- 半自动履约:全链路报文留痕(原本系统入站请求 + 外部平台/Connector 出站调用) +-- Cookie / Token / 密钥一律不落库;报文按 180 天保留,由服务侧定期清理。 + +CREATE TABLE IF NOT EXISTS semi_auto_trace_logs ( + id BIGSERIAL PRIMARY KEY, + task_id BIGINT NOT NULL REFERENCES semi_auto_tasks(id) ON DELETE CASCADE, + order_no TEXT NOT NULL DEFAULT '', + request_id TEXT NOT NULL DEFAULT '', + direction TEXT NOT NULL CHECK (direction IN ('inbound', 'outbound')), + channel TEXT NOT NULL, + action TEXT NOT NULL, + status TEXT NOT NULL DEFAULT 'ok' CHECK (status IN ('ok', 'error')), + http_status INTEGER, + duration_ms INTEGER, + request_summary JSONB NOT NULL DEFAULT '{}'::jsonb, + request_body TEXT NOT NULL DEFAULT '', + response_summary JSONB NOT NULL DEFAULT '{}'::jsonb, + response_body TEXT NOT NULL DEFAULT '', + error_message TEXT NOT NULL DEFAULT '', + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); + +CREATE INDEX IF NOT EXISTS idx_semi_auto_trace_task + ON semi_auto_trace_logs (task_id, id DESC); + +CREATE INDEX IF NOT EXISTS idx_semi_auto_trace_request + ON semi_auto_trace_logs (request_id); + +CREATE INDEX IF NOT EXISTS idx_semi_auto_trace_created + ON semi_auto_trace_logs (created_at); + +COMMENT ON TABLE semi_auto_trace_logs IS + '半自动履约全链路报文;request_body/response_body 已脱敏(Cookie、Token、密钥不落库)'; diff --git a/apps/backend/src/index.ts b/apps/backend/src/index.ts index 15758f51..8746c200 100644 --- a/apps/backend/src/index.ts +++ b/apps/backend/src/index.ts @@ -4,6 +4,7 @@ import { createApp } from './app.js' import { runtimeConfig } from './config/runtime.js' import { assertRuntimeConfigValid } from './config/runtime-validation.js' import { bootstrapCoreServices } from './startup/bootstrap.js' +import { startSemiAutoTraceCleanup } from './services/semi-auto/semi-auto-trace.js' import { createShutdownController } from './startup/shutdown.js' import { createStartupState, formatStartupError } from './startup/state.js' import { logError, logInfo } from './utils/logger.js' @@ -30,6 +31,8 @@ const app = createApp({ const server = app.listen(port, host, () => { logInfo('[startup]', `order-site-backend kuaishou-lite listening on http://${host}:${port}`) void bootstrapCoreServices(startupState, () => shutdownController?.isShutdownStarted() || false) + // 半自动履约报文保留 180 天:启动先清一次,之后每 6 小时清理。 + startSemiAutoTraceCleanup() }) shutdownController = createShutdownController(server, startupState) diff --git a/apps/backend/src/middleware/semi-auto-trace.ts b/apps/backend/src/middleware/semi-auto-trace.ts new file mode 100644 index 00000000..13cb4c62 --- /dev/null +++ b/apps/backend/src/middleware/semi-auto-trace.ts @@ -0,0 +1,248 @@ +import crypto from 'node:crypto' + +import type { NextFunction, Request, Response } from 'express' + +import { query } from '../db/client.js' +import { + recordSemiAutoTrace, + runWithSemiAutoTrace, + traceFingerprint, + type SemiAutoTraceChannel, +} from '../services/semi-auto/semi-auto-trace.js' +import { logWarn } from '../utils/logger.js' + +/** + * 半自动履约入站报文:以 `:taskId` 路由参数为锚点。 + * + * 用法:`router.param('taskId', createSemiAutoTaskTraceHandler({ channel: 'customer_api' }))`。 + * 命中后整条请求链路都在 AsyncLocalStorage 上下文里,外部 Connector / 虎牙 RPC 的出站报文 + * 会自动复用同一个 requestId,前端即可按 requestId 串起「一次客户操作」。 + */ +export type SemiAutoTaskTraceOptions = { + channel: SemiAutoTraceChannel + /** 轮询类请求:只有失败或响应状态变化才落库。 */ + isPolling?: (req: Request) => boolean + /** 不记录本次请求(例如返回 CK 的导出接口、历史查询自身)。 */ + skip?: (req: Request) => boolean +} + +const TASK_ORDER_CACHE_LIMIT = 800 +const taskOrderCache = new Map() + +/** 响应里代表「状态」的字段:轮询指纹只取这些,时间戳/计数变化不算状态变化。 */ +const TRACE_STATE_KEYS = [ + 'status', + 'state', + 'loginStatus', + 'bindingStatus', + 'executionStatus', + 'displayStatus', + 'message', + 'msg', + 'code', + 'errorCode', + 'ok', + 'challenge', + 'ready', + 'pending', + 'type', + 'rebindUnchanged', + 'rebindRequested', + 'rebindConfirmState', + 'rebindConfirmMessage', + 'rebindCooldownDays', + 'nextRebindAt', + 'bindConfirmState', + 'bindConfirmMessage', + 'bindEffectDeadlineMs', + 'bindGameRole', + 'bindGameRoleId', + 'huyaUid', + 'lastError', + 'isBindAccount', + 'isBindRole', +] + +/** 客户请求体里的凭据类字段:短信验证码等一律不落库。 */ +const INBOUND_SECRET_KEYS = new Set([ + 'code', + 'smscode', + 'sms_code', + 'password', + 'token', + 'cookie', + 'qrcode', + 'qrcode_token', + 'qrcodetoken', + 'ticket', + 'sig', +]) + +function normalizeKey(key: string): string { + return key.replace(/([a-z0-9])([A-Z])/g, '$1_$2').toLowerCase() +} + +function createTraceRequestId(): string { + return `req_${Date.now().toString(36)}_${crypto.randomBytes(4).toString('hex')}` +} + +async function resolveTaskOrderNo(taskId: number): Promise { + const cached = taskOrderCache.get(taskId) + if (cached !== undefined) return cached + try { + const result = await query<{ platform_order_id: string | null }>( + `SELECT o.platform_order_id + FROM semi_auto_tasks task + JOIN orders o ON o.id = task.order_id + WHERE task.id = $1 + LIMIT 1`, + [taskId], + ) + const orderNo = String(result.rows[0]?.platform_order_id || '') + if (taskOrderCache.size >= TASK_ORDER_CACHE_LIMIT) taskOrderCache.clear() + taskOrderCache.set(taskId, orderNo) + return orderNo + } catch (error) { + logWarn('[semi-auto/trace]', '解析任务订单号失败,报文将不带订单号', { + taskId, + error: error instanceof Error ? error.message : String(error), + }) + return '' + } +} + +function maskInboundRequestBody(value: unknown, depth = 0): unknown { + if (depth > 4) return '[max-depth]' + if (value === null || value === undefined) return value + if (Array.isArray(value)) { + return value.slice(0, 50).map((item) => maskInboundRequestBody(item, depth + 1)) + } + if (typeof value !== 'object') return value + const source = value as Record + const masked: Record = {} + for (const [key, current] of Object.entries(source)) { + masked[key] = INBOUND_SECRET_KEYS.has(normalizeKey(key)) + ? '******' + : maskInboundRequestBody(current, depth + 1) + } + return masked +} + +function pickTraceState(value: unknown, depth = 0): unknown { + if (!value || typeof value !== 'object' || depth > 3) return value + if (Array.isArray(value)) { + return value.slice(0, 20).map((item) => pickTraceState(item, depth + 1)) + } + const source = value as Record + const picked: Record = {} + for (const key of TRACE_STATE_KEYS) { + if (key in source && source[key] !== undefined) picked[key] = source[key] + } + // 常见响应外壳:{ task, login, binding } + for (const key of ['task', 'login', 'binding', 'result']) { + const nested = source[key] + if (nested && typeof nested === 'object' && !Array.isArray(nested)) { + picked[key] = pickTraceState(nested, depth + 1) + } + } + return Object.keys(picked).length > 0 ? picked : value +} + +function buildPollingFingerprint(payload: unknown): string { + const body = payload && typeof payload === 'object' ? (payload as Record) : {} + return traceFingerprint({ + code: body.code, + msg: body.msg, + errorCode: body.errorCode, + data: pickTraceState(body.data), + }) +} + +export function createSemiAutoTaskTraceHandler(options: SemiAutoTaskTraceOptions) { + return (req: Request, res: Response, next: NextFunction, taskIdInput: string): void => { + const taskId = Number(taskIdInput) + if (!Number.isInteger(taskId) || taskId <= 0) { + next() + return + } + if (options.skip?.(req)) { + next() + return + } + + const pathOrderNo = String(req.params?.orderNo || '').trim() + const startedAt = Date.now() + const requestId = createTraceRequestId() + const polling = options.isPolling?.(req) === true + const actionPath = String(req.originalUrl || req.url || '').split('?')[0] + const action = `${String(req.method || 'GET').toUpperCase()} ${actionPath}` + const requestSummary = { + method: req.method, + path: actionPath, + query: req.query || {}, + ip: req.ip || '', + } + const requestBody = + req.body && typeof req.body === 'object' && Object.keys(req.body as object).length > 0 + ? maskInboundRequestBody(req.body) + : '' + let recorded = false + + const record = (payload: unknown) => { + if (recorded) return + recorded = true + try { + const body = + payload && typeof payload === 'object' ? (payload as Record) : {} + const code = Number(body.code) + const httpStatus = Number(res.statusCode || 200) + const failed = Number.isFinite(code) ? code !== 0 : httpStatus >= 400 + const status = failed || httpStatus >= 400 ? 'error' : 'ok' + recordSemiAutoTrace({ + taskId, + orderNo: pathOrderNo, + requestId, + direction: 'inbound', + channel: options.channel, + action, + status, + httpStatus, + durationMs: Date.now() - startedAt, + requestSummary, + requestBody, + responseSummary: { + code: body.code ?? null, + msg: body.msg ?? '', + errorCode: body.errorCode ?? '', + }, + responseBody: payload, + errorMessage: status === 'error' ? String(body.msg || '') : '', + always: !polling, + fingerprint: polling ? buildPollingFingerprint(payload) : undefined, + }) + } catch (error) { + logWarn('[semi-auto/trace]', '记录入站报文失败,已跳过', { + taskId, + action, + error: error instanceof Error ? error.message : String(error), + }) + } + } + + const originalJson = res.json.bind(res) + res.json = ((payload: unknown) => { + record(payload) + return originalJson(payload as never) + }) as Response['json'] + + const start = (orderNo: string) => { + runWithSemiAutoTrace({ requestId, taskId, orderNo, source: options.channel }, () => next()) + } + + if (pathOrderNo) { + start(pathOrderNo) + return + } + void resolveTaskOrderNo(taskId).then(start, () => start('')) + } +} diff --git a/apps/backend/src/routes/admin/semi-auto.ts b/apps/backend/src/routes/admin/semi-auto.ts index 312bfb08..7834d480 100644 --- a/apps/backend/src/routes/admin/semi-auto.ts +++ b/apps/backend/src/routes/admin/semi-auto.ts @@ -8,15 +8,27 @@ import { createAdminBrowserSession, exportAdminSemiAutoCredential, getAdminSemiAutoTask, + getAdminSemiAutoTaskHistory, listAdminSemiAutoTasks, requestAdminSemiAutoCustomerReauth, syncAdminSemiAutoTask, } from '../../services/semi-auto/semi-auto-task-service.js' +import { createSemiAutoTaskTraceHandler } from '../../middleware/semi-auto-trace.js' import { bodyOf, sessionOf } from './request-helpers.js' import { createJsonHandler, requireAdminRoles } from './session.js' const router = Router() +// 运营端每次操作都会记录入站报文;详情每 3 秒刷新一次,GET 只在状态变化时落库。 +router.param( + 'taskId', + createSemiAutoTaskTraceHandler({ + channel: 'admin_api', + isPolling: (req) => req.method === 'GET', + skip: (req) => req.path.endsWith('/history') || req.path.endsWith('/credential/export'), + }), +) + router.use('/semi-auto', requireAdminRoles(['admin', 'operator', 'support'])) router.get( @@ -37,6 +49,18 @@ router.get( }), ) +router.get( + '/semi-auto/tasks/:taskId/history', + createJsonHandler( + (req) => getAdminSemiAutoTaskHistory(req.params.taskId, req.query as Record), + { + successMessage: 'ok', + errorMessage: '读取半自动履约历史失败', + scope: '[admin/semi-auto/tasks/:taskId/history]', + }, + ), +) + router.post( '/semi-auto/tasks/:taskId/credential/export', createJsonHandler( diff --git a/apps/backend/src/routes/customer-fulfillment.ts b/apps/backend/src/routes/customer-fulfillment.ts index 2343308d..e6d80f07 100644 --- a/apps/backend/src/routes/customer-fulfillment.ts +++ b/apps/backend/src/routes/customer-fulfillment.ts @@ -19,11 +19,21 @@ import { submitPublicRebind, verifyPublicHuyaSmsChallenge, } from '../services/semi-auto/semi-auto-task-service.js' +import { createSemiAutoTaskTraceHandler } from '../middleware/semi-auto-trace.js' import { createRateLimitMiddleware, getParamRateLimitKey } from '../middleware/rate-limit.js' import { createRouteHandler } from '../utils/http.js' const router = Router() +// 客户侧每次操作都会记录入站报文;2 秒一次的 /status 轮询只在状态变化或失败时落库。 +router.param( + 'taskId', + createSemiAutoTaskTraceHandler({ + channel: 'customer_api', + isPolling: (req) => req.path.endsWith('/status'), + }), +) + const readLimit = createRateLimitMiddleware({ scope: 'customer-fulfillment:read', windowMs: 60_000, diff --git a/apps/backend/src/services/semi-auto/huya-connector-client.ts b/apps/backend/src/services/semi-auto/huya-connector-client.ts index bae6640b..3a57621b 100644 --- a/apps/backend/src/services/semi-auto/huya-connector-client.ts +++ b/apps/backend/src/services/semi-auto/huya-connector-client.ts @@ -16,6 +16,7 @@ import { huyaNativeConnector, type HuyaStoredCredential, } from './huya-native/huya-native-connector.js' +import { recordSemiAutoTrace, traceFingerprint } from './semi-auto-trace.js' export type ConnectorLoginSession = { sessionId: string @@ -204,9 +205,11 @@ async function callConnector( const timeoutMs = Math.max(1000, Number(runtimeConfig.semiAuto?.connectorTimeoutMs || 15_000)) const controller = new AbortController() const timer = setTimeout(() => controller.abort(), timeoutMs) + const method = String(options.method || 'GET').toUpperCase() + const startedAt = Date.now() try { const requestInit: RequestInit = { - method: options.method || 'GET', + method, headers: { Accept: 'application/json', 'Content-Type': 'application/json', @@ -223,6 +226,20 @@ async function callConnector( } catch { payload = null } + recordSemiAutoTrace({ + direction: 'outbound', + channel: 'external_connector', + action: `${method} ${path}`, + status: response.ok ? 'ok' : 'error', + httpStatus: response.status, + durationMs: Date.now() - startedAt, + requestSummary: { baseUrl: endpoint.baseUrl }, + requestBody: options.body, + responseSummary: { bodyBytes: text.length }, + responseBody: payload ?? text, + always: method !== 'GET', + fingerprint: method === 'GET' ? traceFingerprint(payload) : undefined, + }) if (!response.ok) { const detail = payload && typeof payload === 'object' @@ -235,6 +252,19 @@ async function callConnector( } return payload as T } catch (error) { + if (!(error && typeof error === 'object' && 'statusCode' in error)) { + recordSemiAutoTrace({ + direction: 'outbound', + channel: 'external_connector', + action: `${method} ${path}`, + status: 'error', + durationMs: Date.now() - startedAt, + requestSummary: { baseUrl: endpoint.baseUrl }, + requestBody: options.body, + always: true, + errorMessage: error instanceof Error ? error.message : String(error), + }) + } if (error && typeof error === 'object' && 'statusCode' in error) throw error if (error instanceof Error && error.name === 'AbortError') { throw createHttpError('半自动履约 Connector 请求超时', { diff --git a/apps/backend/src/services/semi-auto/huya-native/huya-rpc.ts b/apps/backend/src/services/semi-auto/huya-native/huya-rpc.ts index 1135af87..9f2f0fe5 100644 --- a/apps/backend/src/services/semi-auto/huya-native/huya-rpc.ts +++ b/apps/backend/src/services/semi-auto/huya-native/huya-rpc.ts @@ -2,6 +2,7 @@ import crypto from 'node:crypto' +import { recordSemiAutoTrace, traceFingerprint } from '../semi-auto-trace.js' import { buildHuyaLoginContext, cookiePairs, cookieValue, normalizeCookiePairs } from './cookie.js' import { decodeWupResponse, @@ -494,22 +495,67 @@ export class HuyaRpcClient { gid?: number scene?: string }): Promise { - const response = await this.callRpc( - 'webActUI', - 'checkUserBindGameAccount', - input.uid, - input.cookie, - (writer) => { - this.writeActivityUser(writer, input.uid, input.cookie) - writer.writeInt32(1, input.gid || 0) - writer.writeString(2, input.outerActId || '') - writer.writeInt32(3, 0) - writer.writeString(4, input.scene || '') - writer.writeInt32(5, input.bindActId || 0) - writer.writeInt32(6, input.isUseOuterActId ?? 1) - }, - ) - return response ? readWupStruct(response, parseBindResponse) : null + const startedAt = Date.now() + const request = { + servant: 'webActUI', + func: 'checkUserBindGameAccount', + uid: input.uid, + gid: input.gid || 0, + outerActId: input.outerActId || '', + bindActId: input.bindActId || 0, + isUseOuterActId: input.isUseOuterActId ?? 1, + scene: input.scene || '', + } + try { + const response = await this.callRpc( + 'webActUI', + 'checkUserBindGameAccount', + input.uid, + input.cookie, + (writer) => { + this.writeActivityUser(writer, input.uid, input.cookie) + writer.writeInt32(1, input.gid || 0) + writer.writeString(2, input.outerActId || '') + writer.writeInt32(3, 0) + writer.writeString(4, input.scene || '') + writer.writeInt32(5, input.bindActId || 0) + writer.writeInt32(6, input.isUseOuterActId ?? 1) + }, + ) + const parsed = response ? readWupStruct(response, parseBindResponse) : null + recordSemiAutoTrace({ + direction: 'outbound', + channel: 'huya_wup', + action: 'webActUI.checkUserBindGameAccount', + status: parsed && parsed.status === 200 ? 'ok' : 'error', + durationMs: Date.now() - startedAt, + requestSummary: request, + responseSummary: { status: parsed?.status, msg: parsed?.msg }, + responseBody: parsed, + // 绑定轮询:状态没变化就不落库。 + fingerprint: traceFingerprint({ + status: parsed?.status, + msg: parsed?.msg, + isBindAccount: parsed?.accountData?.isBindAccount, + isBindRole: parsed?.accountData?.isBindRole, + role: parsed?.accountData?.gameRole?.roleName, + roleId: parsed?.accountData?.gameRole?.roleId, + }), + errorMessage: parsed && parsed.status !== 200 ? String(parsed.msg || '') : '', + }) + return parsed + } catch (error) { + recordSemiAutoTrace({ + direction: 'outbound', + channel: 'huya_wup', + action: 'webActUI.checkUserBindGameAccount', + status: 'error', + durationMs: Date.now() - startedAt, + requestSummary: request, + errorMessage: error instanceof Error ? error.message : String(error), + }) + throw error + } } async confirmBindActAccount(input: { @@ -519,19 +565,55 @@ export class HuyaRpcClient { outerActId: string gid?: number }): Promise { - const response = await this.callRpc( - 'webActUI', - 'confirmBindActAccount', - input.uid, - input.cookie, - (writer) => { - this.writeActivityUser(writer, input.uid, input.cookie) - writer.writeInt32(1, input.gid || 0) - writer.writeString(2, input.outerActId || '') - writer.writeInt32(3, input.bindActId || 0) - }, - ) - return response ? readWupStruct(response, parseConfirmResponse) : null + const startedAt = Date.now() + const request = { + servant: 'webActUI', + func: 'confirmBindActAccount', + uid: input.uid, + gid: input.gid || 0, + outerActId: input.outerActId || '', + bindActId: input.bindActId || 0, + } + try { + const response = await this.callRpc( + 'webActUI', + 'confirmBindActAccount', + input.uid, + input.cookie, + (writer) => { + this.writeActivityUser(writer, input.uid, input.cookie) + writer.writeInt32(1, input.gid || 0) + writer.writeString(2, input.outerActId || '') + writer.writeInt32(3, input.bindActId || 0) + }, + ) + const parsed = response ? readWupStruct(response, parseConfirmResponse) : null + recordSemiAutoTrace({ + direction: 'outbound', + channel: 'huya_wup', + action: 'webActUI.confirmBindActAccount', + status: parsed && parsed.status === 200 ? 'ok' : 'error', + durationMs: Date.now() - startedAt, + requestSummary: request, + responseSummary: { status: parsed?.status, msg: parsed?.msg }, + responseBody: parsed, + always: true, + errorMessage: parsed && parsed.status !== 200 ? String(parsed.msg || '') : '', + }) + return parsed + } catch (error) { + recordSemiAutoTrace({ + direction: 'outbound', + channel: 'huya_wup', + action: 'webActUI.confirmBindActAccount', + status: 'error', + durationMs: Date.now() - startedAt, + requestSummary: request, + always: true, + errorMessage: error instanceof Error ? error.message : String(error), + }) + throw error + } } async getLiveLinkParam(input: { @@ -541,21 +623,57 @@ export class HuyaRpcClient { outerActId: number gameAuthScene?: string }): Promise { - const response = await this.callRpc( - 'webActUI', - 'getLiveLinkParam', - input.uid, - input.cookie, - (writer) => { - this.writeActivityUser(writer, input.uid, input.cookie) - writer.writeInt32(1, 0) - writer.writeInt32(2, input.outerActId || 0) - writer.writeString(3, input.gameAuthScene || '') - writer.writeString(4, '') - writer.writeInt32(5, input.bindActId || 0) - }, - ) - return response ? readWupStruct(response, parseLiveLinkResponse) : null + const startedAt = Date.now() + const request = { + servant: 'webActUI', + func: 'getLiveLinkParam', + uid: input.uid, + bindActId: input.bindActId || 0, + outerActId: input.outerActId || 0, + gameAuthScene: input.gameAuthScene || '', + } + try { + const response = await this.callRpc( + 'webActUI', + 'getLiveLinkParam', + input.uid, + input.cookie, + (writer) => { + this.writeActivityUser(writer, input.uid, input.cookie) + writer.writeInt32(1, 0) + writer.writeInt32(2, input.outerActId || 0) + writer.writeString(3, input.gameAuthScene || '') + writer.writeString(4, '') + writer.writeInt32(5, input.bindActId || 0) + }, + ) + const parsed = response ? readWupStruct(response, parseLiveLinkResponse) : null + recordSemiAutoTrace({ + direction: 'outbound', + channel: 'huya_wup', + action: 'webActUI.getLiveLinkParam', + status: parsed && parsed.status === 200 ? 'ok' : 'error', + durationMs: Date.now() - startedAt, + requestSummary: request, + responseSummary: { status: parsed?.status, msg: parsed?.msg }, + responseBody: parsed, + always: true, + errorMessage: parsed && parsed.status !== 200 ? String(parsed.msg || '') : '', + }) + return parsed + } catch (error) { + recordSemiAutoTrace({ + direction: 'outbound', + channel: 'huya_wup', + action: 'webActUI.getLiveLinkParam', + status: 'error', + durationMs: Date.now() - startedAt, + requestSummary: request, + always: true, + errorMessage: error instanceof Error ? error.message : String(error), + }) + throw error + } } async getUserProfileBatch(input: { @@ -585,17 +703,53 @@ export class HuyaRpcClient { }): Promise { const targetUid = Math.trunc(input.targetUid) if (!(targetUid > 0)) return null - const response = await this.callRpc( - 'huyauserui', - 'getUserProfile', - input.uid, - input.cookie, - (writer) => { - this.writeActivityUser(writer, 0, input.cookie) - writer.writeInt64(1, targetUid) - }, - ) - return response ? readWupStruct(response, parseProfileResponse) : null + const startedAt = Date.now() + try { + const response = await this.callRpc( + 'huyauserui', + 'getUserProfile', + input.uid, + input.cookie, + (writer) => { + this.writeActivityUser(writer, 0, input.cookie) + writer.writeInt64(1, targetUid) + }, + ) + const parsed = response ? readWupStruct(response, parseProfileResponse) : null + recordSemiAutoTrace({ + direction: 'outbound', + channel: 'huya_wup', + action: 'huyauserui.getUserProfile', + status: parsed ? 'ok' : 'error', + durationMs: Date.now() - startedAt, + requestSummary: { + servant: 'huyauserui', + func: 'getUserProfile', + uid: input.uid, + targetUid, + }, + responseBody: parsed, + always: true, + }) + return parsed + } catch (error) { + recordSemiAutoTrace({ + direction: 'outbound', + channel: 'huya_wup', + action: 'huyauserui.getUserProfile', + status: 'error', + durationMs: Date.now() - startedAt, + requestSummary: { + servant: 'huyauserui', + func: 'getUserProfile', + uid: input.uid, + targetUid, + }, + always: true, + errorMessage: error instanceof Error ? error.message : String(error), + }) + throw error + } } private async callRpc( @@ -715,6 +869,7 @@ export async function getLiveLinkMiniQrcode( ).join('') const sessionId = `${Math.floor(Date.now() / 1000)}_${suffix}` const fetchImpl = options.fetchImpl || fetch + const startedAt = Date.now() const response = await fetchImpl(`${LIVELINK_BIND_API_BASE}/api/qrcode/getMiniAppQrcode`, { method: 'POST', headers: { @@ -728,14 +883,41 @@ export async function getLiveLinkMiniQrcode( body: JSON.stringify({ queryString: `${query}&sessionId=${sessionId}` }), signal: AbortSignal.timeout(options.timeoutMs || 15_000), }) - if (!response.ok) return null + const traceMiniQrcode = (status: 'ok' | 'error', extra: Record = {}) => { + recordSemiAutoTrace({ + direction: 'outbound', + channel: 'huya_http', + action: 'livelink.getMiniAppQrcode', + status, + durationMs: Date.now() - startedAt, + httpStatus: response.status, + requestSummary: { api: 'getMiniAppQrcode', queryLength: query.length }, + responseSummary: extra, + always: true, + }) + } + if (!response.ok) { + traceMiniQrcode('error', { httpStatus: response.status }) + return null + } const payload = (await response.json().catch(() => null)) as { iRet?: number jData?: { qrcode?: string; qrcodeToken?: string } } | null - if (!payload || payload.iRet !== 0) return null + if (!payload || payload.iRet !== 0) { + traceMiniQrcode('error', { iRet: payload?.iRet ?? null }) + return null + } const image = livelinkQrcodeImageSrc(String(payload.jData?.qrcode || '')) - if (!image) return null + if (!image) { + traceMiniQrcode('error', { iRet: payload.iRet, hasImage: false }) + return null + } + traceMiniQrcode('ok', { + iRet: payload.iRet, + hasImage: true, + tokenLength: String(payload.jData?.qrcodeToken || '').length, + }) return { image, token: String(payload.jData?.qrcodeToken || '') } } @@ -751,6 +933,7 @@ export async function getLiveLinkQrcodeStatus( const normalized = String(token || '').trim() if (!normalized) return null const fetchImpl = options.fetchImpl || fetch + const startedAt = Date.now() const response = await fetchImpl(`${LIVELINK_BIND_API_BASE}/api/qrcode/poolingQrcodeStatus`, { method: 'POST', headers: { @@ -764,7 +947,24 @@ export async function getLiveLinkQrcodeStatus( body: JSON.stringify({ qrcodeToken: normalized }), signal: AbortSignal.timeout(options.timeoutMs || 15_000), }) - if (!response.ok) return null + const traceQrcodeStatus = (status: 'ok' | 'error', extra: Record = {}) => { + recordSemiAutoTrace({ + direction: 'outbound', + channel: 'huya_http', + action: 'livelink.poolingQrcodeStatus', + status, + durationMs: Date.now() - startedAt, + httpStatus: response.status, + requestSummary: { api: 'poolingQrcodeStatus', tokenLength: normalized.length }, + responseSummary: extra, + // 二维码轮询:状态没变化就不落库。 + fingerprint: traceFingerprint(extra), + }) + } + if (!response.ok) { + traceQrcodeStatus('error', { httpStatus: response.status }) + return null + } const payload = (await response.json().catch(() => null)) as { iRet?: number jData?: { @@ -774,13 +974,18 @@ export async function getLiveLinkQrcodeStatus( isFailure?: boolean } } | null - if (!payload || payload.iRet !== 0) return null - return { + if (!payload || payload.iRet !== 0) { + traceQrcodeStatus('error', { iRet: payload?.iRet ?? null }) + return null + } + const result = { isScan: Boolean(payload.jData?.isScan), isExpired: Boolean(payload.jData?.isExpired), isCompleted: Boolean(payload.jData?.isCompleted), isFailure: Boolean(payload.jData?.isFailure), } + traceQrcodeStatus('ok', { iRet: payload.iRet, ...result }) + return result } export function buildBindUrls(input: { diff --git a/apps/backend/src/services/semi-auto/semi-auto-task-service.ts b/apps/backend/src/services/semi-auto/semi-auto-task-service.ts index 97a75624..18994e1d 100644 --- a/apps/backend/src/services/semi-auto/semi-auto-task-service.ts +++ b/apps/backend/src/services/semi-auto/semi-auto-task-service.ts @@ -55,6 +55,7 @@ import { markSemiAutoCredentialCheck, upsertSemiAutoCredentialWithClient, } from './semi-auto-credential-service.js' +import { querySemiAutoTraces } from './semi-auto-trace.js' const SEMI_AUTO_PLATFORMS = new Set(['huya', 'weibo']) type SemiAutoPlatform = 'huya' | 'weibo' @@ -920,19 +921,22 @@ async function updateLoginTask( credentialId, ], ) - await appendTaskEvent(client, task.id, { - eventType: 'login_status_changed', - actorType, - fromLoginStatus: task.login_status, - toLoginStatus: mapped.status, - fromExecutionStatus: task.execution_status, - toExecutionStatus: nextExecutionStatus, - detail: { - hasCredential: mapped.hasCredential, - message: mapped.message, - method: options.method || 'qr', - }, - }) + // 轮询会每 2 秒调用一次:状态与执行状态都没变时不写事件,避免时间线被重复项淹没。 + if (mapped.status !== task.login_status || nextExecutionStatus !== task.execution_status) { + await appendTaskEvent(client, task.id, { + eventType: 'login_status_changed', + actorType, + fromLoginStatus: task.login_status, + toLoginStatus: mapped.status, + fromExecutionStatus: task.execution_status, + toExecutionStatus: nextExecutionStatus, + detail: { + hasCredential: mapped.hasCredential, + message: mapped.message, + method: options.method || 'qr', + }, + }) + } }) } @@ -1130,32 +1134,40 @@ async function updateBindingTask( mapped.bindGameRoleId, ], ) - await appendTaskEvent(client, task.id, { - eventType: 'binding_status_changed', - actorType, - fromBindingStatus: task.binding_status, - toBindingStatus: mapped.status, - fromExecutionStatus: task.execution_status, - toExecutionStatus: executionStatus, - detail: { - gameAccount: mapped.bindGameAccount, - gameRole: mapped.bindGameRole, - gameRoleId: mapped.bindGameRoleId, - gameChannel: mapped.bindGameChannel, - verdict: comparison.verdict, - rebindRequested: mapped.rebindRequested, - rebindUnchanged: mapped.rebindUnchanged, - rebindConfirmState: mapped.rebindConfirmState, - rebindConfirmMessage: mapped.rebindConfirmMessage, - bindConfirmState: mapped.bindConfirmState, - bindConfirmMessage: mapped.bindConfirmMessage, - rebindCooldownDays: mapped.rebindCooldownDays, - nextRebindAt: mapped.nextRebindAt, - changeBindDay: mapped.platformChangeBindDay, - changeBindTime: mapped.platformChangeBindTime, - message: mapped.message, - }, - }) + // 轮询会每 2 秒调用一次:只有状态/执行状态变化,或换绑被拒这类关键信号才写事件。 + const bindingChanged = + mapped.status !== task.binding_status || + executionStatus !== task.execution_status || + mapped.rebindUnchanged || + mapped.rebindConfirmState === 'rejected' + if (bindingChanged) { + await appendTaskEvent(client, task.id, { + eventType: 'binding_status_changed', + actorType, + fromBindingStatus: task.binding_status, + toBindingStatus: mapped.status, + fromExecutionStatus: task.execution_status, + toExecutionStatus: executionStatus, + detail: { + gameAccount: mapped.bindGameAccount, + gameRole: mapped.bindGameRole, + gameRoleId: mapped.bindGameRoleId, + gameChannel: mapped.bindGameChannel, + verdict: comparison.verdict, + rebindRequested: mapped.rebindRequested, + rebindUnchanged: mapped.rebindUnchanged, + rebindConfirmState: mapped.rebindConfirmState, + rebindConfirmMessage: mapped.rebindConfirmMessage, + bindConfirmState: mapped.bindConfirmState, + bindConfirmMessage: mapped.bindConfirmMessage, + rebindCooldownDays: mapped.rebindCooldownDays, + nextRebindAt: mapped.nextRebindAt, + changeBindDay: mapped.platformChangeBindDay, + changeBindTime: mapped.platformChangeBindTime, + message: mapped.message, + }, + }) + } }) return { status: mapped.status, @@ -1916,6 +1928,78 @@ export async function getAdminSemiAutoTask(taskIdInput: unknown) { } } +type SemiAutoTaskEventRow = { + id: number + event_type: string + actor_type: string + actor_id: string + from_login_status: string | null + to_login_status: string | null + from_binding_status: string | null + to_binding_status: string | null + from_execution_status: string | null + to_execution_status: string | null + detail_json: Record + created_at: string +} + +/** + * 运营端「历史」:任务状态流转事件 + 全链路报文(本系统入站 + 外部平台出站)。 + * 报文只读,不做任何写操作;Cookie / Token 已在落库前脱敏。 + */ +export async function getAdminSemiAutoTaskHistory( + taskIdInput: unknown, + input: Record = {}, +) { + const task = await loadTask(normalizeId(taskIdInput)) + const eventCount = await query<{ total: number }>( + `SELECT COUNT(*)::int AS total FROM semi_auto_task_events WHERE task_id = $1`, + [task.id], + ) + const events = await query( + `SELECT * FROM ( + SELECT id, event_type, actor_type, actor_id, + from_login_status, to_login_status, + from_binding_status, to_binding_status, + from_execution_status, to_execution_status, + detail_json, created_at + FROM semi_auto_task_events + WHERE task_id = $1 + ORDER BY id DESC + LIMIT 500 + ) recent + ORDER BY id ASC`, + [task.id], + ) + const traces = await querySemiAutoTraces(task.id, { + page: Number(input.page) || 1, + pageSize: Number(input.pageSize) || 50, + channel: String(input.channel || '').trim(), + status: String(input.status || '').trim(), + requestId: String(input.requestId || '').trim(), + keyword: String(input.keyword || '').trim(), + }) + return { + task: mapTask(task), + events: events.rows.map((event) => ({ + id: Number(event.id), + eventType: event.event_type, + actorType: event.actor_type, + actorId: event.actor_id, + fromLoginStatus: event.from_login_status, + toLoginStatus: event.to_login_status, + fromBindingStatus: event.from_binding_status, + toBindingStatus: event.to_binding_status, + fromExecutionStatus: event.from_execution_status, + toExecutionStatus: event.to_execution_status, + detail: event.detail_json || {}, + createdAt: event.created_at, + })), + eventTotal: Number(eventCount.rows[0]?.total || 0), + traces, + } +} + export async function exportAdminSemiAutoCredential(taskIdInput: unknown) { const task = await loadTask(normalizeId(taskIdInput)) if (!task.credential_id) { diff --git a/apps/backend/src/services/semi-auto/semi-auto-trace.ts b/apps/backend/src/services/semi-auto/semi-auto-trace.ts new file mode 100644 index 00000000..0788d1a7 --- /dev/null +++ b/apps/backend/src/services/semi-auto/semi-auto-trace.ts @@ -0,0 +1,326 @@ +import { AsyncLocalStorage } from 'node:async_hooks' +import crypto from 'node:crypto' + +import { query } from '../../db/client.js' +import { logWarn } from '../../utils/logger.js' + +/** 报文保留天数:180 天,由 startSemiAutoTraceCleanup 定时清理。 */ +export const SEMI_AUTO_TRACE_RETENTION_DAYS = 180 +const MAX_BODY_CHARS = 32_000 +const MAX_REDACT_DEPTH = 6 +const FINGERPRINT_LIMIT = 5_000 + +export type SemiAutoTraceChannel = + | 'customer_api' + | 'admin_api' + | 'huya_wup' + | 'huya_http' + | 'external_connector' + +export type SemiAutoTraceContext = { + requestId: string + taskId?: number + orderNo?: string + source?: string +} + +export type SemiAutoTraceEntry = { + taskId?: number + orderNo?: string + requestId?: string + direction: 'inbound' | 'outbound' + channel: SemiAutoTraceChannel | string + action: string + status?: 'ok' | 'error' + httpStatus?: number + durationMs?: number + requestSummary?: Record + requestBody?: unknown + responseSummary?: Record + responseBody?: unknown + errorMessage?: string + /** 写操作/关键读:无条件记录(轮询类不要传)。 */ + always?: boolean + /** 轮询类请求的状态指纹:与上次相同则不记录。 */ + fingerprint?: string | undefined +} + +const traceStorage = new AsyncLocalStorage() +const lastFingerprints = new Map() + +/** Cookie / Token / 密钥字段:一律不落库。 */ +const SENSITIVE_KEYS = new Set([ + 'cookie', + 'set-cookie', + 'authorization', + 'proxyauthorization', + 'token', + 'accesstoken', + 'access_token', + 'refreshtoken', + 'refresh_token', + 'biztoken', + 'udb_biztoken', + 'password', + 'passwd', + 'secret', + 'apikey', + 'api_key', + 'x-semi-auto-key', + 'sig', + 'qrcodetoken', + 'qrcode_token', + 'qrcontent', + 'qr_content', + 'qrimage', + 'qr_image', + 'query_string', + 'smscode', + 'sms_code', + 'sessionid', + 'session_id', + 'baseinfo', + 'cookies', + 'cookie_header', + 'cookieheader', + 'ticket', + 'credential_payload_json', +]) + +export function runWithSemiAutoTrace(context: SemiAutoTraceContext, fn: () => T): T { + return traceStorage.run(context, fn) +} + +export function currentSemiAutoTrace(): SemiAutoTraceContext | undefined { + return traceStorage.getStore() +} + +function maskValue(value: unknown): unknown { + if (value === null || value === undefined) return value + if (typeof value !== 'string') return '******' + return value.length > 0 ? '******' : '' +} + +function normalizeKey(key: string): string { + return key.replace(/([a-z0-9])([A-Z])/g, '$1_$2').toLowerCase() +} + +/** 深度脱敏:Cookie / Token / 密钥字段直接替换为 ******。 */ +export function redactTraceValue(value: unknown, depth = 0): unknown { + if (depth > MAX_REDACT_DEPTH) return '[max-depth]' + if (value === null || value === undefined) return value + if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { + return value + } + if (Array.isArray(value)) { + return value.slice(0, 50).map((item) => redactTraceValue(item, depth + 1)) + } + if (typeof value === 'object') { + const source = value as Record + const result: Record = {} + for (const [key, current] of Object.entries(source)) { + result[key] = SENSITIVE_KEYS.has(normalizeKey(key)) + ? maskValue(current) + : redactTraceValue(current, depth + 1) + } + return result + } + return String(value) +} + +export function stringifyTraceBody(value: unknown): string { + if (value === undefined || value === null) return '' + if (typeof value === 'string') { + return value.length > MAX_BODY_CHARS + ? `${value.slice(0, MAX_BODY_CHARS)}\n...[truncated]` + : value + } + try { + const text = JSON.stringify(redactTraceValue(value), null, 2) + return text.length > MAX_BODY_CHARS ? `${text.slice(0, MAX_BODY_CHARS)}\n...[truncated]` : text + } catch { + return String(value).slice(0, MAX_BODY_CHARS) + } +} + +function fingerprintKey(entry: SemiAutoTraceEntry): string { + return `${entry.taskId || 0}|${entry.channel}|${entry.action}` +} + +/** + * 采样:写操作与关键读一律记录;轮询类只在状态变化或失败时记录,避免每 2 秒一条。 + */ +export function shouldRecordTrace(entry: SemiAutoTraceEntry): boolean { + if (entry.always) return true + if ((entry.status || 'ok') === 'error') return true + const fingerprint = String(entry.fingerprint || '') + if (!fingerprint) return true + const key = fingerprintKey(entry) + const previous = lastFingerprints.get(key) + if (previous === fingerprint) return false + lastFingerprints.set(key, fingerprint) + if (lastFingerprints.size > FINGERPRINT_LIMIT) lastFingerprints.clear() + return true +} + +/** 记录一条报文:异步落库,失败只记日志,绝不阻断主流程。 */ +export function recordSemiAutoTrace(entry: SemiAutoTraceEntry): void { + const context = currentSemiAutoTrace() + const taskId = Number(entry.taskId || context?.taskId || 0) + if (!Number.isFinite(taskId) || taskId <= 0) return + if (!shouldRecordTrace(entry)) return + const orderNo = entry.orderNo || context?.orderNo || '' + const requestId = entry.requestId || context?.requestId || '' + const status = entry.status === 'error' ? 'error' : 'ok' + const requestBody = stringifyTraceBody(entry.requestBody) + const responseBody = stringifyTraceBody(entry.responseBody) + void query( + `INSERT INTO semi_auto_trace_logs ( + task_id, order_no, request_id, direction, channel, action, status, + http_status, duration_ms, request_summary, request_body, + response_summary, response_body, error_message, created_at + ) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10::jsonb,$11,$12::jsonb,$13,$14,NOW())`, + [ + taskId, + orderNo, + requestId, + entry.direction, + entry.channel, + entry.action, + status, + entry.httpStatus ?? null, + entry.durationMs ?? null, + JSON.stringify(redactTraceValue(entry.requestSummary || {})), + requestBody, + JSON.stringify(redactTraceValue(entry.responseSummary || {})), + responseBody, + String(entry.errorMessage || ''), + ], + ).catch((error) => { + logWarn('semi-auto/trace', '写入报文失败', { + taskId, + action: entry.action, + error: error instanceof Error ? error.message : String(error), + }) + }) +} + +/** 供调用方快速生成一个轮询指纹。 */ +export function traceFingerprint(value: unknown): string { + if (value === null || value === undefined) return '' + let text = '' + if (typeof value === 'string') { + text = value + } else { + try { + text = JSON.stringify(value) + } catch { + text = String(value) + } + } + return crypto.createHash('sha1').update(text).digest('hex') +} + +export type SemiAutoTraceQuery = { + page?: number + pageSize?: number + channel?: string + status?: string + requestId?: string + keyword?: string +} + +export async function querySemiAutoTraces(taskId: number, input: SemiAutoTraceQuery = {}) { + const page = Math.max(1, Math.floor(Number(input.page) || 1)) + const pageSize = Math.min(200, Math.max(1, Math.floor(Number(input.pageSize) || 50))) + const conditions = ['task_id = $1'] + const params: unknown[] = [taskId] + if (input.channel) { + params.push(String(input.channel)) + conditions.push(`channel = $${params.length}`) + } + if (input.status) { + params.push(String(input.status)) + conditions.push(`status = $${params.length}`) + } + if (input.requestId) { + params.push(String(input.requestId)) + conditions.push(`request_id = $${params.length}`) + } + if (input.keyword) { + params.push(`%${String(input.keyword).trim()}%`) + conditions.push( + `(action ILIKE $${params.length} OR request_body ILIKE $${params.length} OR response_body ILIKE $${params.length})`, + ) + } + const where = conditions.join(' AND ') + const count = await query( + `SELECT COUNT(*)::int AS total FROM semi_auto_trace_logs WHERE ${where}`, + params, + ) + const rows = await query( + `SELECT id, order_no, request_id, direction, channel, action, status, + http_status, duration_ms, request_summary, request_body, + response_summary, response_body, error_message, created_at + FROM semi_auto_trace_logs + WHERE ${where} + ORDER BY id DESC + LIMIT $${params.length + 1} OFFSET $${params.length + 2}`, + [...params, pageSize, (page - 1) * pageSize], + ) + const summary = await query( + `SELECT channel, status, COUNT(*)::int AS total + FROM semi_auto_trace_logs + WHERE task_id = $1 + GROUP BY channel, status`, + [taskId], + ) + return { + pagination: { page, pageSize, total: Number(count.rows[0]?.total || 0) }, + summary: summary.rows, + items: rows.rows.map((row) => ({ + id: Number(row.id), + orderNo: row.order_no, + requestId: row.request_id, + direction: row.direction, + channel: row.channel, + action: row.action, + status: row.status, + httpStatus: row.http_status, + durationMs: row.duration_ms, + requestSummary: row.request_summary || {}, + requestBody: row.request_body || '', + responseSummary: row.response_summary || {}, + responseBody: row.response_body || '', + errorMessage: row.error_message || '', + createdAt: row.created_at, + })), + } +} + +export async function cleanupSemiAutoTraces(retentionDays = SEMI_AUTO_TRACE_RETENTION_DAYS) { + const days = Math.max(1, Math.floor(Number(retentionDays) || SEMI_AUTO_TRACE_RETENTION_DAYS)) + const result = await query( + `DELETE FROM semi_auto_trace_logs WHERE created_at < NOW() - ($1 || ' days')::interval`, + [String(days)], + ) + return result.rowCount || 0 +} + +let cleanupStarted = false + +/** 启动时清一次,之后每 6 小时清理超过保留期的报文。 */ +export function startSemiAutoTraceCleanup(): void { + if (cleanupStarted) return + cleanupStarted = true + const run = () => { + void cleanupSemiAutoTraces().catch((error) => { + logWarn('semi-auto/trace', '清理历史报文失败', { + error: error instanceof Error ? error.message : String(error), + }) + }) + } + run() + const timer = setInterval(run, 6 * 60 * 60 * 1000) + timer.unref?.() +} diff --git a/apps/frontend/src/components/admin/SemiAutoTaskHistoryDrawer.tsx b/apps/frontend/src/components/admin/SemiAutoTaskHistoryDrawer.tsx new file mode 100644 index 00000000..10837271 --- /dev/null +++ b/apps/frontend/src/components/admin/SemiAutoTaskHistoryDrawer.tsx @@ -0,0 +1,501 @@ +import { CopyOutlined, ReloadOutlined } from '@ant-design/icons' +import { + App, + Button, + Collapse, + Drawer, + Empty, + Input, + Pagination, + Select, + Space, + Tabs, + Tag, + theme, + Timeline, + Typography, +} from 'antd' +import { useQuery } from '@tanstack/react-query' +import { useEffect, useMemo, useState } from 'react' +import type { CSSProperties } from 'react' + +import { fetchAdminSemiAutoTaskHistory } from '@/services/admin/semi-auto' +import type { SemiAutoTaskHistoryEvent, SemiAutoTraceItem } from '@/types/admin/semi-auto' +import { formatAdminDateTime } from '@/utils/admin-time' +import { useIsMobile } from '@/utils/use-is-mobile' + +const { Text } = Typography + +const EVENT_LABELS: Record = { + task_created: '任务创建', + customer_link_opened: '客户打开链接', + customer_profile_saved: '客户保存角色资料', + login_started: '开始平台登录', + login_status_changed: '登录状态变更', + binding_status_changed: '绑定状态变更', + task_claimed: '客服领取', + customer_reauth_requested: '重新发起客户授权', + browser_session_opened: '生成浏览器注入票据', + credential_session_restored: '凭证恢复登录', + credential_invalidated: '凭证失效', + task_completed: '订单完成', + task_cancelled: '订单取消', +} + +const CHANNEL_LABELS: Record = { + customer_api: '客户接口', + admin_api: '运营接口', + huya_wup: '虎牙 WUP', + huya_http: '虎牙 HTTP', + external_connector: '外部 Connector', +} + +const CHANNEL_OPTIONS = Object.keys(CHANNEL_LABELS).map((value) => ({ + value, + label: CHANNEL_LABELS[value], +})) + +const LOGIN_STATUS_LABELS: Record = { + waiting_login: '等待登录', + qr_pending: '待扫码', + scanned: '已扫码', + authenticated: '已登录', + failed: '登录失败', + expired: '登录过期', +} + +const BINDING_STATUS_LABELS: Record = { + not_started: '未开始', + qr_pending: '待扫码', + scanned: '已扫码', + role_ready: '待确认角色', + confirmed: '已确认', + failed: '绑定失败', + expired: '已过期', +} + +const EXECUTION_STATUS_LABELS: Record = { + waiting_customer: '等待客户', + waiting_operator: '等待客服', + processing: '处理中', + completed: '已完成', + failed: '失败', + cancelled: '已取消', +} + +type SemiAutoTaskHistoryDrawerProps = { + open: boolean + taskId: number | null + onClose: () => void +} + +export default function SemiAutoTaskHistoryDrawer({ + open, + taskId, + onClose, +}: SemiAutoTaskHistoryDrawerProps) { + const { message } = App.useApp() + const isMobile = useIsMobile() + const { token } = theme.useToken() + const [tab, setTab] = useState('events') + const [channel, setChannel] = useState('') + const [status, setStatus] = useState('') + const [keywordDraft, setKeywordDraft] = useState('') + const [keyword, setKeyword] = useState('') + const [requestId, setRequestId] = useState('') + const [page, setPage] = useState(1) + const [pageSize, setPageSize] = useState(50) + + useEffect(() => { + if (!open) return + setTab('events') + setChannel('') + setStatus('') + setKeywordDraft('') + setKeyword('') + setRequestId('') + setPage(1) + setPageSize(50) + }, [open, taskId]) + + const params = useMemo( + () => ({ + page, + pageSize, + channel: channel || undefined, + status: status || undefined, + keyword: keyword.trim() || undefined, + requestId: requestId || undefined, + }), + [channel, keyword, page, pageSize, requestId, status], + ) + + const historyQuery = useQuery({ + queryKey: ['admin-semi-auto-task-history', taskId, params], + queryFn: () => fetchAdminSemiAutoTaskHistory(Number(taskId), params), + enabled: open && Boolean(taskId), + refetchInterval: open && Boolean(taskId) ? 8000 : false, + }) + + const history = historyQuery.data?.data + const events = history?.events || [] + const traces = history?.traces + const traceItems = traces?.items || [] + const preStyle: CSSProperties = { + margin: '6px 0 0', + padding: 10, + background: token.colorFillQuaternary, + border: `1px solid ${token.colorBorderSecondary}`, + borderRadius: token.borderRadius, + color: token.colorText, + fontSize: 12, + lineHeight: 1.55, + maxHeight: 320, + overflow: 'auto', + whiteSpace: 'pre-wrap', + wordBreak: 'break-all', + } + + const copyText = (text: string, label: string) => { + if (!text) { + message.warning(`${label}为空`) + return + } + void navigator.clipboard + .writeText(text) + .then(() => message.success(`${label}已复制`)) + .catch(() => message.error('复制失败,请手动选择文本复制')) + } + + const eventsPanel = ( + + {history?.task ? ( + + + 登录:{LOGIN_STATUS_LABELS[history.task.loginStatus] || history.task.loginStatus} + + + 绑定: + {history.task.platform === 'weibo' + ? '登录即授权' + : BINDING_STATUS_LABELS[history.task.bindingStatus] || history.task.bindingStatus} + + + 执行: + {EXECUTION_STATUS_LABELS[history.task.executionStatus] || history.task.executionStatus} + + 创建 {formatAdminDateTime(history.task.createdAt)} + {history.task.completedAt ? ( + 完成 {formatAdminDateTime(history.task.completedAt)} + ) : null} + + ) : null} + {history && history.eventTotal > events.length ? ( + + 仅展示最近 {events.length} 条状态事件,共 {history.eventTotal} 条。 + + ) : null} + {historyQuery.isLoading ? ( + 加载中... + ) : events.length === 0 ? ( + + ) : ( + ({ + color: /fail|invalid|error|cancel/i.test(event.eventType) ? 'red' : 'blue', + children: , + }))} + /> + )} + + ) + + const tracesPanel = ( + +
+ { + setStatus(value || '') + setPage(1) + }} + options={[ + { value: 'ok', label: '成功' }, + { value: 'error', label: '失败' }, + ]} + style={isMobile ? { flex: '1 1 110px', minWidth: 96 } : { width: 120 }} + /> + setKeywordDraft(event.target.value)} + onSearch={(value) => { + setKeyword(value) + setPage(1) + }} + style={isMobile ? { flex: '1 1 220px' } : { width: 240 }} + /> + + {requestId ? ( + { + setRequestId('') + setPage(1) + }} + > + 同一请求:{requestId} + + ) : null} +
+ {traces?.summary?.length ? ( + + {traces.summary.map((item) => ( + + {CHANNEL_LABELS[item.channel] || item.channel} ·{' '} + {item.status === 'error' ? '失败' : '成功'} {item.total} + + ))} + + ) : null} + 报文保留 180 天;Cookie、Token、短信验证码和二维码内容不落库。 + {historyQuery.isLoading ? ( + 加载中... + ) : traceItems.length === 0 ? ( + + ) : ( + ({ + key: String(item.id), + label: , + children: ( + { + setRequestId(value) + setPage(1) + }} + /> + ), + }))} + /> + )} + `共 ${total} 条`} + onChange={(nextPage, nextPageSize) => { + setPage(nextPage) + setPageSize(nextPageSize) + }} + /> +
+ ) + + return ( + } onClick={() => void historyQuery.refetch()}> + 刷新 + + } + > + + + ) +} + +function EventItem({ + event, + preStyle, +}: { + event: SemiAutoTaskHistoryEvent + preStyle: CSSProperties +}) { + const detail = event.detail || {} + const detailKeys = Object.keys(detail) + const transitions = [ + { + label: '登录', + map: LOGIN_STATUS_LABELS, + from: event.fromLoginStatus, + to: event.toLoginStatus, + }, + { + label: '绑定', + map: BINDING_STATUS_LABELS, + from: event.fromBindingStatus, + to: event.toBindingStatus, + }, + { + label: '执行', + map: EXECUTION_STATUS_LABELS, + from: event.fromExecutionStatus, + to: event.toExecutionStatus, + }, + ].filter((item) => item.from !== item.to && Boolean(item.from || item.to)) + + return ( + + {EVENT_LABELS[event.eventType] || event.eventType} + + {formatAdminDateTime(event.createdAt)} · {event.actorType} + {event.actorId ? ` ${event.actorId}` : ''} + + {transitions.map((item) => ( + + {item.label}:{statusLabel(item.map, item.from)} → {statusLabel(item.map, item.to)} + + ))} + {detailKeys.length > 0 ?
{JSON.stringify(detail, null, 2)}
: null} +
+ ) +} + +function TraceLabel({ item }: { item: SemiAutoTraceItem }) { + return ( + + + + {item.direction === 'inbound' ? '入站' : '出站'} + + {CHANNEL_LABELS[item.channel] || item.channel} + + {item.status === 'ok' ? '成功' : '失败'} + + {item.httpStatus ? HTTP {item.httpStatus} : null} + {item.durationMs !== null && item.durationMs !== undefined ? ( + {item.durationMs}ms + ) : null} + {formatAdminDateTime(item.createdAt)} + + + {item.action} + + {item.errorMessage ? {item.errorMessage} : null} + + ) +} + +function TracePayload({ + item, + preStyle, + onCopy, + onFilterRequest, +}: { + item: SemiAutoTraceItem + preStyle: CSSProperties + onCopy: (text: string, label: string) => void + onFilterRequest: (requestId: string) => void +}) { + return ( + + + + + + + + {item.requestId ? ( + + ) : null} + requestId:{item.requestId || '-'} + + + ) +} + +function PayloadBlock({ + title, + value, + preStyle, +}: { + title: string + value: unknown + preStyle: CSSProperties +}) { + const text = + value && typeof value === 'object' + ? Object.keys(value as Record).length > 0 + ? JSON.stringify(value, null, 2) + : '' + : String(value || '').trim() + return ( +
+ {title} + {text ?
{text}
: (空)} +
+ ) +} + +function statusLabel(map: Record, value: string | null) { + if (!value) return '—' + return map[value] || value +} diff --git a/apps/frontend/src/pages/admin/AdminSemiAutoTasksPage.tsx b/apps/frontend/src/pages/admin/AdminSemiAutoTasksPage.tsx index fea9e891..91365073 100644 --- a/apps/frontend/src/pages/admin/AdminSemiAutoTasksPage.tsx +++ b/apps/frontend/src/pages/admin/AdminSemiAutoTasksPage.tsx @@ -2,6 +2,7 @@ import { CheckCircleOutlined, ChromeOutlined, CopyOutlined, + HistoryOutlined, KeyOutlined, ReloadOutlined, SendOutlined, @@ -30,6 +31,7 @@ import { useEffect, useMemo, useState } from 'react' import ImageUpload from '@/components/files/ImageUpload' import PageHeader from '@/components/admin/PageHeader' +import SemiAutoTaskHistoryDrawer from '@/components/admin/SemiAutoTaskHistoryDrawer' import PercentTable from '@/components/common/PercentTable' import { cancelAdminSemiAutoTask, @@ -94,6 +96,7 @@ export default function AdminSemiAutoTasksPage() { const [page, setPage] = useState(1) const [pageSize, setPageSize] = useState(20) const [detailTaskId, setDetailTaskId] = useState(null) + const [historyTaskId, setHistoryTaskId] = useState(null) const [completeTask, setCompleteTask] = useState(null) const [completeFiles, setCompleteFiles] = useState([]) const [completeForm] = Form.useForm() @@ -416,6 +419,13 @@ export default function AdminSemiAutoTasksPage() { + {taskNeedsCustomerReauth(task) ? (
+ {options.afterMobile} setSmsCode(event.target.value)} - placeholder="6 位验证码" + placeholder={options.codePlaceholder} maxLength={8} inputMode="numeric" onPressEnter={() => void handleLoginSms()} @@ -913,7 +919,7 @@ export default function CustomerFulfillmentPage() { loading={smsLogging} onClick={() => void handleLoginSms()} > - 登录 + {options.submitText} + {options.footerNote}
) + const huyaLoginForm = renderLoginForm({ + platformLabel: '虎牙', + mobilePlaceholder: '请输入号码', + codePlaceholder: '6 位验证码', + submitText: '登录', + }) + if (loading) { return ( @@ -1018,92 +1032,24 @@ export default function CustomerFulfillmentPage() { selectedTask?.loginStatus === 'expired' || (loginQrVisible && loginMode === 'sms') ? (
- {isWeibo ? ( - setLoginMode(key as 'sms' | 'qr')} - items={[ - { - key: 'sms', - label: '手机号登录', - children: ( -
-
- +86 - setMobile(event.target.value)} - placeholder={`请输入${isHuya ? '虎牙' : '微博'}绑定手机号`} - maxLength={11} - inputMode="numeric" - /> - -
- {isWeibo && smsMfaRequired ? ( -
- 请在安全验证弹窗中完成验证,通过后会继续发送短信验证码。 -
- ) : null} -
- setSmsCode(event.target.value)} - placeholder="请输入短信验证码" - maxLength={8} - prefix={} - onPressEnter={() => void handleLoginSms()} - /> - -
- {isWeibo ? ( - - 如安全验证弹窗未出现,请检查浏览器是否拦截脚本。 - - ) : null} -
- ), - }, - { - key: 'qr', - label: '扫码登录', - children: ( -
-

- {config.loginInstructions || - `点击下方按钮后,使用${isHuya ? '虎牙' : '微博'} App 扫码并确认登录。`} -

- -
- ), - }, - ]} - /> - ) : ( - huyaLoginForm - )} + {isWeibo + ? renderLoginForm({ + platformLabel: '微博', + mobilePlaceholder: '请输入微博绑定手机号', + codePlaceholder: '请输入短信验证码', + submitText: '登录微博', + afterMobile: smsMfaRequired ? ( +
+ 请在安全验证弹窗中完成验证,通过后会继续发送短信验证码。 +
+ ) : null, + footerNote: ( + + 如安全验证弹窗未出现,请检查浏览器是否拦截脚本。 + + ), + }) + : huyaLoginForm}
) : null} @@ -1148,16 +1094,14 @@ export default function CustomerFulfillmentPage() { > 重新获取二维码 - {isWeibo ? null : ( - - )} +
) : null} @@ -1713,6 +1657,31 @@ function CustomerAuthFrame(input: { } function CustomerOrderCard({ task }: { task: CustomerSemiAutoTask }) { + if (task.platform === 'weibo') { + return ( +
+

订单信息

+
+ 订单号 + {task.orderNo} +
+
+ 商品 + + {task.productName || task.skuName} × {task.quantity} + +
+
+ 平台 + {task.platformLabel || '微博'} +
+
+ 状态 + {task.displayStatus.label} +
+
+ ) + } const zone = task.customerServerZone ? /区$/.test(task.customerServerZone) ? task.customerServerZone diff --git a/apps/frontend/src/styles/client.css b/apps/frontend/src/styles/client.css index 43abfd1f..369281e0 100644 --- a/apps/frontend/src/styles/client.css +++ b/apps/frontend/src/styles/client.css @@ -1473,6 +1473,39 @@ background: none; } +/* 微博登录页顶部 KV:与资料页共用 inside-kv.jpg,叠加深色渐变保证标题可读。 */ +.customer-auth-page.is-weibo .customer-auth-hero { + min-height: 134px; + align-items: flex-start; + justify-content: flex-start; + padding: 26px 20px 20px; + background-color: #0b1220; + background-image: + linear-gradient(180deg, rgba(11, 18, 32, 0.12) 0%, rgba(11, 18, 32, 0.72) 72%, #232936 100%), + url('/images/customer/inside-kv.jpg'); + background-repeat: no-repeat; + background-position: center 38%; + background-size: cover; +} + +.customer-auth-page.is-weibo .customer-auth-brand { + width: 100%; + justify-content: flex-start; +} + +.customer-auth-page.is-weibo .customer-auth-brand h1 { + text-align: left; + text-shadow: 0 2px 12px rgba(0, 0, 0, 0.72); +} + +@media (max-width: 640px) { + .customer-auth-page.is-weibo .customer-auth-hero { + min-height: 118px; + padding: 20px 16px 14px; + background-position: center 42%; + } +} + .customer-auth-brand { display: flex; align-items: center; @@ -2148,10 +2181,23 @@ color: #e5e7eb; } +/* 资料页顶部 KV:原图 https://game.gtimg.cn/images/gp/web201908/inside_kv.jpg(本地 1600×510 q82) */ .customer-collect-hero { - padding: 42px 20px 6px; + position: relative; + min-height: clamp(190px, 24vw, 240px); + display: flex; + align-items: flex-end; + justify-content: center; + padding: 0 20px 16px; + overflow: hidden; text-align: center; - background: linear-gradient(180deg, #0f1a2d, #0b1220); + background-color: #0b1220; + background-image: + linear-gradient(180deg, rgba(11, 18, 32, 0) 45%, rgba(11, 18, 32, 0.55) 72%, #0b1220 100%), + url('/images/customer/inside-kv.jpg'); + background-repeat: no-repeat; + background-position: center 38%; + background-size: cover; } .customer-collect-warning { @@ -2160,6 +2206,19 @@ color: #f87171; font-size: 17px; font-weight: 600; + text-shadow: 0 1px 8px rgba(0, 0, 0, 0.8); +} + +@media (max-width: 640px) { + .customer-collect-hero { + min-height: 180px; + padding: 0 16px 14px; + background-position: center 42%; + } + + .customer-collect-warning { + font-size: 15px; + } } .customer-collect-body { @@ -2480,6 +2539,18 @@ overflow-wrap: anywhere; } +.customer-order-card > div strong.customer-order-status { + flex: 0 0 auto; + padding: 3px 12px; + border: 1px solid rgba(96, 165, 250, 0.38); + border-radius: 999px; + color: #dbeafe; + font-size: 13px; + font-weight: 600; + text-align: center; + background: rgba(47, 111, 237, 0.28); +} + .customer-binding-stage { display: flex; flex-direction: column; diff --git a/apps/frontend/tests/customer-fulfillment-weibo-ui.test.ts b/apps/frontend/tests/customer-fulfillment-weibo-ui.test.ts new file mode 100644 index 00000000..b399112e --- /dev/null +++ b/apps/frontend/tests/customer-fulfillment-weibo-ui.test.ts @@ -0,0 +1,58 @@ +import assert from 'node:assert/strict' +import { readFileSync } from 'node:fs' +import { dirname, join } from 'node:path' +import { fileURLToPath } from 'node:url' +import test from 'node:test' + +const source = readFileSync( + join( + dirname(fileURLToPath(import.meta.url)), + '../src/pages/customer-fulfillment/CustomerFulfillmentPage.tsx', + ), + 'utf8', +) +const styles = readFileSync( + join(dirname(fileURLToPath(import.meta.url)), '../src/styles/client.css'), + 'utf8', +) + +test('微博与虎牙共用同一套登录表单结构', () => { + assert.match(source, /const renderLoginForm = \(options: \{/) + assert.ok(source.includes("platformLabel: '虎牙'")) + assert.ok(source.includes("platformLabel: '微博'")) + assert.ok(!source.includes('customer-auth-tabs')) + assert.ok(!source.includes('SafetyCertificateOutlined')) +}) + +test('微博保留两种登录方式与全部原有提示', () => { + assert.ok(source.includes('改用二维码登录')) + assert.ok(source.includes('改用手机号登录')) + assert.ok(source.includes('smsMfaRequired')) + assert.ok(source.includes('如安全验证弹窗未出现')) + assert.ok(source.includes('CustomerPrivacyNote')) + assert.ok(source.includes('温馨提示:未成年人禁止下单')) +}) + +test('二维码切换与虎牙一致:直接切到扫码并发起登录', () => { + assert.ok(source.includes("setLoginMode('qr')")) + assert.ok(source.includes('void handleStartLogin()')) +}) + +test('微博订单卡只展示订单号/商品/平台/状态,不含游戏和角色名称', () => { + const weiboBranch = source.slice( + source.indexOf("if (task.platform === 'weibo')"), + source.indexOf('const zone = task.customerServerZone'), + ) + assert.ok(weiboBranch.includes('订单号')) + assert.ok(weiboBranch.includes('商品')) + assert.ok(weiboBranch.includes('平台')) + assert.ok(weiboBranch.includes('状态')) + assert.ok(!weiboBranch.includes('角色名称')) + assert.ok(!weiboBranch.includes('游戏名称')) +}) + +test('微博顶部使用 inside-kv 背景,虎牙保持纯色', () => { + assert.ok(styles.includes('.customer-auth-page.is-weibo .customer-auth-hero')) + assert.ok(styles.includes("url('/images/customer/inside-kv.jpg')")) + assert.ok(!styles.includes('.customer-auth-page.is-huya .customer-auth-hero')) +}) From f6214e89952667a7b63fd1ebacba371b5f04a18a Mon Sep 17 00:00:00 2001 From: zhaoxing <2558691827@qq.com> Date: Tue, 17 Nov 2026 13:22:32 +0800 Subject: [PATCH 12/15] =?UTF-8?q?fix(semi-auto):=20=E6=8D=A2=E7=BB=91?= =?UTF-8?q?=E5=A4=B1=E8=B4=A5=E8=B5=84=E6=96=99=E4=B8=8D=E4=B8=80=E8=87=B4?= =?UTF-8?q?=E6=97=B6=E5=BC=95=E5=AF=BC=E4=BF=AE=E6=94=B9=E8=B5=84=E6=96=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../CustomerFulfillmentPage.tsx | 90 +++++++++++++++---- ...stomer-fulfillment-rebind-mismatch.test.ts | 30 +++++++ 2 files changed, 105 insertions(+), 15 deletions(-) create mode 100644 apps/frontend/tests/customer-fulfillment-rebind-mismatch.test.ts diff --git a/apps/frontend/src/pages/customer-fulfillment/CustomerFulfillmentPage.tsx b/apps/frontend/src/pages/customer-fulfillment/CustomerFulfillmentPage.tsx index f7e305b9..76215fe5 100644 --- a/apps/frontend/src/pages/customer-fulfillment/CustomerFulfillmentPage.tsx +++ b/apps/frontend/src/pages/customer-fulfillment/CustomerFulfillmentPage.tsx @@ -608,8 +608,23 @@ export default function CustomerFulfillmentPage() { } } + /** 资料不一致时展开资料编辑表单并滚动到可见位置。 */ + function openProfileEditor() { + setProfileEditing(true) + window.setTimeout(() => { + document + .getElementById('customer-profile-form') + ?.scrollIntoView({ behavior: 'smooth', block: 'center' }) + }, 0) + } + async function handleSubmitRebind() { if (!selectedTask) return + if (bindingInfo?.comparison?.verdict === 'mismatch') { + message.warning('当前资料与平台角色不一致,请先修改资料') + openProfileEditor() + return + } setBindingLoading(true) try { const response = await submitCustomerRebind(orderNo, selectedTask.id) @@ -666,7 +681,11 @@ export default function CustomerFulfillmentPage() { ) const bindingResponse = await pollCustomerBinding(orderNo, selectedTask.id) if (bindingResponse.data.binding) setBindingInfo(bindingResponse.data.binding) - message.success('资料已按平台角色同步,请核对后确认绑定') + message.success( + bindingInfo?.rebindUnchanged + ? '资料已按平台角色同步,请点「仍使用原角色」继续' + : '资料已按平台角色同步,请核对后确认绑定', + ) } catch (error) { message.error(error instanceof Error ? error.message : '同步角色资料失败') } finally { @@ -707,6 +726,11 @@ export default function CustomerFulfillmentPage() { /** 换绑被虎牙拒绝时的二次确认:客户可以选择继续使用原绑定角色。 */ function handleAcceptExistingRole() { if (!selectedTask || bindingLoading) return + if (bindingInfo?.comparison?.verdict === 'mismatch') { + message.warning('当前资料与平台原角色不一致,请先修改资料') + openProfileEditor() + return + } const reason = String(bindingInfo?.rebindConfirmMessage || '').trim() modal.confirm({ title: '仍使用原绑定角色?', @@ -746,7 +770,9 @@ export default function CustomerFulfillmentPage() { } catch { // 绑定尚未开始时没有 binding,可忽略。 } - message.success('角色资料已保存') + message.success( + bindingInfo?.rebindUnchanged ? '资料已保存,请点「仍使用原角色」继续' : '角色资料已保存', + ) } catch (error) { message.error(error instanceof Error ? error.message : '保存角色资料失败') } finally { @@ -856,10 +882,16 @@ export default function CustomerFulfillmentPage() { const nextRebindText = bindingInfo?.nextRebindAt ? formatAdminDateTime(bindingInfo.nextRebindAt) : '' - const comparisonMismatch = - selectedTask?.bindingStatus === 'role_ready' && - !rebindUnchanged && - bindingComparison?.verdict === 'mismatch' + const bindingProfileMismatch = + selectedTask?.bindingStatus === 'role_ready' && bindingComparison?.verdict === 'mismatch' + const comparisonMismatch = bindingProfileMismatch && !rebindUnchanged + const canSyncBindingProfile = Boolean( + bindingComparison && + bindingComparison.boundRoleName && + bindingComparison.boundRoleId && + /^\d+$/.test(bindingComparison.boundRoleId) && + bindingComparison.boundZone, + ) const showProfileForm = showBindingStage && profileEditing const bindingCustomerReady = Boolean( bindingComparison?.customerRoleId || bindingComparison?.customerRoleName, @@ -1352,6 +1384,11 @@ export default function CustomerFulfillmentPage() { {!bindingInfo?.rebindConfirmMessage && !nextRebindText ? ( 请核对虎牙弹窗中选中的目标角色后重新提交。 ) : null} + {bindingProfileMismatch ? ( + + 当前资料与平台原角色不一致,无法直接确认;请修改资料为原角色,或等可换绑时间后再试。 + + ) : null} } /> @@ -1413,15 +1450,38 @@ export default function CustomerFulfillmentPage() {
) : rebindUnchanged ? (
- + {bindingProfileMismatch ? ( + + ) : ( + + )} + {bindingProfileMismatch && canSyncBindingProfile ? ( + + ) : null}
) : rebindUnchanged ? (
- {bindingProfileMismatch ? ( - - ) : ( - - )} - {bindingProfileMismatch && canSyncBindingProfile ? ( - - ) : null} +
) : comparisonMismatch ? ( @@ -1464,6 +1475,28 @@ export default function CustomerFulfillmentPage() { 角色不对,重新扫码换绑 + ) : rebindUnchanged ? ( +
+ + +
) : (
-
@@ -1297,7 +1333,7 @@ export default function CustomerFulfillmentPage() { message="绑定二维码已过期" description="请重新获取绑定二维码后再扫码,已填写的订单资料不会丢失。" action={ - } @@ -1313,7 +1349,7 @@ export default function CustomerFulfillmentPage() { bindingInfo?.message || '请刷新二维码后重新扫码,如持续失败请联系客服。' } action={ - } @@ -1592,6 +1628,16 @@ export default function CustomerFulfillmentPage() { 确认绑定 + {bindingComparison?.verdict === 'mismatch' ? ( +
+ + {canSyncBindingProfile ? ( + + ) : null} +
+ ) : null} {bindingComparison?.verdict === 'mismatch' ? (

{bindingComparison?.message || '两侧角色信息不一致,无法确认绑定'} @@ -1609,19 +1655,7 @@ export default function CustomerFulfillmentPage() {

您填写的角色 -
diff --git a/apps/frontend/src/styles/client.css b/apps/frontend/src/styles/client.css index 369281e0..1b341f6d 100644 --- a/apps/frontend/src/styles/client.css +++ b/apps/frontend/src/styles/client.css @@ -2901,6 +2901,10 @@ border-radius: 8px; } +.customer-binding-modal-actions.is-mismatch { + grid-template-columns: repeat(auto-fit, minmax(140px, 1fr)); +} + .customer-binding-modal-error { margin: 0; color: #dc2626; diff --git a/apps/frontend/tests/customer-fulfillment-binding-compare.test.ts b/apps/frontend/tests/customer-fulfillment-binding-compare.test.ts new file mode 100644 index 00000000..a26107fb --- /dev/null +++ b/apps/frontend/tests/customer-fulfillment-binding-compare.test.ts @@ -0,0 +1,64 @@ +import assert from 'node:assert/strict' +import { readFileSync } from 'node:fs' +import { dirname, join } from 'node:path' +import { fileURLToPath } from 'node:url' +import test from 'node:test' + +const root = dirname(fileURLToPath(import.meta.url)) +const source = readFileSync( + join(root, '../src/pages/customer-fulfillment/CustomerFulfillmentPage.tsx'), + 'utf8', +) +const styles = readFileSync(join(root, '../src/styles/client.css'), 'utf8') + +test('扫码识别角色后,资料不一致也打开对比弹窗', () => { + // 自动弹窗 effect 不再因 mismatch 提前 return。 + assert.ok(source.includes('识别到角色(含与资料不一致)都要弹出对比框')) + assert.ok(!source.includes("if (bindingInfo.comparison.verdict === 'mismatch') return")) + // 手动刷新时 mismatch 同样打开弹窗,不再关闭并只弹提示。 + assert.ok(source.includes('资料不一致同样打开对比框')) + assert.ok(!source.includes('平台角色与已填资料不一致,请先同步资料')) +}) + +test('对比弹窗在资料不一致时提供修改资料与同步平台角色入口', () => { + assert.ok(source.includes('修改资料')) + assert.ok(source.includes('同步平台角色')) + assert.ok(source.includes('canSyncBindingProfile')) + assert.ok(source.includes('onClick={openProfileEditor}')) + assert.ok( + source.includes( + "disabled={!bindingCustomerReady || bindingComparison?.verdict === 'mismatch'}", + ), + ) + assert.ok(styles.includes('.customer-binding-modal-actions.is-mismatch')) + assert.ok(styles.includes('repeat(auto-fit, minmax(140px, 1fr))')) +}) + +test('保存资料或同步平台角色后会重新打开对比弹窗', () => { + assert.ok(source.includes('function reopenBindingConfirm(')) + assert.ok(source.includes("if (nextTask.bindingStatus !== 'role_ready') return false")) + assert.ok(source.includes('reopened = reopenBindingConfirm(')) + assert.ok( + source.includes( + 'reopenBindingConfirm(bindingResponse.data.task, bindingResponse.data.binding)', + ), + ) + assert.ok(source.includes('角色资料已保存,请重新核对绑定角色')) +}) + +test('资料不一致时仍保持后端严格比对:确认按钮禁用并显示原因', () => { + assert.ok(source.includes('两侧角色信息不一致,无法确认绑定')) + assert.ok(source.includes('customer-binding-modal-error')) +}) + +test('二维码区提示扫码后会核对平台角色与已填资料', () => { + assert.ok(source.includes('扫码后系统会核对平台角色与已填资料')) +}) + +test('换绑流程刷新二维码必须带 forceRebind,避免直接返回已有角色', () => { + assert.ok(source.includes('function handleRefreshBindingQr()')) + assert.ok(source.includes('handleRefreshBinding(bindingInfo?.rebindRequested === true)')) + // 三处刷新/重新获取入口都不能再固定传 false。 + assert.ok(!source.includes('handleRefreshBinding(false)')) + assert.ok(source.includes('onClick={handleRefreshBindingQr}')) +})