修复(半自动履约): 收口虎牙绑定为单一状态机
This commit is contained in:
@@ -0,0 +1,246 @@
|
||||
-- 177_semi_auto_huya_binding_state.sql
|
||||
--
|
||||
-- 虎牙绑定唯一状态机:
|
||||
-- 1. 持久化账号角色绑定标志、账号侧与目标角色侧换绑窗口;
|
||||
-- 2. 持久化唯一策略器产出的流程阶段、目标匹配和阻塞作用域;
|
||||
-- 3. 修复历史“登录成功但绑定未确认却进入 waiting_operator”的错位状态;
|
||||
-- 4. 清理非 confirmed 任务上过早写入的 bound_at。
|
||||
|
||||
ALTER TABLE semi_auto_tasks
|
||||
ADD COLUMN IF NOT EXISTS is_bind_account BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
ADD COLUMN IF NOT EXISTS is_bind_role BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
ADD COLUMN IF NOT EXISTS account_change_bind_time BIGINT NOT NULL DEFAULT 0,
|
||||
ADD COLUMN IF NOT EXISTS account_change_bind_day INTEGER NOT NULL DEFAULT 0,
|
||||
ADD COLUMN IF NOT EXISTS binding_flow_state TEXT NOT NULL DEFAULT 'binding_query_required',
|
||||
ADD COLUMN IF NOT EXISTS account_role_state TEXT NOT NULL DEFAULT 'unknown',
|
||||
ADD COLUMN IF NOT EXISTS target_role_match TEXT NOT NULL DEFAULT 'unknown',
|
||||
ADD COLUMN IF NOT EXISTS rebind_block_scope TEXT NOT NULL DEFAULT '',
|
||||
ADD COLUMN IF NOT EXISTS rebind_platform_message TEXT NOT NULL DEFAULT '',
|
||||
ADD COLUMN IF NOT EXISTS rebind_requested BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
ADD COLUMN IF NOT EXISTS bind_confirm_state TEXT NOT NULL DEFAULT 'idle',
|
||||
ADD COLUMN IF NOT EXISTS bind_confirm_message TEXT NOT NULL DEFAULT '',
|
||||
ADD COLUMN IF NOT EXISTS binding_qr_issued_at TIMESTAMPTZ,
|
||||
ADD COLUMN IF NOT EXISTS binding_effect_deadline_at TIMESTAMPTZ,
|
||||
ADD COLUMN IF NOT EXISTS pending_role_observed_at TIMESTAMPTZ,
|
||||
ADD COLUMN IF NOT EXISTS confirmed_role_observed_at TIMESTAMPTZ;
|
||||
|
||||
DO $$
|
||||
BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM pg_constraint
|
||||
WHERE conname = 'chk_semi_auto_tasks_binding_flow_state'
|
||||
) THEN
|
||||
ALTER TABLE semi_auto_tasks
|
||||
ADD CONSTRAINT chk_semi_auto_tasks_binding_flow_state
|
||||
CHECK (
|
||||
binding_flow_state IN (
|
||||
'binding_query_required',
|
||||
'initial_bind_required',
|
||||
'first_bind_qr_pending',
|
||||
'first_bind_role_ready',
|
||||
'first_bind_role_mismatch',
|
||||
'first_bind_failed',
|
||||
'current_role_confirmable',
|
||||
'rebind_required',
|
||||
'rebind_qr_pending',
|
||||
'rebind_role_ready',
|
||||
'rebind_effect_pending',
|
||||
'rebind_blocked_account',
|
||||
'rebind_blocked_target_role',
|
||||
'rebind_rejected',
|
||||
'rebind_effect_failed',
|
||||
'confirmed',
|
||||
'manual_review',
|
||||
'expired'
|
||||
)
|
||||
);
|
||||
END IF;
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM pg_constraint
|
||||
WHERE conname = 'chk_semi_auto_tasks_account_role_state'
|
||||
) THEN
|
||||
ALTER TABLE semi_auto_tasks
|
||||
ADD CONSTRAINT chk_semi_auto_tasks_account_role_state
|
||||
CHECK (account_role_state IN ('unknown', 'none', 'bound', 'inconsistent'));
|
||||
END IF;
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM pg_constraint
|
||||
WHERE conname = 'chk_semi_auto_tasks_target_role_match'
|
||||
) THEN
|
||||
ALTER TABLE semi_auto_tasks
|
||||
ADD CONSTRAINT chk_semi_auto_tasks_target_role_match
|
||||
CHECK (target_role_match IN ('unknown', 'match', 'mismatch'));
|
||||
END IF;
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM pg_constraint
|
||||
WHERE conname = 'chk_semi_auto_tasks_rebind_block_scope'
|
||||
) THEN
|
||||
ALTER TABLE semi_auto_tasks
|
||||
ADD CONSTRAINT chk_semi_auto_tasks_rebind_block_scope
|
||||
CHECK (rebind_block_scope IN ('', 'account', 'target_role', 'platform'));
|
||||
END IF;
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM pg_constraint
|
||||
WHERE conname = 'chk_semi_auto_tasks_bind_confirm_state'
|
||||
) THEN
|
||||
ALTER TABLE semi_auto_tasks
|
||||
ADD CONSTRAINT chk_semi_auto_tasks_bind_confirm_state
|
||||
CHECK (bind_confirm_state IN ('idle', 'submitting', 'accepted', 'rejected'));
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_semi_auto_tasks_binding_flow
|
||||
ON semi_auto_tasks (platform, binding_flow_state, updated_at DESC, id DESC);
|
||||
|
||||
UPDATE semi_auto_tasks
|
||||
SET is_bind_account =
|
||||
platform = 'huya'
|
||||
AND bind_game_role <> ''
|
||||
AND binding_status IN ('role_ready', 'confirmed'),
|
||||
is_bind_role =
|
||||
platform = 'huya'
|
||||
AND bind_game_role <> ''
|
||||
AND binding_status IN ('role_ready', 'confirmed'),
|
||||
account_role_state =
|
||||
CASE
|
||||
WHEN platform <> 'huya' THEN 'unknown'
|
||||
WHEN bind_game_role <> ''
|
||||
AND binding_status IN ('role_ready', 'confirmed') THEN 'bound'
|
||||
WHEN binding_started_at IS NULL
|
||||
AND binding_status = 'not_started'
|
||||
AND bind_game_role = ''
|
||||
AND pending_bind_game_role = '' THEN 'unknown'
|
||||
WHEN bind_game_role = '' AND pending_bind_game_role = '' THEN 'none'
|
||||
ELSE 'none'
|
||||
END,
|
||||
rebind_requested =
|
||||
CASE
|
||||
WHEN bind_game_role <> '' AND pending_bind_game_role <> '' THEN TRUE
|
||||
ELSE rebind_requested
|
||||
END,
|
||||
binding_flow_state =
|
||||
CASE
|
||||
WHEN platform <> 'huya' THEN 'binding_query_required'
|
||||
WHEN binding_status = 'confirmed' AND bind_game_role <> '' THEN 'confirmed'
|
||||
WHEN binding_status = 'confirmed' THEN 'manual_review'
|
||||
WHEN binding_status = 'expired' THEN 'expired'
|
||||
WHEN pending_bind_game_role <> '' AND bind_game_role <> '' THEN 'rebind_role_ready'
|
||||
WHEN pending_bind_game_role <> '' THEN 'first_bind_role_ready'
|
||||
WHEN binding_status IN ('qr_pending', 'scanned')
|
||||
AND bind_game_role <> '' THEN 'rebind_qr_pending'
|
||||
WHEN binding_status IN ('qr_pending', 'scanned') THEN 'first_bind_qr_pending'
|
||||
WHEN binding_status = 'failed' THEN 'manual_review'
|
||||
WHEN bind_game_role <> '' THEN 'manual_review'
|
||||
WHEN binding_status = 'role_ready' THEN 'manual_review'
|
||||
ELSE 'binding_query_required'
|
||||
END,
|
||||
pending_role_observed_at =
|
||||
CASE
|
||||
WHEN pending_bind_game_role <> '' THEN COALESCE(pending_role_observed_at, updated_at)
|
||||
ELSE pending_role_observed_at
|
||||
END,
|
||||
confirmed_role_observed_at =
|
||||
CASE
|
||||
WHEN binding_status = 'confirmed' THEN COALESCE(confirmed_role_observed_at, updated_at)
|
||||
ELSE confirmed_role_observed_at
|
||||
END
|
||||
WHERE platform = 'huya';
|
||||
|
||||
WITH repaired AS (
|
||||
SELECT id, login_status, binding_status, execution_status
|
||||
FROM semi_auto_tasks
|
||||
WHERE platform = 'huya'
|
||||
AND execution_status = 'waiting_operator'
|
||||
AND binding_flow_state <> 'confirmed'
|
||||
)
|
||||
INSERT INTO semi_auto_task_events (
|
||||
task_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
|
||||
)
|
||||
SELECT
|
||||
id,
|
||||
'huya_binding_state_repaired',
|
||||
'system',
|
||||
'',
|
||||
login_status,
|
||||
login_status,
|
||||
binding_status,
|
||||
binding_status,
|
||||
execution_status,
|
||||
'waiting_customer',
|
||||
'{"reason":"unconfirmed_binding_cannot_wait_operator"}'::jsonb,
|
||||
NOW()
|
||||
FROM repaired;
|
||||
|
||||
UPDATE semi_auto_tasks task
|
||||
SET execution_status = 'waiting_customer',
|
||||
updated_at = NOW()
|
||||
WHERE task.platform = 'huya'
|
||||
AND task.execution_status = 'waiting_operator'
|
||||
AND task.binding_flow_state <> 'confirmed';
|
||||
|
||||
WITH repaired AS (
|
||||
SELECT id, binding_status, bound_at
|
||||
FROM semi_auto_tasks
|
||||
WHERE platform = 'huya'
|
||||
AND bound_at IS NOT NULL
|
||||
AND binding_flow_state <> 'confirmed'
|
||||
)
|
||||
INSERT INTO semi_auto_task_events (
|
||||
task_id, event_type, actor_type, actor_id,
|
||||
from_binding_status, to_binding_status,
|
||||
detail_json, created_at
|
||||
)
|
||||
SELECT
|
||||
id,
|
||||
'huya_binding_bound_at_repaired',
|
||||
'system',
|
||||
'',
|
||||
binding_status,
|
||||
binding_status,
|
||||
jsonb_build_object('reason', 'bound_at_requires_confirmed_binding'),
|
||||
NOW()
|
||||
FROM repaired;
|
||||
|
||||
UPDATE semi_auto_tasks
|
||||
SET bound_at = NULL,
|
||||
updated_at = NOW()
|
||||
WHERE platform = 'huya'
|
||||
AND bound_at IS NOT NULL
|
||||
AND binding_flow_state <> 'confirmed';
|
||||
|
||||
COMMENT ON COLUMN semi_auto_tasks.is_bind_account IS
|
||||
'虎牙原始 isBindAccount 标志;只由 Connector 事实映射写入';
|
||||
COMMENT ON COLUMN semi_auto_tasks.is_bind_role IS
|
||||
'虎牙原始 isBindRole 标志;只由 Connector 事实映射写入';
|
||||
COMMENT ON COLUMN semi_auto_tasks.account_change_bind_time IS
|
||||
'当前虎牙账号角色侧的原始 changeBindTime';
|
||||
COMMENT ON COLUMN semi_auto_tasks.account_change_bind_day IS
|
||||
'当前虎牙账号角色侧的原始 changeBindDay';
|
||||
COMMENT ON COLUMN semi_auto_tasks.binding_flow_state IS
|
||||
'虎牙绑定唯一策略器产出的流程阶段';
|
||||
COMMENT ON COLUMN semi_auto_tasks.account_role_state IS
|
||||
'账号角色事实:unknown / none / bound / inconsistent';
|
||||
COMMENT ON COLUMN semi_auto_tasks.target_role_match IS
|
||||
'目标客户资料与当前或待确认角色的唯一比对结果';
|
||||
COMMENT ON COLUMN semi_auto_tasks.rebind_block_scope IS
|
||||
'换绑阻塞作用域:账号 / 目标角色 / 平台其他原因';
|
||||
COMMENT ON COLUMN semi_auto_tasks.rebind_platform_message IS
|
||||
'虎牙换绑拒绝或冷却的原始原因';
|
||||
COMMENT ON COLUMN semi_auto_tasks.rebind_requested IS
|
||||
'当前绑定会话是否由客户明确发起换绑';
|
||||
COMMENT ON COLUMN semi_auto_tasks.bind_confirm_state IS
|
||||
'唯一绑定确认请求状态:idle / submitting / accepted / rejected';
|
||||
COMMENT ON COLUMN semi_auto_tasks.bind_confirm_message IS
|
||||
'虎牙确认绑定接口返回的原始原因';
|
||||
COMMENT ON COLUMN semi_auto_tasks.binding_qr_issued_at IS
|
||||
'当前绑定会话最近一次实际生成二维码的时间';
|
||||
COMMENT ON COLUMN semi_auto_tasks.binding_effect_deadline_at IS
|
||||
'平台受理确认后等待目标角色生效的截止时间';
|
||||
COMMENT ON COLUMN semi_auto_tasks.pending_role_observed_at IS
|
||||
'最近一次观察到本次 pending 角色的时间';
|
||||
COMMENT ON COLUMN semi_auto_tasks.confirmed_role_observed_at IS
|
||||
'最近一次确认 current 角色已生效的时间';
|
||||
@@ -144,7 +144,9 @@ router.post(
|
||||
createRouteHandler(
|
||||
(req) =>
|
||||
confirmPublicBinding(req.params.orderNo, req.params.taskId, {
|
||||
acceptExistingRole: req.body?.acceptExistingRole === true,
|
||||
expectedRoleName: req.body?.expectedRoleName,
|
||||
expectedRoleToken: req.body?.expectedRoleToken,
|
||||
expectedRoleChannel: req.body?.expectedRoleChannel,
|
||||
}),
|
||||
{
|
||||
successMessage: '绑定已确认',
|
||||
|
||||
@@ -0,0 +1,265 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import {
|
||||
classifyHuyaRebindFailure,
|
||||
resolveHuyaBindingDecision,
|
||||
resolveHuyaRoleRebindAvailability,
|
||||
type HuyaBindingDecisionInput,
|
||||
type HuyaRoleSnapshot,
|
||||
} from './huya-binding-policy.js'
|
||||
|
||||
const DAY_MS = 24 * 60 * 60 * 1000
|
||||
const NOW = Date.UTC(2026, 10, 19, 4, 0, 0)
|
||||
const TARGET = {
|
||||
roleName: '最终角色',
|
||||
roleId: '1192083858',
|
||||
serverZone: '安卓V区',
|
||||
}
|
||||
|
||||
function role(input: Partial<HuyaRoleSnapshot> = {}): HuyaRoleSnapshot {
|
||||
return {
|
||||
isBindAccount: true,
|
||||
isBindRole: true,
|
||||
roleName: '旧角色',
|
||||
roleToken: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
|
||||
channel: '安卓(android) · 微信',
|
||||
changeBindTime: 0,
|
||||
changeBindDay: 0,
|
||||
...input,
|
||||
}
|
||||
}
|
||||
|
||||
function input(values: Partial<HuyaBindingDecisionInput> = {}): HuyaBindingDecisionInput {
|
||||
return {
|
||||
customer: TARGET,
|
||||
current: null,
|
||||
pending: null,
|
||||
accountInspected: true,
|
||||
bindingStatus: 'not_started',
|
||||
bindConfirmState: 'idle',
|
||||
nowMs: NOW,
|
||||
...values,
|
||||
}
|
||||
}
|
||||
|
||||
test('账号没有角色时进入首次绑定,不能直接确认', () => {
|
||||
const decision = resolveHuyaBindingDecision(input())
|
||||
assert.equal(decision.accountRoleState, 'none')
|
||||
assert.equal(decision.flowState, 'initial_bind_required')
|
||||
assert.equal(decision.primaryAction, 'start_first_binding')
|
||||
assert.equal(decision.canConfirmBinding, false)
|
||||
})
|
||||
|
||||
test('未查询账号角色时只能先查询,不能把空值当成已确认无角色', () => {
|
||||
const decision = resolveHuyaBindingDecision(input({ accountInspected: false }))
|
||||
assert.equal(decision.accountRoleState, 'unknown')
|
||||
assert.equal(decision.flowState, 'binding_query_required')
|
||||
assert.equal(decision.primaryAction, 'query_binding')
|
||||
assert.equal(decision.canCompleteTask, false)
|
||||
})
|
||||
|
||||
test('首次扫码识别目标角色后允许客户确认绑定', () => {
|
||||
const decision = resolveHuyaBindingDecision(
|
||||
input({
|
||||
pending: role({
|
||||
isBindAccount: false,
|
||||
isBindRole: false,
|
||||
roleName: TARGET.roleName,
|
||||
roleToken: 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb',
|
||||
}),
|
||||
bindingStatus: 'role_ready',
|
||||
}),
|
||||
)
|
||||
assert.equal(decision.flowState, 'first_bind_role_ready')
|
||||
assert.equal(decision.primaryAction, 'confirm_first_binding')
|
||||
assert.equal(decision.canConfirmBinding, true)
|
||||
})
|
||||
|
||||
test('已有角色且就是目标角色时直接确认当前角色', () => {
|
||||
const decision = resolveHuyaBindingDecision(
|
||||
input({
|
||||
current: role({ roleName: TARGET.roleName }),
|
||||
bindingStatus: 'role_ready',
|
||||
}),
|
||||
)
|
||||
assert.equal(decision.accountRoleState, 'bound')
|
||||
assert.equal(decision.targetRoleMatch, 'match')
|
||||
assert.equal(decision.flowState, 'current_role_confirmable')
|
||||
assert.equal(decision.primaryAction, 'confirm_current_role')
|
||||
})
|
||||
|
||||
test('平台原始状态为 confirmed 时仍以唯一决策器的目标匹配结果为准', () => {
|
||||
const matched = resolveHuyaBindingDecision(
|
||||
input({
|
||||
current: role({ roleName: TARGET.roleName }),
|
||||
bindingStatus: 'confirmed',
|
||||
}),
|
||||
)
|
||||
assert.equal(matched.flowState, 'confirmed')
|
||||
assert.equal(matched.canCompleteTask, true)
|
||||
|
||||
const mismatched = resolveHuyaBindingDecision(
|
||||
input({
|
||||
current: role(),
|
||||
bindingStatus: 'confirmed',
|
||||
}),
|
||||
)
|
||||
assert.equal(mismatched.flowState, 'rebind_required')
|
||||
assert.equal(mismatched.canCompleteTask, false)
|
||||
})
|
||||
|
||||
test('已有角色但不是目标角色时要求换绑', () => {
|
||||
const decision = resolveHuyaBindingDecision(
|
||||
input({
|
||||
current: role(),
|
||||
bindingStatus: 'role_ready',
|
||||
}),
|
||||
)
|
||||
assert.equal(decision.targetRoleMatch, 'mismatch')
|
||||
assert.equal(decision.flowState, 'rebind_required')
|
||||
assert.equal(decision.primaryAction, 'start_rebind')
|
||||
})
|
||||
|
||||
test('换绑扫码识别目标角色后允许客户确认换绑', () => {
|
||||
const decision = resolveHuyaBindingDecision(
|
||||
input({
|
||||
current: role(),
|
||||
pending: role({
|
||||
isBindAccount: false,
|
||||
isBindRole: false,
|
||||
roleName: TARGET.roleName,
|
||||
roleToken: 'cccccccccccccccccccccccccccccccccccccccc',
|
||||
}),
|
||||
bindingStatus: 'role_ready',
|
||||
rebindRequested: true,
|
||||
}),
|
||||
)
|
||||
assert.equal(decision.flowState, 'rebind_role_ready')
|
||||
assert.equal(decision.primaryAction, 'confirm_rebind')
|
||||
assert.equal(decision.canConfirmBinding, true)
|
||||
})
|
||||
|
||||
test('账号侧 7 天限制在生成二维码前拦截换绑', () => {
|
||||
const decision = resolveHuyaBindingDecision(
|
||||
input({
|
||||
current: role({
|
||||
changeBindDay: 7,
|
||||
changeBindTime: Math.floor((NOW + 3 * DAY_MS) / 1000),
|
||||
}),
|
||||
bindingStatus: 'role_ready',
|
||||
}),
|
||||
)
|
||||
assert.equal(decision.flowState, 'rebind_blocked_account')
|
||||
assert.equal(decision.rebindBlockScope, 'account')
|
||||
assert.equal(decision.canGenerateBindingQr, false)
|
||||
assert.equal(decision.primaryAction, 'wait_account_rebind')
|
||||
})
|
||||
|
||||
test('目标角色侧 7 天限制单独识别,不与账号限制混用', () => {
|
||||
const decision = resolveHuyaBindingDecision(
|
||||
input({
|
||||
current: role(),
|
||||
pending: role({
|
||||
isBindAccount: false,
|
||||
isBindRole: false,
|
||||
roleName: TARGET.roleName,
|
||||
roleToken: 'dddddddddddddddddddddddddddddddddddddddd',
|
||||
changeBindDay: 7,
|
||||
changeBindTime: Math.floor((NOW + 4 * DAY_MS) / 1000),
|
||||
}),
|
||||
bindingStatus: 'role_ready',
|
||||
rebindRequested: true,
|
||||
}),
|
||||
)
|
||||
assert.equal(decision.flowState, 'rebind_blocked_target_role')
|
||||
assert.equal(decision.rebindBlockScope, 'target_role')
|
||||
assert.equal(decision.primaryAction, 'wait_target_role_rebind')
|
||||
})
|
||||
|
||||
test('换绑确认被平台拒绝时按返回原因归类账号或目标角色限制', () => {
|
||||
const accountDecision = resolveHuyaBindingDecision(
|
||||
input({
|
||||
current: role(),
|
||||
bindingStatus: 'failed',
|
||||
bindConfirmState: 'rejected',
|
||||
bindConfirmMessage: '当前角色暂不能换绑,剩余 3 天',
|
||||
}),
|
||||
)
|
||||
assert.equal(accountDecision.flowState, 'rebind_blocked_account')
|
||||
assert.equal(accountDecision.rebindBlockScope, 'account')
|
||||
|
||||
const targetDecision = resolveHuyaBindingDecision(
|
||||
input({
|
||||
current: role(),
|
||||
pending: role({
|
||||
isBindAccount: false,
|
||||
isBindRole: false,
|
||||
roleName: TARGET.roleName,
|
||||
}),
|
||||
bindingStatus: 'failed',
|
||||
bindConfirmState: 'rejected',
|
||||
bindConfirmMessage: '待绑定游戏账号未到换绑时间',
|
||||
}),
|
||||
)
|
||||
assert.equal(targetDecision.flowState, 'rebind_blocked_target_role')
|
||||
assert.equal(targetDecision.rebindBlockScope, 'target_role')
|
||||
})
|
||||
|
||||
test('平台已受理但角色未生效时进入等待态,超时后允许重新换绑', () => {
|
||||
const pending = role({
|
||||
isBindAccount: false,
|
||||
isBindRole: false,
|
||||
roleName: TARGET.roleName,
|
||||
})
|
||||
const waiting = resolveHuyaBindingDecision(
|
||||
input({
|
||||
current: role(),
|
||||
pending,
|
||||
bindingStatus: 'scanned',
|
||||
rebindRequested: true,
|
||||
bindConfirmState: 'accepted',
|
||||
bindingEffectDeadlineAt: new Date(NOW + 60_000).toISOString(),
|
||||
}),
|
||||
)
|
||||
assert.equal(waiting.flowState, 'rebind_effect_pending')
|
||||
assert.equal(waiting.primaryAction, 'refresh_binding_status')
|
||||
|
||||
const failed = resolveHuyaBindingDecision(
|
||||
input({
|
||||
current: role(),
|
||||
bindingStatus: 'scanned',
|
||||
rebindRequested: true,
|
||||
bindConfirmState: 'accepted',
|
||||
bindingEffectDeadlineAt: new Date(NOW - 60_000).toISOString(),
|
||||
}),
|
||||
)
|
||||
assert.equal(failed.flowState, 'rebind_effect_failed')
|
||||
assert.equal(failed.primaryAction, 'start_rebind')
|
||||
})
|
||||
|
||||
test('绑定标志不一致时统一进入客服人工核实', () => {
|
||||
const decision = resolveHuyaBindingDecision(
|
||||
input({
|
||||
current: role({ isBindRole: false }),
|
||||
bindingStatus: 'role_ready',
|
||||
}),
|
||||
)
|
||||
assert.equal(decision.accountRoleState, 'inconsistent')
|
||||
assert.equal(decision.flowState, 'manual_review')
|
||||
assert.equal(decision.primaryAction, 'contact_support')
|
||||
})
|
||||
|
||||
test('冷却计算和目标匹配器保持唯一实现', () => {
|
||||
const availability = resolveHuyaRoleRebindAvailability(
|
||||
role({
|
||||
changeBindDay: 7,
|
||||
changeBindTime: Math.floor((NOW - 2 * DAY_MS) / 1000),
|
||||
}),
|
||||
NOW,
|
||||
)
|
||||
assert.equal(availability.blocked, true)
|
||||
assert.equal(availability.remainingDays, 4)
|
||||
assert.equal(classifyHuyaRebindFailure('该游戏角色仍在换绑冷却期'), 'target_role')
|
||||
assert.equal(classifyHuyaRebindFailure('当前绑定账号暂不可换绑'), 'account')
|
||||
})
|
||||
@@ -0,0 +1,710 @@
|
||||
import {
|
||||
compareBindingIdentity,
|
||||
resolveServerZone,
|
||||
type BindingIdentityComparison,
|
||||
} from '../account-binding/binding-identity.js'
|
||||
import { getAccountBindingPolicy } from '../account-binding/platform-policy.js'
|
||||
import { isHuyaRoleToken, isNumericBindingRoleId } from './binding-role-id.js'
|
||||
|
||||
const DAY_MS = 24 * 60 * 60 * 1000
|
||||
const DEFAULT_REBIND_WINDOW_DAYS = 7
|
||||
|
||||
export type HuyaRoleSnapshot = {
|
||||
isBindAccount: boolean
|
||||
isBindRole: boolean
|
||||
roleName: string
|
||||
roleToken: string
|
||||
channel: string
|
||||
changeBindTime: number
|
||||
changeBindDay: number
|
||||
}
|
||||
|
||||
export type HuyaCustomerRoleSnapshot = {
|
||||
roleName: string
|
||||
roleId: string
|
||||
serverZone: string
|
||||
}
|
||||
|
||||
export type HuyaAccountRoleState = 'unknown' | 'none' | 'bound' | 'inconsistent'
|
||||
export type HuyaTargetRoleMatch = 'unknown' | 'match' | 'mismatch'
|
||||
export type HuyaRebindBlockScope = '' | 'account' | 'target_role' | 'platform'
|
||||
|
||||
export type HuyaBindingFlowState =
|
||||
| 'binding_query_required'
|
||||
| 'initial_bind_required'
|
||||
| 'first_bind_qr_pending'
|
||||
| 'first_bind_role_ready'
|
||||
| 'first_bind_role_mismatch'
|
||||
| 'first_bind_failed'
|
||||
| 'current_role_confirmable'
|
||||
| 'rebind_required'
|
||||
| 'rebind_qr_pending'
|
||||
| 'rebind_role_ready'
|
||||
| 'rebind_effect_pending'
|
||||
| 'rebind_blocked_account'
|
||||
| 'rebind_blocked_target_role'
|
||||
| 'rebind_rejected'
|
||||
| 'rebind_effect_failed'
|
||||
| 'confirmed'
|
||||
| 'manual_review'
|
||||
| 'expired'
|
||||
|
||||
export type HuyaBindingAction =
|
||||
| 'query_binding'
|
||||
| 'start_first_binding'
|
||||
| 'refresh_first_binding_qr'
|
||||
| 'confirm_first_binding'
|
||||
| 'confirm_current_role'
|
||||
| 'start_rebind'
|
||||
| 'refresh_rebind_qr'
|
||||
| 'confirm_rebind'
|
||||
| 'refresh_binding_status'
|
||||
| 'wait_account_rebind'
|
||||
| 'wait_target_role_rebind'
|
||||
| 'relogin'
|
||||
| 'edit_profile'
|
||||
| 'contact_support'
|
||||
| 'none'
|
||||
|
||||
export type HuyaBindingComparison = {
|
||||
verdict: 'match' | 'mismatch' | 'unknown'
|
||||
customerRoleName: string
|
||||
customerRoleId: string
|
||||
customerZone: string
|
||||
boundRoleName: string
|
||||
boundRoleId: string
|
||||
boundRoleIdKind: 'game_role_uid' | 'huya_role_token' | 'missing'
|
||||
boundZone: string
|
||||
verificationBasis: 'role_name_zone' | 'platform_numeric_uid' | 'manual'
|
||||
message: string
|
||||
missing: string[]
|
||||
mismatched: string[]
|
||||
}
|
||||
|
||||
export type HuyaRebindAvailability = {
|
||||
blocked: boolean
|
||||
availableAt: string
|
||||
remainingDays: number
|
||||
windowDays: number
|
||||
}
|
||||
|
||||
export type HuyaBindingDecisionInput = {
|
||||
customer: HuyaCustomerRoleSnapshot
|
||||
current: HuyaRoleSnapshot | null
|
||||
pending: HuyaRoleSnapshot | null
|
||||
accountInspected: boolean
|
||||
bindingStatus:
|
||||
| 'not_started'
|
||||
| 'qr_pending'
|
||||
| 'scanned'
|
||||
| 'role_ready'
|
||||
| 'confirmed'
|
||||
| 'failed'
|
||||
| 'expired'
|
||||
rebindRequested?: boolean
|
||||
bindConfirmState?: 'idle' | 'submitting' | 'accepted' | 'rejected'
|
||||
bindConfirmMessage?: string
|
||||
rebindConfirmMessage?: string
|
||||
bindingEffectDeadlineAt?: string
|
||||
hasBindingQr?: boolean
|
||||
nowMs?: number
|
||||
}
|
||||
|
||||
export type HuyaBindingDecision = {
|
||||
accountRoleState: HuyaAccountRoleState
|
||||
targetRoleMatch: HuyaTargetRoleMatch
|
||||
flowState: HuyaBindingFlowState
|
||||
primaryAction: HuyaBindingAction
|
||||
allowedActions: HuyaBindingAction[]
|
||||
rebindBlockScope: HuyaRebindBlockScope
|
||||
accountRebindAvailableAt: string
|
||||
targetRoleRebindAvailableAt: string
|
||||
canGenerateBindingQr: boolean
|
||||
canConfirmBinding: boolean
|
||||
canCompleteTask: boolean
|
||||
requiresCustomerConfirmation: boolean
|
||||
requiresSupport: boolean
|
||||
comparison: HuyaBindingComparison
|
||||
currentRoleComparison: HuyaBindingComparison | null
|
||||
pendingRoleComparison: HuyaBindingComparison | null
|
||||
message: string
|
||||
}
|
||||
|
||||
function readString(value: unknown): string {
|
||||
return String(value ?? '').trim()
|
||||
}
|
||||
|
||||
function iso(value: number): string {
|
||||
return value > 0 ? new Date(value).toISOString() : ''
|
||||
}
|
||||
|
||||
function comparisonBase(customer: HuyaCustomerRoleSnapshot, role: HuyaRoleSnapshot | null) {
|
||||
const customerRoleName = readString(customer.roleName)
|
||||
const customerRoleId = readString(customer.roleId)
|
||||
const customerZone = resolveServerZone(customer.serverZone)
|
||||
const roleName = readString(role?.roleName)
|
||||
const roleToken = readString(role?.roleToken)
|
||||
const platformRoleUid = isNumericBindingRoleId(roleToken) ? roleToken : ''
|
||||
const boundZone = resolveServerZone(role?.channel)
|
||||
return {
|
||||
customerRoleName,
|
||||
customerRoleId,
|
||||
customerZone,
|
||||
boundRoleName: roleName,
|
||||
boundRoleId: platformRoleUid || roleToken,
|
||||
boundRoleIdKind: platformRoleUid
|
||||
? ('game_role_uid' as const)
|
||||
: isHuyaRoleToken(roleToken)
|
||||
? ('huya_role_token' as const)
|
||||
: ('missing' as const),
|
||||
boundZone,
|
||||
verificationBasis: platformRoleUid
|
||||
? ('platform_numeric_uid' as const)
|
||||
: ('role_name_zone' as const),
|
||||
platformRoleUid,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 虎牙角色比对的唯一入口。
|
||||
*
|
||||
* 当前虎牙只稳定返回角色名、区服和可选的数值平台角色 UID。
|
||||
* 40 位加密 role token 只用于判断平台前后角色是否变化,不参与客户资料比对。
|
||||
*/
|
||||
export function compareHuyaBindingRole(
|
||||
customer: HuyaCustomerRoleSnapshot,
|
||||
role: HuyaRoleSnapshot | null,
|
||||
): HuyaBindingComparison {
|
||||
const base = comparisonBase(customer, role)
|
||||
const policy = getAccountBindingPolicy('huya')
|
||||
const comparison = compareBindingIdentity({
|
||||
requiredFields: base.platformRoleUid
|
||||
? [...policy.requiredFields, 'roleId']
|
||||
: policy.requiredFields,
|
||||
customer: {
|
||||
roleName: base.customerRoleName,
|
||||
roleId: base.customerRoleId,
|
||||
serverZone: base.customerZone,
|
||||
},
|
||||
platform: {
|
||||
roleName: base.boundRoleName,
|
||||
roleId: base.platformRoleUid,
|
||||
serverZone: base.boundZone,
|
||||
},
|
||||
})
|
||||
const missing = comparison.missing.map((field) => bindingFieldLabel(field, base))
|
||||
const mismatched = comparison.mismatched.map((field) => bindingFieldLabel(field, base))
|
||||
if (comparison.verdict === 'unknown') {
|
||||
return {
|
||||
...base,
|
||||
verdict: 'unknown',
|
||||
message: `缺少${missing.join('、')},无法核对绑定角色,请联系客服`,
|
||||
missing,
|
||||
mismatched,
|
||||
}
|
||||
}
|
||||
if (comparison.verdict === 'mismatch') {
|
||||
const message = comparison.mismatched.includes('roleId')
|
||||
? '两侧游戏角色 UID 不一致,无法提交平台绑定'
|
||||
: comparison.mismatched.includes('roleName')
|
||||
? '两侧角色名称不一致,无法提交平台绑定'
|
||||
: '两侧区服不一致,无法提交平台绑定'
|
||||
return { ...base, verdict: 'mismatch', message, missing, mismatched }
|
||||
}
|
||||
return {
|
||||
...base,
|
||||
verdict: 'match',
|
||||
message: base.platformRoleUid
|
||||
? '两侧区服、角色名称、平台角色 UID 一致,可提交平台绑定'
|
||||
: '角色名称与区服一致,请确认绑定本次待确认角色',
|
||||
missing,
|
||||
mismatched,
|
||||
}
|
||||
}
|
||||
|
||||
function bindingFieldLabel(
|
||||
value: keyof BindingIdentityComparison['customer'],
|
||||
base: ReturnType<typeof comparisonBase>,
|
||||
) {
|
||||
if (value === 'roleName') {
|
||||
return base.customerRoleName ? '平台角色名' : '客户角色名'
|
||||
}
|
||||
if (value === 'roleId') return '平台游戏角色 UID'
|
||||
if (value === 'serverZone') {
|
||||
return base.customerZone ? '平台区服' : '客户区服'
|
||||
}
|
||||
return '登录渠道'
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算单侧角色 7 天换绑窗口。账号当前角色与本次目标角色必须分别计算。
|
||||
*/
|
||||
export function resolveHuyaRoleRebindAvailability(
|
||||
role: HuyaRoleSnapshot | null,
|
||||
nowMs = Date.now(),
|
||||
): HuyaRebindAvailability {
|
||||
if (!role) {
|
||||
return { blocked: false, availableAt: '', remainingDays: 0, windowDays: 0 }
|
||||
}
|
||||
const configuredDays = Number(role.changeBindDay || 0)
|
||||
const hasPlatformWindow =
|
||||
Number.isFinite(configuredDays) && configuredDays > 0 && configuredDays <= 30
|
||||
const windowDays = hasPlatformWindow ? Math.round(configuredDays) : DEFAULT_REBIND_WINDOW_DAYS
|
||||
const changeBindTime = Number(role.changeBindTime || 0)
|
||||
if (Number.isFinite(changeBindTime) && changeBindTime > 0) {
|
||||
const changedAtMs = changeBindTime > 1e12 ? changeBindTime : changeBindTime * 1000
|
||||
const offsetDays = hasPlatformWindow ? Math.max(windowDays - 1, 0) : DEFAULT_REBIND_WINDOW_DAYS
|
||||
const availableAtMs = changedAtMs + offsetDays * DAY_MS
|
||||
if (availableAtMs > nowMs) {
|
||||
return {
|
||||
blocked: true,
|
||||
availableAt: iso(availableAtMs),
|
||||
remainingDays: Math.ceil((availableAtMs - nowMs) / DAY_MS),
|
||||
windowDays,
|
||||
}
|
||||
}
|
||||
}
|
||||
if (hasPlatformWindow) {
|
||||
return {
|
||||
blocked: false,
|
||||
availableAt: '',
|
||||
remainingDays: 0,
|
||||
windowDays,
|
||||
}
|
||||
}
|
||||
return { blocked: false, availableAt: '', remainingDays: 0, windowDays: 0 }
|
||||
}
|
||||
|
||||
/**
|
||||
* 旧 Connector 响应到统一冷却计算的兼容适配,不包含第二套判断。
|
||||
*/
|
||||
export function resolveHuyaRebindCooldownResponse(
|
||||
response:
|
||||
| {
|
||||
status?: number
|
||||
changeBindDay?: number
|
||||
accountData?: { changeBindTime?: number } | null
|
||||
}
|
||||
| null
|
||||
| undefined,
|
||||
nowMs = Date.now(),
|
||||
) {
|
||||
if (!response || (response.status !== undefined && response.status !== 200)) {
|
||||
return { days: 0, nextRebindAt: '' }
|
||||
}
|
||||
const availability = resolveHuyaRoleRebindAvailability(
|
||||
{
|
||||
isBindAccount: true,
|
||||
isBindRole: true,
|
||||
roleName: '',
|
||||
roleToken: '',
|
||||
channel: '',
|
||||
changeBindTime: Number(response.accountData?.changeBindTime || 0),
|
||||
changeBindDay: Number(response.changeBindDay || 0),
|
||||
},
|
||||
nowMs,
|
||||
)
|
||||
if (availability.blocked) {
|
||||
return {
|
||||
days: availability.remainingDays,
|
||||
nextRebindAt: availability.availableAt,
|
||||
}
|
||||
}
|
||||
if (availability.windowDays > 0) {
|
||||
return {
|
||||
days: availability.windowDays,
|
||||
nextRebindAt: iso(nowMs + availability.windowDays * DAY_MS),
|
||||
}
|
||||
}
|
||||
return { days: 0, nextRebindAt: '' }
|
||||
}
|
||||
|
||||
export function classifyHuyaRebindFailure(messageInput: unknown): HuyaRebindBlockScope {
|
||||
const message = readString(messageInput).toLowerCase()
|
||||
if (!message) return 'platform'
|
||||
if (
|
||||
/待绑定游戏账号|目标角色|该游戏角色|游戏角色.*冷却|角色.*未到换绑|未到换绑时间/.test(message)
|
||||
) {
|
||||
return 'target_role'
|
||||
}
|
||||
if (/当前绑定账号|当前账号|当前角色|账号.*冷却|暂不能换绑|暂不能更换/.test(message)) {
|
||||
return 'account'
|
||||
}
|
||||
return 'platform'
|
||||
}
|
||||
|
||||
function resolveAccountRoleState(
|
||||
current: HuyaRoleSnapshot | null,
|
||||
inspected: boolean,
|
||||
): HuyaAccountRoleState {
|
||||
if (!inspected) return 'unknown'
|
||||
if (!current) return 'none'
|
||||
if (current.isBindAccount && current.isBindRole && readString(current.roleName)) return 'bound'
|
||||
if (!current.isBindAccount && !current.isBindRole) return 'none'
|
||||
return 'inconsistent'
|
||||
}
|
||||
|
||||
function decisionContext(input: HuyaBindingDecisionInput, nowMs: number) {
|
||||
const current = input.current
|
||||
const pending = input.pending
|
||||
const accountRoleState = resolveAccountRoleState(current, input.accountInspected)
|
||||
const currentComparison = current ? compareHuyaBindingRole(input.customer, current) : null
|
||||
const pendingComparison = pending ? compareHuyaBindingRole(input.customer, pending) : null
|
||||
const comparison =
|
||||
pendingComparison || currentComparison || compareHuyaBindingRole(input.customer, null)
|
||||
const accountAvailability = resolveHuyaRoleRebindAvailability(current, nowMs)
|
||||
const targetAvailability = resolveHuyaRoleRebindAvailability(pending, nowMs)
|
||||
const message = readString(input.bindConfirmMessage || input.rebindConfirmMessage)
|
||||
const failureScope =
|
||||
input.bindConfirmState === 'rejected' && message
|
||||
? classifyHuyaRebindFailure(message)
|
||||
: ('platform' as const)
|
||||
return {
|
||||
accountRoleState,
|
||||
currentComparison,
|
||||
pendingComparison,
|
||||
comparison,
|
||||
targetRoleMatch: comparison.verdict,
|
||||
accountAvailability,
|
||||
targetAvailability,
|
||||
message,
|
||||
failureScope,
|
||||
}
|
||||
}
|
||||
|
||||
function decision(
|
||||
input: HuyaBindingDecisionInput,
|
||||
base: ReturnType<typeof decisionContext>,
|
||||
state: {
|
||||
flowState: HuyaBindingFlowState
|
||||
primaryAction: HuyaBindingAction
|
||||
allowedActions: HuyaBindingAction[]
|
||||
rebindBlockScope?: HuyaRebindBlockScope
|
||||
message: string
|
||||
},
|
||||
): HuyaBindingDecision {
|
||||
const canConfirmBinding = [
|
||||
'first_bind_role_ready',
|
||||
'rebind_role_ready',
|
||||
'current_role_confirmable',
|
||||
].includes(state.flowState)
|
||||
const canGenerateBindingQr = [
|
||||
'initial_bind_required',
|
||||
'first_bind_qr_pending',
|
||||
'first_bind_failed',
|
||||
'rebind_required',
|
||||
'rebind_qr_pending',
|
||||
'rebind_rejected',
|
||||
'rebind_effect_failed',
|
||||
'expired',
|
||||
].includes(state.flowState)
|
||||
const requiresSupport = ['manual_review', 'first_bind_role_mismatch'].includes(state.flowState)
|
||||
return {
|
||||
accountRoleState: base.accountRoleState,
|
||||
targetRoleMatch: base.targetRoleMatch,
|
||||
flowState: state.flowState,
|
||||
primaryAction: state.primaryAction,
|
||||
allowedActions: state.allowedActions,
|
||||
rebindBlockScope: state.rebindBlockScope || '',
|
||||
accountRebindAvailableAt: base.accountAvailability.availableAt,
|
||||
targetRoleRebindAvailableAt: base.targetAvailability.availableAt,
|
||||
canGenerateBindingQr,
|
||||
canConfirmBinding,
|
||||
canCompleteTask: state.flowState === 'confirmed',
|
||||
requiresCustomerConfirmation: canConfirmBinding,
|
||||
requiresSupport,
|
||||
comparison: base.comparison,
|
||||
currentRoleComparison: base.currentComparison,
|
||||
pendingRoleComparison: base.pendingComparison,
|
||||
message: state.message,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 虎牙绑定业务判断的唯一入口。
|
||||
*
|
||||
* Connector 只提供 current/pending 原始事实,页面和任务服务只消费本函数结果。
|
||||
*/
|
||||
export function resolveHuyaBindingDecision(input: HuyaBindingDecisionInput): HuyaBindingDecision {
|
||||
const nowMs = input.nowMs ?? Date.now()
|
||||
const base = decisionContext(input, nowMs)
|
||||
const flow = input.bindingStatus
|
||||
const actions = (...items: HuyaBindingAction[]) => [...new Set(items)]
|
||||
|
||||
if (flow === 'expired') {
|
||||
const firstBinding = base.accountRoleState !== 'bound'
|
||||
return decision(input, base, {
|
||||
flowState: 'expired',
|
||||
primaryAction: firstBinding ? 'refresh_first_binding_qr' : 'refresh_rebind_qr',
|
||||
allowedActions: actions(
|
||||
firstBinding ? 'refresh_first_binding_qr' : 'refresh_rebind_qr',
|
||||
'contact_support',
|
||||
),
|
||||
message: '绑定二维码已过期,请重新获取',
|
||||
})
|
||||
}
|
||||
|
||||
if (!input.accountInspected) {
|
||||
return decision(input, base, {
|
||||
flowState: 'binding_query_required',
|
||||
primaryAction: 'query_binding',
|
||||
allowedActions: actions('query_binding', 'contact_support'),
|
||||
message: '请先查询虎牙账号当前绑定角色',
|
||||
})
|
||||
}
|
||||
|
||||
if (base.accountRoleState === 'inconsistent') {
|
||||
return decision(input, base, {
|
||||
flowState: 'manual_review',
|
||||
primaryAction: 'contact_support',
|
||||
allowedActions: actions('refresh_binding_status', 'contact_support'),
|
||||
message: '虎牙账号返回的绑定标志不完整,需要客服人工核实',
|
||||
})
|
||||
}
|
||||
|
||||
if (base.accountRoleState === 'bound') {
|
||||
if (base.currentComparison?.verdict === 'match') {
|
||||
if (flow === 'confirmed') {
|
||||
return decision(input, base, {
|
||||
flowState: 'confirmed',
|
||||
primaryAction: 'none',
|
||||
allowedActions: actions('none'),
|
||||
message: '目标角色已绑定,等待客服处理',
|
||||
})
|
||||
}
|
||||
return decision(input, base, {
|
||||
flowState: 'current_role_confirmable',
|
||||
primaryAction: 'confirm_current_role',
|
||||
allowedActions: actions('confirm_current_role', 'edit_profile', 'contact_support'),
|
||||
message: '当前虎牙角色与目标角色一致,请确认后进入客服处理',
|
||||
})
|
||||
}
|
||||
|
||||
if (base.currentComparison?.verdict === 'unknown') {
|
||||
return decision(input, base, {
|
||||
flowState: 'manual_review',
|
||||
primaryAction: 'contact_support',
|
||||
allowedActions: actions('refresh_binding_status', 'contact_support'),
|
||||
message: base.currentComparison.message,
|
||||
})
|
||||
}
|
||||
|
||||
if (input.bindConfirmState === 'accepted') {
|
||||
const deadlineMs = Date.parse(input.bindingEffectDeadlineAt || '')
|
||||
if (!Number.isFinite(deadlineMs) || nowMs < deadlineMs) {
|
||||
return decision(input, base, {
|
||||
flowState: 'rebind_effect_pending',
|
||||
primaryAction: 'refresh_binding_status',
|
||||
allowedActions: actions('refresh_binding_status'),
|
||||
message: '虎牙已受理换绑,正在等待目标角色生效',
|
||||
})
|
||||
}
|
||||
if (!input.pending) {
|
||||
return decision(input, base, {
|
||||
flowState: 'rebind_effect_failed',
|
||||
primaryAction: 'start_rebind',
|
||||
allowedActions: actions('start_rebind', 'edit_profile', 'contact_support'),
|
||||
message: '虎牙已受理换绑,但目标角色未生效,请重新选择角色',
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if (base.accountAvailability.blocked) {
|
||||
return decision(input, base, {
|
||||
flowState: 'rebind_blocked_account',
|
||||
primaryAction: 'wait_account_rebind',
|
||||
allowedActions: actions(
|
||||
'wait_account_rebind',
|
||||
'relogin',
|
||||
'edit_profile',
|
||||
'contact_support',
|
||||
),
|
||||
rebindBlockScope: 'account',
|
||||
message: `当前虎牙账号暂不可换绑,预计 ${base.accountAvailability.availableAt || '稍后'} 恢复`,
|
||||
})
|
||||
}
|
||||
|
||||
if (base.targetAvailability.blocked) {
|
||||
return decision(input, base, {
|
||||
flowState: 'rebind_blocked_target_role',
|
||||
primaryAction: 'wait_target_role_rebind',
|
||||
allowedActions: actions('wait_target_role_rebind', 'edit_profile', 'contact_support'),
|
||||
rebindBlockScope: 'target_role',
|
||||
message: `目标游戏角色仍在换绑冷却期,预计 ${base.targetAvailability.availableAt || '稍后'} 恢复`,
|
||||
})
|
||||
}
|
||||
|
||||
if (input.bindConfirmState === 'rejected') {
|
||||
const scope = base.failureScope
|
||||
if (scope === 'account') {
|
||||
return decision(input, base, {
|
||||
flowState: 'rebind_blocked_account',
|
||||
primaryAction: 'wait_account_rebind',
|
||||
allowedActions: actions(
|
||||
'wait_account_rebind',
|
||||
'relogin',
|
||||
'edit_profile',
|
||||
'contact_support',
|
||||
),
|
||||
rebindBlockScope: 'account',
|
||||
message: base.message || '当前虎牙账号暂不可换绑',
|
||||
})
|
||||
}
|
||||
if (scope === 'target_role') {
|
||||
return decision(input, base, {
|
||||
flowState: 'rebind_blocked_target_role',
|
||||
primaryAction: 'wait_target_role_rebind',
|
||||
allowedActions: actions('wait_target_role_rebind', 'edit_profile', 'contact_support'),
|
||||
rebindBlockScope: 'target_role',
|
||||
message: base.message || '目标游戏角色仍在换绑冷却期',
|
||||
})
|
||||
}
|
||||
return decision(input, base, {
|
||||
flowState: 'rebind_rejected',
|
||||
primaryAction: 'start_rebind',
|
||||
allowedActions: actions('start_rebind', 'edit_profile', 'contact_support'),
|
||||
rebindBlockScope: 'platform',
|
||||
message: base.message || '虎牙未接受本次换绑',
|
||||
})
|
||||
}
|
||||
|
||||
if (input.pending) {
|
||||
if (base.pendingComparison?.verdict === 'match') {
|
||||
return decision(input, base, {
|
||||
flowState: 'rebind_role_ready',
|
||||
primaryAction: 'confirm_rebind',
|
||||
allowedActions: actions(
|
||||
'confirm_rebind',
|
||||
'refresh_rebind_qr',
|
||||
'edit_profile',
|
||||
'contact_support',
|
||||
),
|
||||
message: '已识别本次待确认角色,核对后提交平台换绑',
|
||||
})
|
||||
}
|
||||
return decision(input, base, {
|
||||
flowState: 'manual_review',
|
||||
primaryAction: 'contact_support',
|
||||
allowedActions: actions('refresh_binding_status', 'edit_profile', 'contact_support'),
|
||||
message: base.pendingComparison?.message || '待确认角色与目标资料不一致',
|
||||
})
|
||||
}
|
||||
|
||||
if (
|
||||
input.rebindRequested &&
|
||||
input.hasBindingQr !== false &&
|
||||
['qr_pending', 'scanned'].includes(flow)
|
||||
) {
|
||||
return decision(input, base, {
|
||||
flowState: 'rebind_qr_pending',
|
||||
primaryAction: 'refresh_rebind_qr',
|
||||
allowedActions: actions('refresh_rebind_qr', 'refresh_binding_status', 'contact_support'),
|
||||
message: '请扫码并在虎牙中选择目标角色',
|
||||
})
|
||||
}
|
||||
|
||||
return decision(input, base, {
|
||||
flowState: 'rebind_required',
|
||||
primaryAction: 'start_rebind',
|
||||
allowedActions: actions('start_rebind', 'edit_profile', 'contact_support'),
|
||||
message: '当前角色不是目标角色,需要重新扫码换绑',
|
||||
})
|
||||
}
|
||||
|
||||
if (input.pending) {
|
||||
if (base.pendingComparison?.verdict === 'match') {
|
||||
return decision(input, base, {
|
||||
flowState: 'first_bind_role_ready',
|
||||
primaryAction: 'confirm_first_binding',
|
||||
allowedActions: actions(
|
||||
'confirm_first_binding',
|
||||
'refresh_first_binding_qr',
|
||||
'edit_profile',
|
||||
'contact_support',
|
||||
),
|
||||
message: '已识别首次待绑定角色,核对后提交平台绑定',
|
||||
})
|
||||
}
|
||||
return decision(input, base, {
|
||||
flowState: 'first_bind_role_mismatch',
|
||||
primaryAction: 'contact_support',
|
||||
allowedActions: actions('refresh_first_binding_qr', 'edit_profile', 'contact_support'),
|
||||
message: base.pendingComparison?.message || '待绑定角色与目标资料不一致',
|
||||
})
|
||||
}
|
||||
|
||||
if (input.bindConfirmState === 'rejected') {
|
||||
return decision(input, base, {
|
||||
flowState: 'first_bind_failed',
|
||||
primaryAction: 'refresh_first_binding_qr',
|
||||
allowedActions: actions('refresh_first_binding_qr', 'edit_profile', 'contact_support'),
|
||||
message: base.message || '虎牙未接受本次首次绑定',
|
||||
})
|
||||
}
|
||||
|
||||
if (input.hasBindingQr !== false && ['qr_pending', 'scanned'].includes(flow)) {
|
||||
return decision(input, base, {
|
||||
flowState: 'first_bind_qr_pending',
|
||||
primaryAction: 'refresh_first_binding_qr',
|
||||
allowedActions: actions(
|
||||
'refresh_first_binding_qr',
|
||||
'refresh_binding_status',
|
||||
'contact_support',
|
||||
),
|
||||
message: '请扫码并在虎牙中选择目标游戏角色',
|
||||
})
|
||||
}
|
||||
|
||||
return decision(input, base, {
|
||||
flowState: 'initial_bind_required',
|
||||
primaryAction: 'start_first_binding',
|
||||
allowedActions: actions('start_first_binding', 'edit_profile', 'contact_support'),
|
||||
message: '虎牙账号尚未绑定角色,请绑定目标角色',
|
||||
})
|
||||
}
|
||||
|
||||
export function isHuyaBindingConfirmedForCompletion(input: HuyaBindingDecisionInput): boolean {
|
||||
return resolveHuyaBindingDecision(input).canCompleteTask
|
||||
}
|
||||
|
||||
export function roleSnapshotsFromLegacyFields(input: {
|
||||
bindGameRole: string
|
||||
bindGameRoleToken: string
|
||||
bindGameChannel: string
|
||||
isBindAccount: boolean
|
||||
isBindRole: boolean
|
||||
changeBindTime: number
|
||||
changeBindDay: number
|
||||
pendingBindGameRole: string
|
||||
pendingBindGameRoleToken: string
|
||||
pendingBindGameChannel: string
|
||||
pendingChangeBindTime: number
|
||||
pendingChangeBindDay: number
|
||||
}): { current: HuyaRoleSnapshot | null; pending: HuyaRoleSnapshot | null } {
|
||||
const currentRole = readString(input.bindGameRole)
|
||||
const pendingRole = readString(input.pendingBindGameRole)
|
||||
return {
|
||||
current: currentRole
|
||||
? {
|
||||
isBindAccount: input.isBindAccount,
|
||||
isBindRole: input.isBindRole,
|
||||
roleName: currentRole,
|
||||
roleToken: readString(input.bindGameRoleToken),
|
||||
channel: readString(input.bindGameChannel),
|
||||
changeBindTime: Number(input.changeBindTime || 0),
|
||||
changeBindDay: Number(input.changeBindDay || 0),
|
||||
}
|
||||
: null,
|
||||
pending: pendingRole
|
||||
? {
|
||||
isBindAccount: false,
|
||||
isBindRole: false,
|
||||
roleName: pendingRole,
|
||||
roleToken: readString(input.pendingBindGameRoleToken),
|
||||
channel: readString(input.pendingBindGameChannel),
|
||||
changeBindTime: Number(input.pendingChangeBindTime || 0),
|
||||
changeBindDay: Number(input.pendingChangeBindDay || 0),
|
||||
}
|
||||
: null,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import test from 'node:test'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
const root = path.dirname(fileURLToPath(import.meta.url))
|
||||
|
||||
function source(file: string) {
|
||||
return readFileSync(path.join(root, file), 'utf8')
|
||||
}
|
||||
|
||||
test('虎牙绑定判断只保留一个策略器,任务服务只消费决策结果', () => {
|
||||
const policy = source('huya-binding-policy.ts')
|
||||
const taskCore = source('semi-auto-task-core.ts')
|
||||
const customerService = source('semi-auto-customer-service.ts')
|
||||
const adminService = source('semi-auto-admin-service.ts')
|
||||
|
||||
assert.match(policy, /export function resolveHuyaBindingDecision\(/)
|
||||
assert.match(taskCore, /return resolveHuyaBindingDecision\(\{/)
|
||||
assert.match(customerService, /resolveTaskHuyaBindingDecision\(/)
|
||||
assert.match(adminService, /resolveTaskHuyaBindingDecision\(/)
|
||||
assert.doesNotMatch(customerService, /binding_status\s*===\s*'confirmed'/)
|
||||
assert.doesNotMatch(customerService, /binding_status\s*!==\s*'role_ready'/)
|
||||
assert.doesNotMatch(adminService, /bindingStatus\s*===\s*'confirmed'/)
|
||||
})
|
||||
|
||||
test('外部 Connector 状态快照复用统一绑定写入和确认门禁', () => {
|
||||
const adminService = source('semi-auto-admin-service.ts')
|
||||
const customerService = source('semi-auto-customer-service.ts')
|
||||
|
||||
assert.match(adminService, /updateBindingTaskWithClient\(/)
|
||||
assert.match(adminService, /!isTaskBindingConfirmed\(task\)/)
|
||||
assert.match(customerService, /getHuyaBindingSnapshot\(/)
|
||||
assert.match(customerService, /if \(!decision\.canConfirmBinding\)/)
|
||||
})
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
type HuyaRestoreCredentialInput,
|
||||
type HuyaStoredCredential,
|
||||
} from './huya-native/huya-native-connector.js'
|
||||
import type { HuyaRoleSnapshot } from './huya-binding-policy.js'
|
||||
import { recordSemiAutoTrace, traceFingerprint } from './semi-auto-trace.js'
|
||||
|
||||
export type ConnectorLoginSession = {
|
||||
@@ -105,6 +106,10 @@ export type ConnectorBindingSession = {
|
||||
bindGameRoleToken?: string
|
||||
platformGameRoleUid?: string
|
||||
bindGameChannel: string
|
||||
/** 当前已生效角色原始事实;业务判断只允许由 huya-binding-policy 处理。 */
|
||||
currentRole?: HuyaRoleSnapshot | null
|
||||
/** 本次扫码后待确认角色原始事实。 */
|
||||
pendingRole?: HuyaRoleSnapshot | null
|
||||
pendingBindGameAccount?: string
|
||||
pendingBindGameRole?: string
|
||||
pendingBindGameRoleToken?: string
|
||||
@@ -125,6 +130,7 @@ export type ConnectorBindingSession = {
|
||||
rebindConfirmMessage?: string
|
||||
bindConfirmState?: 'idle' | 'submitting' | 'accepted' | 'rejected'
|
||||
bindConfirmMessage?: string
|
||||
bindEffectDeadlineAt?: string
|
||||
rebindCooldownDays?: number
|
||||
nextRebindAt?: string
|
||||
platformChangeBindDay?: number
|
||||
|
||||
@@ -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 { resolveHuyaRebindCooldownResponse } from '../huya-binding-policy.js'
|
||||
import type {
|
||||
ConnectorBindingSession,
|
||||
ConnectorBrowserTicket,
|
||||
@@ -254,32 +255,7 @@ 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 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
|
||||
// 虎牙把「本次绑定日」记成次日 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),
|
||||
nextRebindAt: iso(nextRebindMs),
|
||||
}
|
||||
}
|
||||
}
|
||||
if (hasPlatformWindow) {
|
||||
return { days: windowDays, nextRebindAt: iso(now + windowDays * DAY_MS) }
|
||||
}
|
||||
return { days: 0, nextRebindAt: '' }
|
||||
return resolveHuyaRebindCooldownResponse(response, now)
|
||||
}
|
||||
|
||||
function applyRebindMeta(
|
||||
@@ -1706,6 +1682,28 @@ export class HuyaNativeConnector {
|
||||
bindGameRoleToken: binding.roleId,
|
||||
platformGameRoleUid: /^\d+$/.test(binding.roleId) ? binding.roleId : '',
|
||||
bindGameChannel: binding.channel,
|
||||
currentRole: binding.role
|
||||
? {
|
||||
isBindAccount: binding.isBindAccount,
|
||||
isBindRole: binding.isBindRole,
|
||||
roleName: binding.role,
|
||||
roleToken: binding.roleId,
|
||||
channel: binding.channel,
|
||||
changeBindTime: binding.changeBindTime,
|
||||
changeBindDay: binding.changeBindDay,
|
||||
}
|
||||
: null,
|
||||
pendingRole: binding.pendingRole
|
||||
? {
|
||||
isBindAccount: false,
|
||||
isBindRole: false,
|
||||
roleName: binding.pendingRole,
|
||||
roleToken: binding.pendingRoleId,
|
||||
channel: binding.pendingChannel,
|
||||
changeBindTime: binding.pendingChangeBindTime,
|
||||
changeBindDay: binding.pendingChangeBindDay,
|
||||
}
|
||||
: null,
|
||||
pendingBindGameAccount: binding.pendingAccount,
|
||||
pendingBindGameRole: binding.pendingRole,
|
||||
pendingBindGameRoleToken: binding.pendingRoleId,
|
||||
@@ -1727,6 +1725,8 @@ export class HuyaNativeConnector {
|
||||
rebindConfirmMessage: binding.rebindConfirmMessage,
|
||||
bindConfirmState: binding.bindConfirmState,
|
||||
bindConfirmMessage: binding.bindConfirmMessage,
|
||||
bindEffectDeadlineAt:
|
||||
binding.bindEffectDeadlineMs > 0 ? iso(binding.bindEffectDeadlineMs) : '',
|
||||
rebindCooldownDays: binding.rebindCooldownDays,
|
||||
nextRebindAt: binding.nextRebindAt,
|
||||
platformChangeBindDay: binding.changeBindDay,
|
||||
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
consumeHuyaBrowserTicket,
|
||||
createHuyaBrowserTicket,
|
||||
revokeHuyaSession,
|
||||
type ConnectorBindingSession,
|
||||
type ConnectorInjectionPayload,
|
||||
type SemiAutoConnectorMode,
|
||||
} from './huya-connector-client.js'
|
||||
@@ -35,21 +36,23 @@ import { isHuyaRoleToken } from './binding-role-id.js'
|
||||
import { getAccountBindingPolicy } from '../account-binding/platform-policy.js'
|
||||
import {
|
||||
appendTaskEvent,
|
||||
compareBindingRole,
|
||||
ensureConnectorSessionForTask,
|
||||
ensureSemiAutoTasksForAdminList,
|
||||
getBindingForTask,
|
||||
getLoginSessionForTask,
|
||||
isTaskBindingConfirmed,
|
||||
loadTask,
|
||||
loadTaskForUpdateWithClient,
|
||||
mapTask,
|
||||
normalizeId,
|
||||
normalizeOrderNo,
|
||||
publishSemiAutoTaskRealtimeChange,
|
||||
resolveTaskHuyaBindingDecision,
|
||||
resetTaskForCustomerLogin,
|
||||
revokeSessionForTask,
|
||||
TASK_SELECT,
|
||||
updateBindingTask,
|
||||
updateBindingTaskWithClient,
|
||||
type BindingStatus,
|
||||
type ExecutionStatus,
|
||||
type LoginStatus,
|
||||
@@ -125,6 +128,7 @@ export async function listAdminSemiAutoTasks(input: Record<string, unknown> = {}
|
||||
|
||||
export async function getAdminSemiAutoTask(taskIdInput: unknown) {
|
||||
const task = await loadTask(normalizeId(taskIdInput))
|
||||
const bindingDecision = resolveTaskHuyaBindingDecision(task)
|
||||
const events = await query<{
|
||||
id: number
|
||||
event_type: string
|
||||
@@ -143,12 +147,7 @@ export async function getAdminSemiAutoTask(taskIdInput: unknown) {
|
||||
return {
|
||||
task: mapTask(task),
|
||||
// 管理端详情直接复用与客户页相同的角色核对口径。
|
||||
comparison: compareBindingRole(task, {
|
||||
bindGameRole: task.pending_bind_game_role || task.bind_game_role,
|
||||
bindGameRoleToken: task.pending_bind_game_role_token || task.bind_game_role_token,
|
||||
bindGameChannel: task.pending_bind_game_channel || task.bind_game_channel,
|
||||
platformGameRoleUid: task.platform_game_role_uid,
|
||||
}),
|
||||
comparison: bindingDecision?.comparison || null,
|
||||
events: events.rows.map((event) => ({
|
||||
id: Number(event.id),
|
||||
eventType: event.event_type,
|
||||
@@ -324,6 +323,14 @@ export async function syncAdminSemiAutoTask(taskIdInput: unknown) {
|
||||
await updateLoginTask(task, login, 'connector')
|
||||
task = await loadTask(taskId)
|
||||
}
|
||||
if (
|
||||
task.platform === 'huya' &&
|
||||
task.login_status === 'authenticated' &&
|
||||
!isTaskBindingConfirmed(task)
|
||||
) {
|
||||
const binding = await getBindingForTask(task, task.connector_session_id)
|
||||
await updateBindingTask(task, binding, 'connector')
|
||||
}
|
||||
return getAdminSemiAutoTask(taskId)
|
||||
}
|
||||
|
||||
@@ -408,6 +415,12 @@ const ROLE_IDENTITY_SOURCES = new Set([
|
||||
'manual',
|
||||
])
|
||||
const VERIFICATION_BASES = new Set(['', 'role_name_zone', 'platform_numeric_uid', 'manual'])
|
||||
const CONFIRM_STATES = new Set<'idle' | 'submitting' | 'accepted' | 'rejected'>([
|
||||
'idle',
|
||||
'submitting',
|
||||
'accepted',
|
||||
'rejected',
|
||||
])
|
||||
|
||||
function parseSnapshotStatus<T extends string>(value: unknown, allowed: Set<T>, label: string): T {
|
||||
const status = String(value || '').trim() as T
|
||||
@@ -420,6 +433,21 @@ function parseSnapshotStatus<T extends string>(value: unknown, allowed: Set<T>,
|
||||
return status
|
||||
}
|
||||
|
||||
function parseSnapshotBoolean(value: unknown): boolean | undefined {
|
||||
if (value === undefined || value === null || value === '') return undefined
|
||||
if (typeof value === 'boolean') return value
|
||||
if (typeof value === 'number') return value !== 0
|
||||
const text = String(value).trim().toLowerCase()
|
||||
if (['true', '1', 'yes'].includes(text)) return true
|
||||
if (['false', '0', 'no'].includes(text)) return false
|
||||
return undefined
|
||||
}
|
||||
|
||||
function parseSnapshotNumber(value: unknown): number {
|
||||
const number = Number(value)
|
||||
return Number.isFinite(number) && number > 0 ? number : 0
|
||||
}
|
||||
|
||||
/**
|
||||
* 外部 Connector 的幂等状态快照入口。
|
||||
*
|
||||
@@ -471,11 +499,6 @@ export async function applySemiAutoTaskStateSnapshot(
|
||||
return { applied: false, terminal: true }
|
||||
}
|
||||
|
||||
const executionStatus: ExecutionStatus =
|
||||
loginStatus === 'authenticated' &&
|
||||
(task.platform === 'weibo' || bindingStatus === 'confirmed')
|
||||
? 'waiting_operator'
|
||||
: 'waiting_customer'
|
||||
const uid = String(input.huyaUid ?? input.huya_uid ?? '').trim()
|
||||
const nickname = String(input.platformNickname ?? input.platform_nickname ?? '').trim()
|
||||
const bindGameAccount = String(input.bindGameAccount ?? input.bind_game_account ?? '').trim()
|
||||
@@ -548,72 +571,131 @@ export async function applySemiAutoTaskStateSnapshot(
|
||||
const message = String(input.message ?? input.lastError ?? input.last_error ?? '')
|
||||
.trim()
|
||||
.slice(0, 1000)
|
||||
const isBindAccount = parseSnapshotBoolean(input.isBindAccount ?? input.is_bind_account)
|
||||
const isBindRole = parseSnapshotBoolean(input.isBindRole ?? input.is_bind_role)
|
||||
const accountChangeBindTime = parseSnapshotNumber(
|
||||
input.accountChangeBindTime ?? input.account_change_bind_time,
|
||||
)
|
||||
const accountChangeBindDay = parseSnapshotNumber(
|
||||
input.accountChangeBindDay ?? input.account_change_bind_day,
|
||||
)
|
||||
const pendingChangeBindTime = parseSnapshotNumber(
|
||||
input.pendingChangeBindTime ??
|
||||
input.pending_bind_game_change_bind_time ??
|
||||
input.pendingBindGameChangeBindTime,
|
||||
)
|
||||
const pendingChangeBindDay = parseSnapshotNumber(
|
||||
input.pendingChangeBindDay ??
|
||||
input.pending_bind_game_change_bind_day ??
|
||||
input.pendingBindGameChangeBindDay,
|
||||
)
|
||||
const rebindConfirmState = parseSnapshotStatus(
|
||||
input.rebindConfirmState ?? input.rebind_confirm_state ?? 'idle',
|
||||
CONFIRM_STATES,
|
||||
'换绑确认状态',
|
||||
)
|
||||
const bindConfirmState = parseSnapshotStatus(
|
||||
input.bindConfirmState ?? input.bind_confirm_state ?? 'idle',
|
||||
CONFIRM_STATES,
|
||||
'绑定确认状态',
|
||||
)
|
||||
const accountFactsObserved =
|
||||
bindGameRole ||
|
||||
bindGameRoleToken ||
|
||||
platformGameRoleUid ||
|
||||
isBindAccount !== undefined ||
|
||||
isBindRole !== undefined
|
||||
const currentRole = accountFactsObserved
|
||||
? {
|
||||
isBindAccount: isBindAccount ?? Boolean(bindGameRole),
|
||||
isBindRole: isBindRole ?? Boolean(bindGameRole),
|
||||
roleName: bindGameRole,
|
||||
roleToken: platformGameRoleUid || bindGameRoleToken,
|
||||
channel: bindGameChannel,
|
||||
changeBindTime: accountChangeBindTime,
|
||||
changeBindDay: accountChangeBindDay,
|
||||
}
|
||||
: null
|
||||
const pendingRole = pendingBindGameRole
|
||||
? {
|
||||
isBindAccount: false,
|
||||
isBindRole: false,
|
||||
roleName: pendingBindGameRole,
|
||||
roleToken: pendingBindGameRoleToken,
|
||||
channel: pendingBindGameChannel,
|
||||
changeBindTime: pendingChangeBindTime,
|
||||
changeBindDay: pendingChangeBindDay,
|
||||
}
|
||||
: null
|
||||
const bindingSession: ConnectorBindingSession = {
|
||||
sessionId: task.connector_session_id,
|
||||
status: bindingStatus,
|
||||
qrImage: '',
|
||||
qrExpiresAt: '',
|
||||
qrUrl: '',
|
||||
bindGameAccount,
|
||||
bindGameRole,
|
||||
bindGameRoleId: legacyRoleId,
|
||||
bindGameRoleToken,
|
||||
platformGameRoleUid,
|
||||
bindGameChannel,
|
||||
...(accountFactsObserved && currentRole ? { currentRole } : {}),
|
||||
pendingRole,
|
||||
pendingBindGameAccount,
|
||||
pendingBindGameRole,
|
||||
pendingBindGameRoleToken,
|
||||
pendingBindGameChannel,
|
||||
pendingChangeBindTime,
|
||||
pendingChangeBindDay,
|
||||
roleIdentitySource: roleIdentitySource as NonNullable<
|
||||
ConnectorBindingSession['roleIdentitySource']
|
||||
>,
|
||||
verificationBasis: verificationBasis as NonNullable<
|
||||
ConnectorBindingSession['verificationBasis']
|
||||
>,
|
||||
...(accountFactsObserved ? { hasExistingBinding: currentRole?.isBindAccount === true } : {}),
|
||||
rebindRequested:
|
||||
parseSnapshotBoolean(input.rebindRequested ?? input.rebind_requested) === true,
|
||||
rebindUnchanged:
|
||||
parseSnapshotBoolean(input.rebindUnchanged ?? input.rebind_unchanged) === true,
|
||||
rebindConfirmState,
|
||||
rebindConfirmMessage: String(
|
||||
input.rebindConfirmMessage ?? input.rebind_confirm_message ?? '',
|
||||
).trim(),
|
||||
bindConfirmState,
|
||||
bindConfirmMessage: String(
|
||||
input.bindConfirmMessage ?? input.bind_confirm_message ?? '',
|
||||
).trim(),
|
||||
bindEffectDeadlineAt: String(
|
||||
input.bindEffectDeadlineAt ?? input.binding_effect_deadline_at ?? '',
|
||||
).trim(),
|
||||
message,
|
||||
}
|
||||
|
||||
await client.query(
|
||||
`UPDATE semi_auto_tasks
|
||||
SET login_status = $2,
|
||||
binding_status = $3,
|
||||
execution_status = $4,
|
||||
huya_uid = CASE WHEN $5 <> '' THEN $5 ELSE huya_uid END,
|
||||
platform_nickname = CASE WHEN $6 <> '' THEN $6 ELSE platform_nickname END,
|
||||
bind_game_account = CASE WHEN $7 <> '' THEN $7 ELSE bind_game_account END,
|
||||
bind_game_role = CASE WHEN $8 <> '' THEN $8 ELSE bind_game_role END,
|
||||
bind_game_role_token = CASE WHEN $9 <> '' THEN $9 ELSE bind_game_role_token END,
|
||||
bind_game_channel = CASE WHEN $10 <> '' THEN $10 ELSE bind_game_channel END,
|
||||
pending_bind_game_account = $12,
|
||||
pending_bind_game_role = $13,
|
||||
pending_bind_game_role_token = $14,
|
||||
pending_bind_game_channel = $15,
|
||||
platform_game_role_uid = $18,
|
||||
role_identity_source = CASE WHEN $16 <> '' THEN $16 ELSE role_identity_source END,
|
||||
verification_basis = CASE WHEN $17 <> '' THEN $17 ELSE verification_basis END,
|
||||
huya_uid = CASE WHEN $3 <> '' THEN $3 ELSE huya_uid END,
|
||||
platform_nickname = CASE WHEN $4 <> '' THEN $4 ELSE platform_nickname END,
|
||||
authenticated_at = CASE
|
||||
WHEN $2 = 'authenticated' THEN COALESCE(authenticated_at, NOW())
|
||||
ELSE authenticated_at
|
||||
END,
|
||||
bound_at = CASE
|
||||
WHEN $3 IN ('role_ready', 'confirmed') THEN COALESCE(bound_at, NOW())
|
||||
ELSE bound_at
|
||||
END,
|
||||
last_error = CASE WHEN $2 IN ('failed', 'expired') OR $3 IN ('failed', 'expired')
|
||||
THEN $11 ELSE '' END,
|
||||
last_error = CASE WHEN $2 IN ('failed', 'expired') THEN $5 ELSE last_error END,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1`,
|
||||
[
|
||||
task.id,
|
||||
loginStatus,
|
||||
bindingStatus,
|
||||
executionStatus,
|
||||
uid,
|
||||
nickname,
|
||||
bindGameAccount,
|
||||
bindGameRole,
|
||||
bindGameRoleToken,
|
||||
bindGameChannel,
|
||||
message,
|
||||
pendingBindGameAccount,
|
||||
pendingBindGameRole,
|
||||
pendingBindGameRoleToken,
|
||||
pendingBindGameChannel,
|
||||
roleIdentitySource,
|
||||
verificationBasis,
|
||||
platformGameRoleUid,
|
||||
],
|
||||
[task.id, loginStatus, uid, nickname, message],
|
||||
)
|
||||
if (
|
||||
loginStatus !== task.login_status ||
|
||||
bindingStatus !== task.binding_status ||
|
||||
executionStatus !== task.execution_status
|
||||
uid !== task.huya_uid ||
|
||||
nickname !== task.platform_nickname
|
||||
) {
|
||||
await appendTaskEvent(client, task.id, {
|
||||
eventType: 'connector_state_synced',
|
||||
eventType: 'connector_login_state_synced',
|
||||
actorType: 'connector',
|
||||
fromLoginStatus: task.login_status,
|
||||
toLoginStatus: loginStatus,
|
||||
fromBindingStatus: task.binding_status,
|
||||
toBindingStatus: bindingStatus,
|
||||
fromExecutionStatus: task.execution_status,
|
||||
toExecutionStatus: executionStatus,
|
||||
detail: {
|
||||
eventId,
|
||||
source: 'semi_auto_connector',
|
||||
@@ -621,11 +703,22 @@ export async function applySemiAutoTaskStateSnapshot(
|
||||
},
|
||||
})
|
||||
}
|
||||
const bindingResult = await updateBindingTaskWithClient(
|
||||
client,
|
||||
task.id,
|
||||
bindingSession,
|
||||
'connector',
|
||||
{
|
||||
eventType: 'connector_state_synced',
|
||||
eventDetail: { eventId, source: 'semi_auto_connector', message },
|
||||
},
|
||||
)
|
||||
return {
|
||||
applied: true,
|
||||
terminal: false,
|
||||
taskId: task.id,
|
||||
orderId: task.order_id,
|
||||
executionStatus: bindingResult.executionStatus,
|
||||
}
|
||||
})
|
||||
if (result.applied && result.taskId && result.orderId) {
|
||||
@@ -849,6 +942,19 @@ export async function completeAdminSemiAutoTask(
|
||||
errorCode: 'semi_auto_credential_required',
|
||||
})
|
||||
}
|
||||
const bindingDecision = resolveTaskHuyaBindingDecision(task)
|
||||
if (task.platform === 'huya' && !bindingDecision?.canCompleteTask) {
|
||||
throw createHttpError('虎牙角色绑定尚未确认,不能完成履约', {
|
||||
statusCode: 409,
|
||||
errorCode: 'huya_binding_not_confirmed',
|
||||
})
|
||||
}
|
||||
if (task.platform === 'weibo' && !isTaskBindingConfirmed(task)) {
|
||||
throw createHttpError('微博角色绑定尚未确认,不能完成履约', {
|
||||
statusCode: 409,
|
||||
errorCode: 'weibo_binding_not_confirmed',
|
||||
})
|
||||
}
|
||||
if (task.assigned_admin_user_id && Number(task.assigned_admin_user_id) !== adminUserId) {
|
||||
throw createHttpError('该任务已被其他客服领取', {
|
||||
statusCode: 409,
|
||||
|
||||
@@ -24,20 +24,20 @@ import {
|
||||
startWeiboBinding,
|
||||
} from './weibo-connector-client.js'
|
||||
import { upsertSemiAutoCredentialWithClient } from './semi-auto-credential-service.js'
|
||||
import { isHuyaRoleToken } from './binding-role-id.js'
|
||||
import { getAccountBindingPolicy } from '../account-binding/platform-policy.js'
|
||||
import {
|
||||
appendTaskEvent,
|
||||
assertCustomerProfileReady,
|
||||
assertHuyaTask,
|
||||
assertWeiboTask,
|
||||
compareBindingRole,
|
||||
createLoginSessionForTask,
|
||||
deriveSemiAutoExecutionStatus,
|
||||
ensureConnectorSessionForTask,
|
||||
ensureSemiAutoTasksForOrder,
|
||||
getBindingForTask,
|
||||
getLoginSessionForTask,
|
||||
hasCustomerProfile,
|
||||
isTaskBindingConfirmed,
|
||||
loadTask,
|
||||
loadTaskForOrder,
|
||||
loadTaskForUpdateWithClient,
|
||||
@@ -45,9 +45,11 @@ import {
|
||||
normalizeId,
|
||||
normalizeOrderNo,
|
||||
publishSemiAutoTaskRealtimeChange,
|
||||
refreshHuyaBindingDecisionForTask,
|
||||
resetTaskForInvalidCredential,
|
||||
resetTaskForCustomerLogin,
|
||||
revokeSessionForTask,
|
||||
resolveTaskHuyaBindingDecision,
|
||||
TASK_SELECT,
|
||||
updateBindingTask,
|
||||
type BindingStatus,
|
||||
@@ -154,7 +156,7 @@ export async function savePublicTaskProfile(
|
||||
errorCode: 'semi_auto_task_closed',
|
||||
})
|
||||
}
|
||||
if (task.binding_status === 'confirmed') {
|
||||
if (isTaskBindingConfirmed(task)) {
|
||||
throw createHttpError('绑定已确认,不能修改角色资料', {
|
||||
statusCode: 409,
|
||||
errorCode: 'semi_auto_profile_locked',
|
||||
@@ -176,7 +178,7 @@ export async function savePublicTaskProfile(
|
||||
errorCode: 'semi_auto_task_closed',
|
||||
})
|
||||
}
|
||||
if (current.binding_status === 'confirmed') {
|
||||
if (isTaskBindingConfirmed(current)) {
|
||||
throw createHttpError('绑定已确认,不能修改角色资料', {
|
||||
statusCode: 409,
|
||||
errorCode: 'semi_auto_profile_locked',
|
||||
@@ -206,7 +208,14 @@ export async function savePublicTaskProfile(
|
||||
})
|
||||
})
|
||||
publishSemiAutoTaskRealtimeChange(task.id, task.order_id)
|
||||
const updated = await loadTask(task.id)
|
||||
let updated = await loadTask(task.id)
|
||||
if (updated.platform === 'huya') {
|
||||
updated = await refreshHuyaBindingDecisionForTask(
|
||||
updated.id,
|
||||
'customer',
|
||||
'customer_profile_saved',
|
||||
)
|
||||
}
|
||||
return { task: mapTask(updated) }
|
||||
}
|
||||
|
||||
@@ -272,13 +281,12 @@ export async function updateLoginTask(
|
||||
return
|
||||
}
|
||||
// 登录成功只代表拿到账号 CK;必须等平台角色绑定事实确认后才进入客服处理。
|
||||
const nextExecutionStatus: ExecutionStatus =
|
||||
mapped.status === 'authenticated'
|
||||
? !getAccountBindingPolicy(current.platform).bindingRequired ||
|
||||
current.binding_status === 'confirmed'
|
||||
? 'waiting_operator'
|
||||
: 'waiting_customer'
|
||||
: current.execution_status
|
||||
const loginUpdated = { ...current, login_status: mapped.status }
|
||||
const nextExecutionStatus = deriveSemiAutoExecutionStatus(
|
||||
loginUpdated,
|
||||
current.binding_status,
|
||||
resolveTaskHuyaBindingDecision(loginUpdated),
|
||||
)
|
||||
const credentialId = storedCredential
|
||||
? await upsertSemiAutoCredentialWithClient(client, {
|
||||
platform: current.platform,
|
||||
@@ -404,6 +412,10 @@ export async function startPublicLogin(orderNoInput: unknown, taskIdInput: unkno
|
||||
bind_game_role_token = '',
|
||||
platform_game_role_uid = '',
|
||||
bind_game_channel = '',
|
||||
is_bind_account = FALSE,
|
||||
is_bind_role = FALSE,
|
||||
account_change_bind_time = 0,
|
||||
account_change_bind_day = 0,
|
||||
pending_bind_game_account = '',
|
||||
pending_bind_game_role = '',
|
||||
pending_bind_game_role_token = '',
|
||||
@@ -412,6 +424,18 @@ export async function startPublicLogin(orderNoInput: unknown, taskIdInput: unkno
|
||||
pending_bind_game_change_bind_day = 0,
|
||||
role_identity_source = '',
|
||||
verification_basis = '',
|
||||
binding_flow_state = 'binding_query_required',
|
||||
account_role_state = 'unknown',
|
||||
target_role_match = 'unknown',
|
||||
rebind_block_scope = '',
|
||||
rebind_platform_message = '',
|
||||
rebind_requested = FALSE,
|
||||
bind_confirm_state = 'idle',
|
||||
bind_confirm_message = '',
|
||||
binding_qr_issued_at = NULL,
|
||||
binding_effect_deadline_at = NULL,
|
||||
pending_role_observed_at = NULL,
|
||||
confirmed_role_observed_at = NULL,
|
||||
binding_started_at = NULL,
|
||||
bound_at = NULL,
|
||||
execution_status = 'waiting_customer',
|
||||
@@ -470,7 +494,7 @@ export async function pollPublicLogin(orderNoInput: unknown, taskIdInput: unknow
|
||||
export async function startPublicBinding(
|
||||
orderNoInput: unknown,
|
||||
taskIdInput: unknown,
|
||||
input: { forceRebind?: unknown; channel?: unknown } = {},
|
||||
input: { forceRebind?: unknown; channel?: unknown; intent?: unknown } = {},
|
||||
) {
|
||||
const orderNo = normalizeOrderNo(orderNoInput)
|
||||
const taskId = normalizeId(taskIdInput)
|
||||
@@ -488,22 +512,62 @@ export async function startPublicBinding(
|
||||
})
|
||||
}
|
||||
assertCustomerProfileReady(task)
|
||||
let session: ConnectorBindingSession
|
||||
if (task.platform === 'weibo') {
|
||||
const session = await startWeiboBinding(task.connector_session_id, task.connector_mode, {
|
||||
channel: input.channel === 'qq' ? 'qq' : 'wx',
|
||||
forceRebind: input.forceRebind === true,
|
||||
})
|
||||
const binding = await updateBindingTask(task, session, 'customer')
|
||||
const updated = await loadTask(task.id)
|
||||
return { task: mapTask(updated), binding }
|
||||
}
|
||||
|
||||
let inspection: ConnectorBindingSession
|
||||
try {
|
||||
session =
|
||||
task.platform === 'weibo'
|
||||
? await startWeiboBinding(task.connector_session_id, task.connector_mode, {
|
||||
channel: input.channel === 'qq' ? 'qq' : 'wx',
|
||||
forceRebind: input.forceRebind === true,
|
||||
})
|
||||
: await startHuyaBinding(task.connector_session_id, task.connector_mode, {
|
||||
forceRebind: input.forceRebind === true,
|
||||
})
|
||||
inspection = await getBindingForTask(task, task.connector_session_id)
|
||||
} catch (error) {
|
||||
await resetTaskForInvalidCredential(task, error)
|
||||
throw error
|
||||
}
|
||||
const binding = await updateBindingTask(task, session, 'customer')
|
||||
await updateBindingTask(task, inspection, 'customer')
|
||||
const inspectedTask = await loadTask(task.id)
|
||||
const decision = resolveTaskHuyaBindingDecision(inspectedTask)
|
||||
if (!decision) {
|
||||
throw createHttpError('虎牙绑定状态判断失败', {
|
||||
statusCode: 500,
|
||||
errorCode: 'huya_binding_decision_missing',
|
||||
})
|
||||
}
|
||||
|
||||
const wantsFirstBinding = ['start_first_binding', 'refresh_first_binding_qr'].includes(
|
||||
decision.primaryAction,
|
||||
)
|
||||
const wantsRebind =
|
||||
(input.intent === 'rebind' || input.forceRebind === true) &&
|
||||
['start_rebind', 'refresh_rebind_qr'].includes(decision.primaryAction)
|
||||
if (!wantsFirstBinding && !wantsRebind) {
|
||||
return {
|
||||
task: mapTask(inspectedTask),
|
||||
binding: {
|
||||
...inspection,
|
||||
comparison: decision.comparison,
|
||||
bindingDecision: decision,
|
||||
bindingFlowState: decision.flowState,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
const forceRebind = wantsRebind || decision.flowState.startsWith('rebind_')
|
||||
let session: ConnectorBindingSession
|
||||
try {
|
||||
session = await startHuyaBinding(task.connector_session_id, task.connector_mode, {
|
||||
forceRebind,
|
||||
})
|
||||
} catch (error) {
|
||||
await resetTaskForInvalidCredential(task, error)
|
||||
throw error
|
||||
}
|
||||
const binding = await updateBindingTask(inspectedTask, session, 'customer')
|
||||
const updated = await loadTask(task.id)
|
||||
return { task: mapTask(updated), binding }
|
||||
}
|
||||
@@ -533,7 +597,7 @@ export async function resetPublicBinding(orderNoInput: unknown, taskIdInput: unk
|
||||
errorCode: 'semi_auto_task_closed',
|
||||
})
|
||||
}
|
||||
if (task.binding_status === 'confirmed') {
|
||||
if (isTaskBindingConfirmed(task)) {
|
||||
throw createHttpError('绑定已确认,不能返回修改资料', {
|
||||
statusCode: 409,
|
||||
errorCode: 'semi_auto_profile_locked',
|
||||
@@ -562,7 +626,7 @@ export async function resetPublicBinding(orderNoInput: unknown, taskIdInput: unk
|
||||
errorCode: 'semi_auto_task_closed',
|
||||
})
|
||||
}
|
||||
if (current.binding_status === 'confirmed') {
|
||||
if (isTaskBindingConfirmed(current)) {
|
||||
throw createHttpError('绑定已确认,不能返回修改资料', {
|
||||
statusCode: 409,
|
||||
errorCode: 'semi_auto_profile_locked',
|
||||
@@ -578,6 +642,10 @@ export async function resetPublicBinding(orderNoInput: unknown, taskIdInput: unk
|
||||
bind_game_role_token = '',
|
||||
platform_game_role_uid = '',
|
||||
bind_game_channel = '',
|
||||
is_bind_account = FALSE,
|
||||
is_bind_role = FALSE,
|
||||
account_change_bind_time = 0,
|
||||
account_change_bind_day = 0,
|
||||
pending_bind_game_account = '',
|
||||
pending_bind_game_role = '',
|
||||
pending_bind_game_role_token = '',
|
||||
@@ -586,6 +654,18 @@ export async function resetPublicBinding(orderNoInput: unknown, taskIdInput: unk
|
||||
pending_bind_game_change_bind_day = 0,
|
||||
role_identity_source = '',
|
||||
verification_basis = '',
|
||||
binding_flow_state = 'binding_query_required',
|
||||
account_role_state = 'unknown',
|
||||
target_role_match = 'unknown',
|
||||
rebind_block_scope = '',
|
||||
rebind_platform_message = '',
|
||||
rebind_requested = FALSE,
|
||||
bind_confirm_state = 'idle',
|
||||
bind_confirm_message = '',
|
||||
binding_qr_issued_at = NULL,
|
||||
binding_effect_deadline_at = NULL,
|
||||
pending_role_observed_at = NULL,
|
||||
confirmed_role_observed_at = NULL,
|
||||
binding_started_at = NULL,
|
||||
bound_at = NULL,
|
||||
execution_status = 'waiting_customer',
|
||||
@@ -639,7 +719,11 @@ export async function pollPublicBinding(orderNoInput: unknown, taskIdInput: unkn
|
||||
export async function confirmPublicBinding(
|
||||
orderNoInput: unknown,
|
||||
taskIdInput: unknown,
|
||||
options: { acceptExistingRole?: boolean } = {},
|
||||
options: {
|
||||
expectedRoleName?: unknown
|
||||
expectedRoleToken?: unknown
|
||||
expectedRoleChannel?: unknown
|
||||
} = {},
|
||||
) {
|
||||
const orderNo = normalizeOrderNo(orderNoInput)
|
||||
const taskId = normalizeId(taskIdInput)
|
||||
@@ -657,71 +741,68 @@ export async function confirmPublicBinding(
|
||||
errorCode: 'semi_auto_task_closed',
|
||||
})
|
||||
}
|
||||
if (
|
||||
!task.connector_session_id ||
|
||||
(bindingPolicy.bindingRequired && task.binding_status !== 'role_ready')
|
||||
) {
|
||||
if (!task.connector_session_id) {
|
||||
throw createHttpError('当前没有待确认的绑定角色', {
|
||||
statusCode: 409,
|
||||
errorCode: 'semi_auto_binding_not_ready',
|
||||
})
|
||||
}
|
||||
assertCustomerProfileReady(task)
|
||||
// 先读取本地 pending 快照并比对;只有比对通过后才允许调用虎牙确认写接口。
|
||||
const session =
|
||||
bindingPolicy.bindingRequired && bindingPolicy.queryOwner === 'order_site'
|
||||
task.platform === 'huya'
|
||||
? await getHuyaBindingSnapshot(task.connector_session_id, task.connector_mode)
|
||||
: await getBindingForTask(task, task.connector_session_id)
|
||||
const comparisonRoleToken = String(
|
||||
session.pendingBindGameRole
|
||||
? session.pendingBindGameRoleToken
|
||||
: session.bindGameRoleToken || session.bindGameRoleId || '',
|
||||
).trim()
|
||||
const comparisonRole = {
|
||||
bindGameRole: session.pendingBindGameRole || session.bindGameRole,
|
||||
bindGameRoleToken: isHuyaRoleToken(comparisonRoleToken) ? comparisonRoleToken : '',
|
||||
bindGameChannel: session.pendingBindGameChannel || session.bindGameChannel,
|
||||
platformGameRoleUid: session.platformGameRoleUid || '',
|
||||
}
|
||||
const comparison = compareBindingRole(task, comparisonRole)
|
||||
// 换绑被虎牙拒绝时平台仍返回原角色。若客户已把资料改成与原角色一致,
|
||||
// 允许直接确认;否则要求重新扫码或返回上一步修改资料。
|
||||
if (
|
||||
task.platform === 'huya' &&
|
||||
session.rebindUnchanged === true &&
|
||||
comparison.verdict !== 'match'
|
||||
) {
|
||||
const reason = String(session.rebindConfirmMessage || '').trim()
|
||||
throw createHttpError(
|
||||
`${
|
||||
reason ? `换绑未成功:${reason}。` : '换绑未生效:平台仍返回原绑定角色。'
|
||||
}请重新扫码换绑,或返回上一步修改资料,使资料与平台当前角色一致后再提交平台绑定`,
|
||||
{
|
||||
await updateBindingTask(task, session, 'customer')
|
||||
const refreshedTask = await loadTask(task.id)
|
||||
const decision = resolveTaskHuyaBindingDecision(refreshedTask)
|
||||
if (task.platform === 'huya') {
|
||||
if (!decision) {
|
||||
throw createHttpError('虎牙绑定状态判断失败', {
|
||||
statusCode: 500,
|
||||
errorCode: 'huya_binding_decision_missing',
|
||||
})
|
||||
}
|
||||
if (!decision.canConfirmBinding) {
|
||||
throw createHttpError(decision.message || '当前没有可确认的绑定角色', {
|
||||
statusCode: 409,
|
||||
errorCode: 'semi_auto_binding_rebind_decision_required',
|
||||
},
|
||||
)
|
||||
}
|
||||
// 角色名和区服必须一致;信息不完整同样不能自动放行,必须转客服核实。
|
||||
if (comparison.verdict !== 'match') {
|
||||
throw createHttpError(comparison.message, {
|
||||
errorCode: 'semi_auto_binding_not_ready',
|
||||
})
|
||||
}
|
||||
const expectedRoleName = String(options.expectedRoleName || '').trim()
|
||||
const expectedRoleToken = String(options.expectedRoleToken || '').trim()
|
||||
const expectedRoleChannel = String(options.expectedRoleChannel || '').trim()
|
||||
if (!expectedRoleName || !expectedRoleChannel) {
|
||||
throw createHttpError('缺少页面核对快照,请刷新绑定角色后重试', {
|
||||
statusCode: 409,
|
||||
errorCode: 'semi_auto_binding_snapshot_required',
|
||||
})
|
||||
}
|
||||
const currentRole = session.currentRole || null
|
||||
const pendingRole = session.pendingRole || null
|
||||
const targetRole = pendingRole || currentRole
|
||||
if (
|
||||
!targetRole ||
|
||||
targetRole.roleName !== expectedRoleName ||
|
||||
targetRole.channel !== expectedRoleChannel ||
|
||||
(expectedRoleToken && targetRole.roleToken !== expectedRoleToken)
|
||||
) {
|
||||
throw createHttpError('待确认角色已变化,请重新核对后再提交', {
|
||||
statusCode: 409,
|
||||
errorCode: 'huya_bind_pending_role_changed',
|
||||
})
|
||||
}
|
||||
} else if (session.status !== 'confirmed') {
|
||||
throw createHttpError('当前没有可确认的绑定角色', {
|
||||
statusCode: 409,
|
||||
errorCode:
|
||||
comparison.verdict === 'mismatch'
|
||||
? 'semi_auto_binding_role_mismatch'
|
||||
: 'semi_auto_binding_role_unverifiable',
|
||||
errorCode: 'semi_auto_binding_not_ready',
|
||||
})
|
||||
}
|
||||
// 必须调用 Connector 完成确认,否则会话仍是 role_ready,数据库也会停在待确认。
|
||||
const confirmedSession =
|
||||
task.platform === 'huya'
|
||||
? await confirmHuyaBinding(task.connector_session_id, task.connector_mode, {
|
||||
...(options.acceptExistingRole === true || session.rebindUnchanged === true
|
||||
? { acceptExistingRole: true }
|
||||
: {}),
|
||||
expectedRoleName: comparisonRole.bindGameRole || '',
|
||||
expectedRoleToken: comparisonRole.bindGameRoleToken || '',
|
||||
expectedRoleChannel: comparisonRole.bindGameChannel || '',
|
||||
expectedRoleName: String(options.expectedRoleName || '').trim(),
|
||||
expectedRoleToken: String(options.expectedRoleToken || '').trim(),
|
||||
expectedRoleChannel: String(options.expectedRoleChannel || '').trim(),
|
||||
})
|
||||
: session
|
||||
const binding = await updateBindingTask(task, confirmedSession, 'customer')
|
||||
@@ -798,7 +879,40 @@ export async function sendPublicHuyaSmsCode(
|
||||
UPDATE semi_auto_tasks
|
||||
SET connector_session_id = $2,
|
||||
login_status = 'waiting_login',
|
||||
binding_status = 'not_started',
|
||||
execution_status = 'waiting_customer',
|
||||
bind_game_account = '',
|
||||
bind_game_role = '',
|
||||
bind_game_role_id = '',
|
||||
bind_game_role_token = '',
|
||||
platform_game_role_uid = '',
|
||||
bind_game_channel = '',
|
||||
is_bind_account = FALSE,
|
||||
is_bind_role = FALSE,
|
||||
account_change_bind_time = 0,
|
||||
account_change_bind_day = 0,
|
||||
pending_bind_game_account = '',
|
||||
pending_bind_game_role = '',
|
||||
pending_bind_game_role_token = '',
|
||||
pending_bind_game_channel = '',
|
||||
pending_bind_game_change_bind_time = 0,
|
||||
pending_bind_game_change_bind_day = 0,
|
||||
role_identity_source = '',
|
||||
verification_basis = '',
|
||||
binding_flow_state = 'binding_query_required',
|
||||
account_role_state = 'unknown',
|
||||
target_role_match = 'unknown',
|
||||
rebind_block_scope = '',
|
||||
rebind_platform_message = '',
|
||||
rebind_requested = FALSE,
|
||||
bind_confirm_state = 'idle',
|
||||
bind_confirm_message = '',
|
||||
binding_qr_issued_at = NULL,
|
||||
binding_effect_deadline_at = NULL,
|
||||
binding_started_at = NULL,
|
||||
pending_role_observed_at = NULL,
|
||||
confirmed_role_observed_at = NULL,
|
||||
bound_at = NULL,
|
||||
auth_started_at = COALESCE(auth_started_at, NOW()),
|
||||
last_error = '',
|
||||
updated_at = NOW()
|
||||
|
||||
@@ -23,18 +23,14 @@ import {
|
||||
defaultSemiAutoConnectorMode,
|
||||
createHuyaBrowserTicket,
|
||||
createHuyaLoginSession,
|
||||
confirmHuyaBinding,
|
||||
exportHuyaSessionCredential,
|
||||
getHuyaBinding,
|
||||
getHuyaBindingSnapshot,
|
||||
getHuyaLoginSession,
|
||||
loginHuyaSms,
|
||||
resetHuyaBinding,
|
||||
restoreHuyaSessionFromCredential,
|
||||
revokeHuyaSession,
|
||||
sendHuyaSmsCode,
|
||||
startHuyaBinding,
|
||||
submitHuyaRebind,
|
||||
consumeHuyaBrowserTicket,
|
||||
verifyHuyaSmsChallenge,
|
||||
type ConnectorBindingSession,
|
||||
@@ -65,8 +61,19 @@ import {
|
||||
} from './semi-auto-credential-service.js'
|
||||
import { querySemiAutoTraces } from './semi-auto-trace.js'
|
||||
import { isHuyaRoleToken, isNumericBindingRoleId } from './binding-role-id.js'
|
||||
import { compareBindingIdentity, resolveServerZone } from '../account-binding/binding-identity.js'
|
||||
import { resolveServerZone } from '../account-binding/binding-identity.js'
|
||||
import { getAccountBindingPolicy } from '../account-binding/platform-policy.js'
|
||||
import {
|
||||
compareHuyaBindingRole,
|
||||
resolveHuyaBindingDecision,
|
||||
roleSnapshotsFromLegacyFields,
|
||||
type HuyaBindingDecision,
|
||||
type HuyaBindingFlowState,
|
||||
type HuyaRebindBlockScope,
|
||||
type HuyaTargetRoleMatch,
|
||||
type HuyaAccountRoleState,
|
||||
type HuyaRoleSnapshot,
|
||||
} from './huya-binding-policy.js'
|
||||
|
||||
const SEMI_AUTO_PLATFORMS = new Set(['huya', 'weibo'])
|
||||
const ADMIN_LIST_BACKFILL_INTERVAL_MS = 15_000
|
||||
@@ -117,6 +124,10 @@ export type TaskRow = {
|
||||
bind_game_role_id: string
|
||||
bind_game_role_token: string
|
||||
platform_game_role_uid: string
|
||||
is_bind_account: boolean
|
||||
is_bind_role: boolean
|
||||
account_change_bind_time: number
|
||||
account_change_bind_day: number
|
||||
bind_game_channel: string
|
||||
pending_bind_game_account: string
|
||||
pending_bind_game_role: string
|
||||
@@ -124,6 +135,18 @@ export type TaskRow = {
|
||||
pending_bind_game_channel: string
|
||||
pending_bind_game_change_bind_time: number
|
||||
pending_bind_game_change_bind_day: number
|
||||
binding_flow_state: HuyaBindingFlowState
|
||||
account_role_state: HuyaAccountRoleState
|
||||
target_role_match: HuyaTargetRoleMatch
|
||||
rebind_block_scope: HuyaRebindBlockScope
|
||||
rebind_platform_message: string
|
||||
rebind_requested: boolean
|
||||
bind_confirm_state: 'idle' | 'submitting' | 'accepted' | 'rejected'
|
||||
bind_confirm_message: string
|
||||
binding_qr_issued_at: string | null
|
||||
binding_effect_deadline_at: string | null
|
||||
pending_role_observed_at: string | null
|
||||
confirmed_role_observed_at: string | null
|
||||
role_identity_source: string
|
||||
verification_basis: string
|
||||
legacy_bind_game_role_id: string
|
||||
@@ -241,7 +264,140 @@ export function hasCustomerProfile(
|
||||
)
|
||||
}
|
||||
|
||||
export function displayStatus(task: TaskRow) {
|
||||
function huyaRoleSnapshots(task: TaskRow): {
|
||||
current: HuyaRoleSnapshot | null
|
||||
pending: HuyaRoleSnapshot | null
|
||||
} {
|
||||
return roleSnapshotsFromLegacyFields({
|
||||
bindGameRole: task.bind_game_role,
|
||||
bindGameRoleToken: task.bind_game_role_token,
|
||||
bindGameChannel: task.bind_game_channel,
|
||||
isBindAccount: task.is_bind_account,
|
||||
isBindRole: task.is_bind_role,
|
||||
changeBindTime: task.account_change_bind_time,
|
||||
changeBindDay: task.account_change_bind_day,
|
||||
pendingBindGameRole: task.pending_bind_game_role,
|
||||
pendingBindGameRoleToken: task.pending_bind_game_role_token,
|
||||
pendingBindGameChannel: task.pending_bind_game_channel,
|
||||
pendingChangeBindTime: task.pending_bind_game_change_bind_time,
|
||||
pendingChangeBindDay: task.pending_bind_game_change_bind_day,
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 任务 DTO、客户操作和后台完成门禁共用的虎牙绑定判断入口。
|
||||
* 其他模块只能消费返回值,不得重新解释角色、换绑或确认状态。
|
||||
*/
|
||||
export function resolveTaskHuyaBindingDecision(task: TaskRow): HuyaBindingDecision | null {
|
||||
if (task.platform !== 'huya') return null
|
||||
const roles = huyaRoleSnapshots(task)
|
||||
const accountInspected =
|
||||
task.account_role_state !== 'unknown' ||
|
||||
task.binding_flow_state !== 'binding_query_required' ||
|
||||
Boolean(task.binding_started_at) ||
|
||||
Boolean(task.pending_role_observed_at) ||
|
||||
Boolean(task.confirmed_role_observed_at) ||
|
||||
task.binding_status !== 'not_started'
|
||||
return resolveHuyaBindingDecision({
|
||||
customer: {
|
||||
roleName: task.customer_game_role,
|
||||
roleId: task.customer_game_id,
|
||||
serverZone: task.customer_server_zone,
|
||||
},
|
||||
current: roles.current,
|
||||
pending: roles.pending,
|
||||
accountInspected,
|
||||
bindingStatus: task.binding_status,
|
||||
rebindRequested: task.rebind_requested,
|
||||
bindConfirmState: task.bind_confirm_state,
|
||||
bindConfirmMessage: task.bind_confirm_message,
|
||||
rebindConfirmMessage: task.rebind_platform_message,
|
||||
hasBindingQr: Boolean(task.binding_qr_issued_at),
|
||||
...(task.binding_effect_deadline_at
|
||||
? { bindingEffectDeadlineAt: task.binding_effect_deadline_at }
|
||||
: {}),
|
||||
})
|
||||
}
|
||||
|
||||
export function isTaskBindingConfirmed(task: TaskRow): boolean {
|
||||
if (task.platform === 'huya') {
|
||||
return resolveTaskHuyaBindingDecision(task)?.flowState === 'confirmed'
|
||||
}
|
||||
return (
|
||||
!getAccountBindingPolicy(task.platform).bindingRequired || task.binding_status === 'confirmed'
|
||||
)
|
||||
}
|
||||
|
||||
export async function refreshHuyaBindingDecisionForTask(
|
||||
taskIdInput: unknown,
|
||||
actorType: TaskActorType = 'system',
|
||||
eventType = 'binding_decision_recomputed',
|
||||
) {
|
||||
const taskId = normalizeId(taskIdInput)
|
||||
const result = await withTransaction(async (client) => {
|
||||
const current = await loadTaskForUpdateWithClient(client, taskId)
|
||||
const bindingDecision = resolveTaskHuyaBindingDecision(current)
|
||||
if (!bindingDecision) return current
|
||||
const executionStatus = deriveSemiAutoExecutionStatus(
|
||||
current,
|
||||
current.binding_status,
|
||||
bindingDecision,
|
||||
)
|
||||
await client.query(
|
||||
`
|
||||
UPDATE semi_auto_tasks
|
||||
SET binding_flow_state = $2,
|
||||
account_role_state = $3,
|
||||
target_role_match = $4,
|
||||
rebind_block_scope = $5,
|
||||
execution_status = $6,
|
||||
bound_at = CASE WHEN $7 THEN COALESCE(bound_at, NOW()) ELSE NULL END,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1
|
||||
`,
|
||||
[
|
||||
current.id,
|
||||
bindingDecision.flowState,
|
||||
bindingDecision.accountRoleState,
|
||||
bindingDecision.targetRoleMatch,
|
||||
bindingDecision.rebindBlockScope,
|
||||
executionStatus,
|
||||
bindingDecision.flowState === 'confirmed',
|
||||
],
|
||||
)
|
||||
if (
|
||||
current.binding_flow_state !== bindingDecision.flowState ||
|
||||
current.execution_status !== executionStatus ||
|
||||
current.account_role_state !== bindingDecision.accountRoleState ||
|
||||
current.target_role_match !== bindingDecision.targetRoleMatch
|
||||
) {
|
||||
await appendTaskEvent(client, current.id, {
|
||||
eventType,
|
||||
actorType,
|
||||
fromBindingStatus: current.binding_status,
|
||||
toBindingStatus: current.binding_status,
|
||||
fromExecutionStatus: current.execution_status,
|
||||
toExecutionStatus: executionStatus,
|
||||
detail: {
|
||||
bindingFlowState: bindingDecision.flowState,
|
||||
primaryAction: bindingDecision.primaryAction,
|
||||
accountRoleState: bindingDecision.accountRoleState,
|
||||
targetRoleMatch: bindingDecision.targetRoleMatch,
|
||||
rebindBlockScope: bindingDecision.rebindBlockScope,
|
||||
accountRebindAvailableAt: bindingDecision.accountRebindAvailableAt,
|
||||
targetRoleRebindAvailableAt: bindingDecision.targetRoleRebindAvailableAt,
|
||||
message: bindingDecision.message,
|
||||
},
|
||||
})
|
||||
}
|
||||
return current
|
||||
})
|
||||
if (!result) return loadTask(taskId)
|
||||
publishSemiAutoTaskRealtimeChange(taskId, result.order_id)
|
||||
return loadTask(taskId)
|
||||
}
|
||||
|
||||
export function displayStatus(task: TaskRow, decision = resolveTaskHuyaBindingDecision(task)) {
|
||||
const bindingPolicy = getAccountBindingPolicy(task.platform)
|
||||
const status = (
|
||||
key: string,
|
||||
@@ -265,10 +421,6 @@ export function displayStatus(task: TaskRow) {
|
||||
return status('processing', '处理中', 'operator', '客服继续履约')
|
||||
}
|
||||
if (task.login_status === 'authenticated') {
|
||||
// 微博和虎牙都必须在平台侧完成角色绑定后才能进入客服处理。
|
||||
if (!bindingPolicy.bindingRequired || task.binding_status === 'confirmed') {
|
||||
return status('waiting_operator', '等待客服处理', 'operator', '客服领取并履约')
|
||||
}
|
||||
if (bindingPolicy.requiresCustomerProfile && !hasCustomerProfile(task)) {
|
||||
return status(
|
||||
'waiting_profile',
|
||||
@@ -277,6 +429,53 @@ export function displayStatus(task: TaskRow) {
|
||||
'客户填写区服、游戏角色 UID 和角色名',
|
||||
)
|
||||
}
|
||||
if (task.platform === 'huya' && decision) {
|
||||
switch (decision.flowState) {
|
||||
case 'confirmed':
|
||||
return status('waiting_operator', '等待客服处理', 'operator', '客服领取并履约')
|
||||
case 'current_role_confirmable':
|
||||
case 'first_bind_role_ready':
|
||||
case 'rebind_role_ready':
|
||||
return status('binding_confirm', '待确认绑定角色', 'customer', '核对角色并提交确认')
|
||||
case 'rebind_required':
|
||||
return status('rebind_required', '需要换绑目标角色', 'customer', '重新扫码换绑')
|
||||
case 'rebind_blocked_account':
|
||||
return status(
|
||||
'rebind_blocked_account',
|
||||
'账号换绑冷却中',
|
||||
'customer',
|
||||
'更换账号或等待冷却结束',
|
||||
)
|
||||
case 'rebind_blocked_target_role':
|
||||
return status(
|
||||
'rebind_blocked_target_role',
|
||||
'目标角色换绑冷却中',
|
||||
'customer',
|
||||
'修改目标资料或等待冷却结束',
|
||||
)
|
||||
case 'rebind_effect_pending':
|
||||
return status('rebind_effect_pending', '换绑生效中', 'system', '稍后刷新绑定状态')
|
||||
case 'manual_review':
|
||||
case 'first_bind_role_mismatch':
|
||||
return status('binding_support', '绑定需人工核实', 'operator', '客服核对角色信息')
|
||||
case 'rebind_rejected':
|
||||
case 'rebind_effect_failed':
|
||||
case 'first_bind_failed':
|
||||
return status('binding_failed', '绑定失败,需处理', 'customer', '查看原因后重试')
|
||||
case 'expired':
|
||||
return status('binding_expired', '绑定二维码已过期', 'customer', '刷新绑定二维码')
|
||||
case 'initial_bind_required':
|
||||
case 'first_bind_qr_pending':
|
||||
case 'rebind_qr_pending':
|
||||
return status('waiting_binding', '等待客户绑定角色', 'customer', '完成角色扫码绑定')
|
||||
case 'binding_query_required':
|
||||
return status('waiting_binding', '等待查询绑定状态', 'system', '刷新绑定状态')
|
||||
}
|
||||
}
|
||||
// 微博以平台事实确认;虎牙已在上方由唯一决策器处理。
|
||||
if (isTaskBindingConfirmed(task)) {
|
||||
return status('waiting_operator', '等待客服处理', 'operator', '客服领取并履约')
|
||||
}
|
||||
if (task.binding_status === 'role_ready') {
|
||||
return status('binding_confirm', '待确认绑定角色', 'customer', '核对角色并提交绑定')
|
||||
}
|
||||
@@ -299,6 +498,7 @@ export function displayStatus(task: TaskRow) {
|
||||
|
||||
export function mapTask(task: TaskRow) {
|
||||
const bindingPolicy = getAccountBindingPolicy(task.platform)
|
||||
const bindingDecision = resolveTaskHuyaBindingDecision(task)
|
||||
return {
|
||||
id: Number(task.id),
|
||||
orderId: Number(task.order_id),
|
||||
@@ -320,7 +520,7 @@ export function mapTask(task: TaskRow) {
|
||||
bindingStatus: task.binding_status,
|
||||
executionStatus: task.execution_status,
|
||||
connectorMode: task.connector_mode,
|
||||
displayStatus: displayStatus(task),
|
||||
displayStatus: displayStatus(task, bindingDecision),
|
||||
connectorReady: Boolean(task.connector_session_id || task.credential_id),
|
||||
credentialReady: Boolean(task.credential_id),
|
||||
credentialStatus: task.credential_status || 'unknown',
|
||||
@@ -332,6 +532,10 @@ export function mapTask(task: TaskRow) {
|
||||
bindGameRole: task.bind_game_role,
|
||||
bindGameRoleId: '',
|
||||
bindGameRoleToken: task.bind_game_role_token,
|
||||
isBindAccount: task.is_bind_account,
|
||||
isBindRole: task.is_bind_role,
|
||||
accountChangeBindTime: Number(task.account_change_bind_time || 0),
|
||||
accountChangeBindDay: Number(task.account_change_bind_day || 0),
|
||||
platformGameRoleUid: task.platform_game_role_uid,
|
||||
bindGameChannel: task.bind_game_channel,
|
||||
pendingBindGameAccount: task.pending_bind_game_account,
|
||||
@@ -340,6 +544,12 @@ export function mapTask(task: TaskRow) {
|
||||
pendingBindGameChannel: task.pending_bind_game_channel,
|
||||
roleIdentitySource: task.role_identity_source,
|
||||
verificationBasis: task.verification_basis,
|
||||
bindingDecision,
|
||||
bindingFlowState: bindingDecision?.flowState || task.binding_flow_state,
|
||||
accountRoleState: bindingDecision?.accountRoleState || task.account_role_state,
|
||||
targetRoleMatch: bindingDecision?.targetRoleMatch || task.target_role_match,
|
||||
rebindBlockScope: bindingDecision?.rebindBlockScope || task.rebind_block_scope,
|
||||
rebindPlatformMessage: task.rebind_platform_message,
|
||||
customerGameRoleId: task.customer_game_id || '',
|
||||
customerGameRoleName: task.customer_game_role || '',
|
||||
customerServerZone: task.customer_server_zone || '',
|
||||
@@ -618,6 +828,10 @@ export async function resetTaskForCustomerLogin(
|
||||
bind_game_role_token = '',
|
||||
platform_game_role_uid = '',
|
||||
bind_game_channel = '',
|
||||
is_bind_account = FALSE,
|
||||
is_bind_role = FALSE,
|
||||
account_change_bind_time = 0,
|
||||
account_change_bind_day = 0,
|
||||
pending_bind_game_account = '',
|
||||
pending_bind_game_role = '',
|
||||
pending_bind_game_role_token = '',
|
||||
@@ -626,6 +840,18 @@ export async function resetTaskForCustomerLogin(
|
||||
pending_bind_game_change_bind_day = 0,
|
||||
role_identity_source = '',
|
||||
verification_basis = '',
|
||||
binding_flow_state = 'binding_query_required',
|
||||
account_role_state = 'unknown',
|
||||
target_role_match = 'unknown',
|
||||
rebind_block_scope = '',
|
||||
rebind_platform_message = '',
|
||||
rebind_requested = FALSE,
|
||||
bind_confirm_state = 'idle',
|
||||
bind_confirm_message = '',
|
||||
binding_qr_issued_at = NULL,
|
||||
binding_effect_deadline_at = NULL,
|
||||
pending_role_observed_at = NULL,
|
||||
confirmed_role_observed_at = NULL,
|
||||
customer_link_opened_at = NULL,
|
||||
auth_started_at = NULL,
|
||||
authenticated_at = NULL,
|
||||
@@ -940,18 +1166,7 @@ export async function backfillSemiAutoTasks(
|
||||
return { createdIds: result.createdIds, orderIds: result.orderIds }
|
||||
}
|
||||
|
||||
export type BindingRoleComparison = {
|
||||
verdict: 'match' | 'mismatch' | 'unknown'
|
||||
customerRoleName: string
|
||||
customerRoleId: string
|
||||
customerZone: string
|
||||
boundRoleName: string
|
||||
boundRoleId: string
|
||||
boundRoleIdKind: 'game_role_uid' | 'huya_role_token' | 'missing'
|
||||
boundZone: string
|
||||
verificationBasis: 'role_name_zone' | 'platform_numeric_uid' | 'manual'
|
||||
message: string
|
||||
}
|
||||
export type BindingRoleComparison = ReturnType<typeof compareHuyaBindingRole>
|
||||
|
||||
/**
|
||||
* 从虎牙渠道串解析区服,例如「安卓(android) · 微信」→ 安卓V区。
|
||||
@@ -975,76 +1190,24 @@ export function compareBindingRole(
|
||||
platformGameRoleUid?: string
|
||||
},
|
||||
): BindingRoleComparison {
|
||||
const customerRoleName = String(task.customer_game_role || '').trim()
|
||||
const customerRoleId = String(task.customer_game_id || '').trim()
|
||||
const customerZone = resolveServerZone(task.customer_game_server_zone)
|
||||
const boundRoleName = String(binding.bindGameRole || '').trim()
|
||||
const roleToken = String(binding.bindGameRoleToken || '').trim()
|
||||
const platformRoleUid = String(binding.platformGameRoleUid || '').trim()
|
||||
const numericPlatformRoleUid = isNumericBindingRoleId(platformRoleUid) ? platformRoleUid : ''
|
||||
const boundZone = detectServerZone(binding.bindGameChannel)
|
||||
const base = {
|
||||
customerRoleName,
|
||||
customerRoleId,
|
||||
customerZone,
|
||||
boundRoleName,
|
||||
boundRoleId: numericPlatformRoleUid || roleToken,
|
||||
boundRoleIdKind: numericPlatformRoleUid
|
||||
? ('game_role_uid' as const)
|
||||
: roleToken
|
||||
? ('huya_role_token' as const)
|
||||
: ('missing' as const),
|
||||
boundZone,
|
||||
verificationBasis: numericPlatformRoleUid
|
||||
? ('platform_numeric_uid' as const)
|
||||
: ('role_name_zone' as const),
|
||||
}
|
||||
|
||||
const policy = getAccountBindingPolicy('huya')
|
||||
const comparison = compareBindingIdentity({
|
||||
requiredFields: numericPlatformRoleUid
|
||||
? [...policy.requiredFields, 'roleId']
|
||||
: policy.requiredFields,
|
||||
customer: {
|
||||
roleName: customerRoleName,
|
||||
roleId: customerRoleId,
|
||||
serverZone: customerZone,
|
||||
return compareHuyaBindingRole(
|
||||
{
|
||||
roleName: task.customer_game_role,
|
||||
roleId: task.customer_game_id,
|
||||
serverZone: task.customer_game_server_zone,
|
||||
},
|
||||
platform: {
|
||||
roleName: boundRoleName,
|
||||
roleId: numericPlatformRoleUid,
|
||||
serverZone: boundZone,
|
||||
{
|
||||
isBindAccount: true,
|
||||
isBindRole: true,
|
||||
roleName: binding.bindGameRole || '',
|
||||
roleToken: platformRoleUid || roleToken,
|
||||
channel: binding.bindGameChannel || '',
|
||||
changeBindTime: 0,
|
||||
changeBindDay: 0,
|
||||
},
|
||||
})
|
||||
if (comparison.verdict === 'unknown') {
|
||||
const missing: string[] = []
|
||||
if (!customerRoleId) missing.push('客户游戏角色 UID')
|
||||
if (!customerRoleName) missing.push('客户角色名')
|
||||
if (!customerZone) missing.push('客户区服')
|
||||
if (!boundRoleName) missing.push('平台角色名')
|
||||
if (!boundZone) missing.push('平台区服')
|
||||
return {
|
||||
...base,
|
||||
verdict: 'unknown',
|
||||
message: `缺少${missing.join('、')},无法核对绑定角色,请联系客服`,
|
||||
}
|
||||
}
|
||||
if (comparison.mismatched.includes('roleId')) {
|
||||
return { ...base, verdict: 'mismatch', message: '两侧游戏角色 UID 不一致,无法提交平台绑定' }
|
||||
}
|
||||
if (comparison.mismatched.includes('roleName')) {
|
||||
return { ...base, verdict: 'mismatch', message: '两侧角色名称不一致,无法提交平台绑定' }
|
||||
}
|
||||
if (comparison.mismatched.includes('serverZone')) {
|
||||
return { ...base, verdict: 'mismatch', message: '两侧区服不一致,无法提交平台绑定' }
|
||||
}
|
||||
return {
|
||||
...base,
|
||||
verdict: 'match',
|
||||
message: numericPlatformRoleUid
|
||||
? '两侧区服、角色名称、平台角色 UID 一致,可提交平台绑定'
|
||||
: '角色名称与区服一致,请确认绑定本次待确认角色',
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
function mapBindingUpdate(session: ConnectorBindingSession) {
|
||||
@@ -1061,6 +1224,37 @@ function mapBindingUpdate(session: ConnectorBindingSession) {
|
||||
const platformGameRoleUid = isNumericBindingRoleId(session.platformGameRoleUid)
|
||||
? String(session.platformGameRoleUid || '').trim()
|
||||
: ''
|
||||
const legacyCurrentRole =
|
||||
session.bindGameRole || platformGameRoleUid || legacyRoleId
|
||||
? {
|
||||
isBindAccount: session.hasExistingBinding === true || Boolean(session.bindGameRole),
|
||||
isBindRole: session.hasExistingBinding === true || Boolean(session.bindGameRole),
|
||||
roleName: String(session.bindGameRole || ''),
|
||||
roleToken: platformGameRoleUid || String(session.bindGameRoleToken || legacyRoleId || ''),
|
||||
channel: String(session.bindGameChannel || ''),
|
||||
changeBindTime: Number(session.platformChangeBindTime || 0),
|
||||
changeBindDay: Number(session.platformChangeBindDay || 0),
|
||||
}
|
||||
: null
|
||||
const legacyPendingRole = session.pendingBindGameRole
|
||||
? {
|
||||
isBindAccount: false,
|
||||
isBindRole: false,
|
||||
roleName: String(session.pendingBindGameRole || ''),
|
||||
roleToken: String(session.pendingBindGameRoleToken || ''),
|
||||
channel: String(session.pendingBindGameChannel || ''),
|
||||
changeBindTime: Number(session.pendingChangeBindTime || 0),
|
||||
changeBindDay: Number(session.pendingChangeBindDay || 0),
|
||||
}
|
||||
: null
|
||||
const currentRole = session.currentRole === undefined ? legacyCurrentRole : session.currentRole
|
||||
const pendingRole = session.pendingRole === undefined ? legacyPendingRole : session.pendingRole
|
||||
const accountFactsObserved =
|
||||
session.currentRole !== undefined ||
|
||||
session.hasExistingBinding !== undefined ||
|
||||
Boolean(session.bindGameRole) ||
|
||||
Boolean(session.bindGameRoleToken) ||
|
||||
Boolean(platformGameRoleUid)
|
||||
return {
|
||||
status: statusMap[session.status] || 'failed',
|
||||
qrImage: String(session.qrImage || ''),
|
||||
@@ -1072,6 +1266,13 @@ function mapBindingUpdate(session: ConnectorBindingSession) {
|
||||
session.bindGameRoleToken || (isHuyaRoleToken(legacyRoleId) ? legacyRoleId : ''),
|
||||
),
|
||||
bindGameChannel: String(session.bindGameChannel || ''),
|
||||
currentRole,
|
||||
pendingRole,
|
||||
isBindAccount: currentRole?.isBindAccount === true,
|
||||
isBindRole: currentRole?.isBindRole === true,
|
||||
accountChangeBindTime: Number(currentRole?.changeBindTime || 0),
|
||||
accountChangeBindDay: Number(currentRole?.changeBindDay || 0),
|
||||
accountFactsObserved,
|
||||
pendingBindGameAccount: String(session.pendingBindGameAccount || ''),
|
||||
pendingBindGameRole: String(session.pendingBindGameRole || ''),
|
||||
pendingBindGameRoleToken: String(session.pendingBindGameRoleToken || ''),
|
||||
@@ -1088,6 +1289,7 @@ function mapBindingUpdate(session: ConnectorBindingSession) {
|
||||
rebindConfirmMessage: String(session.rebindConfirmMessage || ''),
|
||||
bindConfirmState: session.bindConfirmState || 'idle',
|
||||
bindConfirmMessage: String(session.bindConfirmMessage || ''),
|
||||
bindingEffectDeadlineAt: String(session.bindEffectDeadlineAt || ''),
|
||||
rebindCooldownDays: Number(session.rebindCooldownDays || 0),
|
||||
nextRebindAt: String(session.nextRebindAt || ''),
|
||||
platformChangeBindDay: Number(session.platformChangeBindDay || 0),
|
||||
@@ -1096,139 +1298,233 @@ function mapBindingUpdate(session: ConnectorBindingSession) {
|
||||
}
|
||||
}
|
||||
|
||||
export function deriveSemiAutoExecutionStatus(
|
||||
task: TaskRow,
|
||||
bindingStatus: BindingStatus,
|
||||
bindingDecision: HuyaBindingDecision | null,
|
||||
): ExecutionStatus {
|
||||
if (task.execution_status === 'completed' || task.execution_status === 'cancelled') {
|
||||
return task.execution_status
|
||||
}
|
||||
if (task.execution_status === 'processing') return 'processing'
|
||||
if (task.login_status !== 'authenticated') return 'waiting_customer'
|
||||
if (task.platform === 'huya') {
|
||||
return bindingDecision?.flowState === 'confirmed' ? 'waiting_operator' : 'waiting_customer'
|
||||
}
|
||||
const policy = getAccountBindingPolicy(task.platform)
|
||||
return !policy.bindingRequired || bindingStatus === 'confirmed'
|
||||
? 'waiting_operator'
|
||||
: 'waiting_customer'
|
||||
}
|
||||
|
||||
type BindingUpdateOptions = {
|
||||
eventType?: string
|
||||
eventDetail?: Record<string, unknown>
|
||||
}
|
||||
|
||||
export async function updateBindingTaskWithClient(
|
||||
client: PoolClient,
|
||||
taskId: number,
|
||||
session: ConnectorBindingSession,
|
||||
actorType: TaskActorType,
|
||||
options: BindingUpdateOptions = {},
|
||||
) {
|
||||
const mapped = mapBindingUpdate(session)
|
||||
const current = await loadTaskForUpdateWithClient(client, taskId)
|
||||
const currentDecision = resolveTaskHuyaBindingDecision(current)
|
||||
if (current.execution_status === 'completed' || current.execution_status === 'cancelled') {
|
||||
return { current, decision: currentDecision, executionStatus: current.execution_status, mapped }
|
||||
}
|
||||
|
||||
const accountFactsObserved = mapped.accountFactsObserved
|
||||
const provisional: TaskRow = {
|
||||
...current,
|
||||
binding_status: mapped.status,
|
||||
bind_game_role: mapped.bindGameRole || current.bind_game_role,
|
||||
bind_game_role_token: mapped.bindGameRoleToken || current.bind_game_role_token,
|
||||
bind_game_channel: mapped.bindGameChannel || current.bind_game_channel,
|
||||
is_bind_account: accountFactsObserved ? mapped.isBindAccount : current.is_bind_account,
|
||||
is_bind_role: accountFactsObserved ? mapped.isBindRole : current.is_bind_role,
|
||||
account_change_bind_time: accountFactsObserved
|
||||
? mapped.accountChangeBindTime
|
||||
: current.account_change_bind_time,
|
||||
account_change_bind_day: accountFactsObserved
|
||||
? mapped.accountChangeBindDay
|
||||
: current.account_change_bind_day,
|
||||
pending_bind_game_role: mapped.pendingBindGameRole,
|
||||
pending_bind_game_role_token: mapped.pendingBindGameRoleToken,
|
||||
pending_bind_game_channel: mapped.pendingBindGameChannel,
|
||||
pending_bind_game_change_bind_time: mapped.pendingBindGameChangeBindTime,
|
||||
pending_bind_game_change_bind_day: mapped.pendingBindGameChangeBindDay,
|
||||
rebind_requested: mapped.rebindRequested,
|
||||
bind_confirm_state: mapped.bindConfirmState,
|
||||
bind_confirm_message: mapped.bindConfirmMessage,
|
||||
rebind_platform_message: mapped.rebindConfirmMessage,
|
||||
binding_effect_deadline_at: mapped.bindingEffectDeadlineAt || null,
|
||||
binding_qr_issued_at:
|
||||
mapped.qrImage || mapped.qrExpiresAt
|
||||
? new Date().toISOString()
|
||||
: current.binding_qr_issued_at,
|
||||
}
|
||||
const bindingDecision = resolveTaskHuyaBindingDecision(provisional)
|
||||
const executionStatus = deriveSemiAutoExecutionStatus(current, mapped.status, bindingDecision)
|
||||
const bindingConfirmed =
|
||||
bindingDecision?.flowState === 'confirmed' ||
|
||||
(current.platform !== 'huya' && mapped.status === 'confirmed')
|
||||
const bindingFlowState =
|
||||
bindingDecision?.flowState || current.binding_flow_state || 'binding_query_required'
|
||||
|
||||
await client.query(
|
||||
`
|
||||
UPDATE semi_auto_tasks
|
||||
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_token = CASE WHEN $8 <> '' THEN $8 ELSE bind_game_role_token END,
|
||||
bind_game_channel = CASE WHEN $5 <> '' THEN $5 ELSE bind_game_channel END,
|
||||
is_bind_account = CASE WHEN $32 THEN $18 ELSE is_bind_account END,
|
||||
is_bind_role = CASE WHEN $32 THEN $19 ELSE is_bind_role END,
|
||||
account_change_bind_time = CASE WHEN $32 THEN $20 ELSE account_change_bind_time END,
|
||||
account_change_bind_day = CASE WHEN $32 THEN $21 ELSE account_change_bind_day END,
|
||||
pending_bind_game_account = $9,
|
||||
pending_bind_game_role = $10,
|
||||
pending_bind_game_role_token = $11,
|
||||
pending_bind_game_channel = $12,
|
||||
pending_bind_game_change_bind_time = $13,
|
||||
pending_bind_game_change_bind_day = $14,
|
||||
role_identity_source = CASE WHEN $15 <> '' THEN $15 ELSE role_identity_source END,
|
||||
verification_basis = CASE WHEN $16 <> '' THEN $16 ELSE verification_basis END,
|
||||
platform_game_role_uid = CASE WHEN $17 <> '' THEN $17 ELSE platform_game_role_uid END,
|
||||
binding_flow_state = CASE WHEN $34 THEN $22 ELSE binding_flow_state END,
|
||||
account_role_state = CASE WHEN $34 THEN $23 ELSE account_role_state END,
|
||||
target_role_match = CASE WHEN $34 THEN $24 ELSE target_role_match END,
|
||||
rebind_block_scope = CASE WHEN $34 THEN $25 ELSE rebind_block_scope END,
|
||||
rebind_platform_message = $26,
|
||||
rebind_requested = $27,
|
||||
bind_confirm_state = $28,
|
||||
bind_confirm_message = $29,
|
||||
binding_effect_deadline_at = $30,
|
||||
binding_qr_issued_at = CASE
|
||||
WHEN $2 = 'qr_pending' AND $31 THEN COALESCE(binding_qr_issued_at, NOW())
|
||||
WHEN $2 IN ('not_started', 'failed', 'expired') THEN NULL
|
||||
ELSE binding_qr_issued_at
|
||||
END,
|
||||
pending_role_observed_at = CASE
|
||||
WHEN $10 <> '' THEN COALESCE(pending_role_observed_at, NOW())
|
||||
ELSE NULL
|
||||
END,
|
||||
confirmed_role_observed_at = CASE
|
||||
WHEN $33 THEN COALESCE(confirmed_role_observed_at, NOW())
|
||||
ELSE confirmed_role_observed_at
|
||||
END,
|
||||
binding_started_at = CASE
|
||||
WHEN $2 = 'qr_pending' THEN COALESCE(binding_started_at, NOW())
|
||||
ELSE binding_started_at
|
||||
END,
|
||||
bound_at = CASE WHEN $33 THEN COALESCE(bound_at, NOW()) ELSE NULL END,
|
||||
execution_status = $6,
|
||||
last_error = CASE WHEN $2 IN ('failed', 'expired') THEN $7 ELSE '' END,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1
|
||||
`,
|
||||
[
|
||||
current.id,
|
||||
mapped.status,
|
||||
mapped.bindGameAccount,
|
||||
mapped.bindGameRole,
|
||||
mapped.bindGameChannel,
|
||||
executionStatus,
|
||||
mapped.message,
|
||||
mapped.bindGameRoleToken,
|
||||
mapped.pendingBindGameAccount,
|
||||
mapped.pendingBindGameRole,
|
||||
mapped.pendingBindGameRoleToken,
|
||||
mapped.pendingBindGameChannel,
|
||||
mapped.pendingBindGameChangeBindTime,
|
||||
mapped.pendingBindGameChangeBindDay,
|
||||
mapped.roleIdentitySource,
|
||||
mapped.verificationBasis,
|
||||
mapped.platformGameRoleUid,
|
||||
accountFactsObserved ? mapped.isBindAccount : current.is_bind_account,
|
||||
accountFactsObserved ? mapped.isBindRole : current.is_bind_role,
|
||||
accountFactsObserved ? mapped.accountChangeBindTime : current.account_change_bind_time,
|
||||
accountFactsObserved ? mapped.accountChangeBindDay : current.account_change_bind_day,
|
||||
bindingFlowState,
|
||||
bindingDecision?.accountRoleState || current.account_role_state,
|
||||
bindingDecision?.targetRoleMatch || current.target_role_match,
|
||||
bindingDecision?.rebindBlockScope || '',
|
||||
mapped.rebindConfirmMessage,
|
||||
mapped.rebindRequested,
|
||||
mapped.bindConfirmState,
|
||||
mapped.bindConfirmMessage,
|
||||
mapped.bindingEffectDeadlineAt || null,
|
||||
Boolean(mapped.qrImage || mapped.qrExpiresAt),
|
||||
accountFactsObserved,
|
||||
bindingConfirmed,
|
||||
current.platform === 'huya',
|
||||
],
|
||||
)
|
||||
const bindingChanged =
|
||||
mapped.status !== current.binding_status ||
|
||||
executionStatus !== current.execution_status ||
|
||||
bindingFlowState !== current.binding_flow_state ||
|
||||
mapped.rebindUnchanged ||
|
||||
mapped.rebindConfirmState === 'rejected'
|
||||
if (bindingChanged) {
|
||||
await appendTaskEvent(client, current.id, {
|
||||
eventType: options.eventType || 'binding_status_changed',
|
||||
actorType,
|
||||
fromBindingStatus: current.binding_status,
|
||||
toBindingStatus: mapped.status,
|
||||
fromExecutionStatus: current.execution_status,
|
||||
toExecutionStatus: executionStatus,
|
||||
detail: {
|
||||
...(options.eventDetail || {}),
|
||||
gameAccount: mapped.bindGameAccount,
|
||||
gameRole: mapped.bindGameRole,
|
||||
gameRoleToken: mapped.bindGameRoleToken,
|
||||
gameChannel: mapped.bindGameChannel,
|
||||
pendingGameAccount: mapped.pendingBindGameAccount,
|
||||
pendingGameRole: mapped.pendingBindGameRole,
|
||||
pendingGameRoleToken: mapped.pendingBindGameRoleToken,
|
||||
pendingGameChannel: mapped.pendingBindGameChannel,
|
||||
roleIdentitySource: mapped.roleIdentitySource,
|
||||
verificationBasis: mapped.verificationBasis,
|
||||
verdict: bindingDecision?.targetRoleMatch || 'unknown',
|
||||
bindingFlowState,
|
||||
accountRoleState: bindingDecision?.accountRoleState || 'unknown',
|
||||
primaryAction: bindingDecision?.primaryAction || 'query_binding',
|
||||
rebindBlockScope: bindingDecision?.rebindBlockScope || '',
|
||||
accountRebindAvailableAt: bindingDecision?.accountRebindAvailableAt || '',
|
||||
targetRoleRebindAvailableAt: bindingDecision?.targetRoleRebindAvailableAt || '',
|
||||
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 { current, decision: bindingDecision, executionStatus, mapped }
|
||||
}
|
||||
|
||||
export async function updateBindingTask(
|
||||
task: TaskRow,
|
||||
session: ConnectorBindingSession,
|
||||
actorType: TaskActorType,
|
||||
) {
|
||||
const mapped = mapBindingUpdate(session)
|
||||
const comparisonRole = mapped.pendingBindGameRole
|
||||
? {
|
||||
bindGameRole: mapped.pendingBindGameRole,
|
||||
bindGameRoleToken: mapped.pendingBindGameRoleToken,
|
||||
bindGameChannel: mapped.pendingBindGameChannel,
|
||||
platformGameRoleUid: '',
|
||||
}
|
||||
: {
|
||||
bindGameRole: mapped.bindGameRole,
|
||||
bindGameRoleToken: mapped.bindGameRoleToken,
|
||||
bindGameChannel: mapped.bindGameChannel,
|
||||
platformGameRoleUid: mapped.platformGameRoleUid,
|
||||
}
|
||||
const roleIdVerified = isNumericBindingRoleId(mapped.platformGameRoleUid)
|
||||
const requiresSupport =
|
||||
getAccountBindingPolicy(task.platform).requiresCustomerProfile &&
|
||||
mapped.hasExistingBinding === true &&
|
||||
!mapped.bindGameRole
|
||||
const comparison = await withTransaction(async (client) => {
|
||||
const current = await loadTaskForUpdateWithClient(client, task.id)
|
||||
const bindingPolicy = getAccountBindingPolicy(current.platform)
|
||||
const currentComparison: BindingRoleComparison = bindingPolicy.requiresCustomerProfile
|
||||
? compareBindingRole(current, comparisonRole)
|
||||
: {
|
||||
verdict: 'match',
|
||||
customerRoleName: '',
|
||||
customerRoleId: '',
|
||||
customerZone: '',
|
||||
boundRoleName: comparisonRole.bindGameRole || '',
|
||||
boundRoleId: comparisonRole.bindGameRoleToken || '',
|
||||
boundRoleIdKind: comparisonRole.bindGameRoleToken ? 'huya_role_token' : 'missing',
|
||||
boundZone: comparisonRole.bindGameChannel || '',
|
||||
verificationBasis: 'manual',
|
||||
message: '平台角色绑定状态已确认',
|
||||
}
|
||||
if (current.execution_status === 'completed' || current.execution_status === 'cancelled') {
|
||||
return currentComparison
|
||||
}
|
||||
const executionStatus: ExecutionStatus =
|
||||
mapped.status === 'confirmed' ? 'waiting_operator' : 'waiting_customer'
|
||||
await client.query(
|
||||
`
|
||||
UPDATE semi_auto_tasks
|
||||
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_token = CASE WHEN $8 <> '' THEN $8 ELSE bind_game_role_token END,
|
||||
bind_game_channel = CASE WHEN $5 <> '' THEN $5 ELSE bind_game_channel END,
|
||||
pending_bind_game_account = $9,
|
||||
pending_bind_game_role = $10,
|
||||
pending_bind_game_role_token = $11,
|
||||
pending_bind_game_channel = $12,
|
||||
pending_bind_game_change_bind_time = $13,
|
||||
pending_bind_game_change_bind_day = $14,
|
||||
role_identity_source = CASE WHEN $15 <> '' THEN $15 ELSE role_identity_source END,
|
||||
verification_basis = CASE WHEN $16 <> '' THEN $16 ELSE verification_basis END,
|
||||
platform_game_role_uid = CASE WHEN $17 <> '' THEN $17 ELSE platform_game_role_uid END,
|
||||
binding_started_at = CASE WHEN $2 = 'qr_pending' THEN COALESCE(binding_started_at, NOW()) ELSE binding_started_at END,
|
||||
bound_at = CASE WHEN $2 IN ('role_ready', 'confirmed') THEN COALESCE(bound_at, NOW()) ELSE bound_at END,
|
||||
execution_status = $6,
|
||||
last_error = CASE WHEN $2 IN ('failed', 'expired') THEN $7 ELSE '' END,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1
|
||||
`,
|
||||
[
|
||||
current.id,
|
||||
mapped.status,
|
||||
mapped.bindGameAccount,
|
||||
mapped.bindGameRole,
|
||||
mapped.bindGameChannel,
|
||||
executionStatus,
|
||||
mapped.message,
|
||||
mapped.bindGameRoleToken,
|
||||
mapped.pendingBindGameAccount,
|
||||
mapped.pendingBindGameRole,
|
||||
mapped.pendingBindGameRoleToken,
|
||||
mapped.pendingBindGameChannel,
|
||||
mapped.pendingBindGameChangeBindTime,
|
||||
mapped.pendingBindGameChangeBindDay,
|
||||
mapped.roleIdentitySource,
|
||||
mapped.verificationBasis,
|
||||
mapped.platformGameRoleUid,
|
||||
],
|
||||
)
|
||||
// 轮询会每 2 秒调用一次:只有状态/执行状态变化,或换绑被拒这类关键信号才写事件。
|
||||
const bindingChanged =
|
||||
mapped.status !== current.binding_status ||
|
||||
executionStatus !== current.execution_status ||
|
||||
mapped.rebindUnchanged ||
|
||||
mapped.rebindConfirmState === 'rejected'
|
||||
if (bindingChanged) {
|
||||
await appendTaskEvent(client, current.id, {
|
||||
eventType: 'binding_status_changed',
|
||||
actorType,
|
||||
fromBindingStatus: current.binding_status,
|
||||
toBindingStatus: mapped.status,
|
||||
fromExecutionStatus: current.execution_status,
|
||||
toExecutionStatus: executionStatus,
|
||||
detail: {
|
||||
gameAccount: mapped.bindGameAccount,
|
||||
gameRole: mapped.bindGameRole,
|
||||
gameRoleToken: mapped.bindGameRoleToken,
|
||||
gameChannel: mapped.bindGameChannel,
|
||||
pendingGameAccount: mapped.pendingBindGameAccount,
|
||||
pendingGameRole: mapped.pendingBindGameRole,
|
||||
pendingGameRoleToken: mapped.pendingBindGameRoleToken,
|
||||
pendingGameChannel: mapped.pendingBindGameChannel,
|
||||
roleIdentitySource: mapped.roleIdentitySource,
|
||||
verificationBasis: mapped.verificationBasis,
|
||||
verdict: currentComparison.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 currentComparison
|
||||
})
|
||||
const result = await withTransaction((client) =>
|
||||
updateBindingTaskWithClient(client, task.id, session, actorType),
|
||||
)
|
||||
publishSemiAutoTaskRealtimeChange(task.id, task.order_id)
|
||||
const updated = await loadTask(task.id)
|
||||
const mapped = result.mapped
|
||||
return {
|
||||
status: mapped.status,
|
||||
qrImage: mapped.qrImage,
|
||||
@@ -1239,6 +1535,8 @@ export async function updateBindingTask(
|
||||
bindGameRoleId: '',
|
||||
bindGameRoleToken: mapped.bindGameRoleToken,
|
||||
bindGameChannel: mapped.bindGameChannel,
|
||||
isBindAccount: mapped.isBindAccount,
|
||||
isBindRole: mapped.isBindRole,
|
||||
pendingBindGameAccount: mapped.pendingBindGameAccount,
|
||||
pendingBindGameRole: mapped.pendingBindGameRole,
|
||||
pendingBindGameRoleToken: mapped.pendingBindGameRoleToken,
|
||||
@@ -1248,8 +1546,8 @@ export async function updateBindingTask(
|
||||
pendingChangeBindDay: mapped.pendingBindGameChangeBindDay,
|
||||
roleIdentitySource: mapped.roleIdentitySource,
|
||||
verificationBasis: mapped.verificationBasis,
|
||||
roleIdVerified,
|
||||
requiresSupport,
|
||||
roleIdVerified: isNumericBindingRoleId(mapped.platformGameRoleUid),
|
||||
requiresSupport: result.decision?.requiresSupport === true,
|
||||
hasExistingBinding: mapped.hasExistingBinding,
|
||||
rebindRequested: mapped.rebindRequested,
|
||||
rebindUnchanged: mapped.rebindUnchanged,
|
||||
@@ -1262,6 +1560,21 @@ export async function updateBindingTask(
|
||||
platformChangeBindDay: mapped.platformChangeBindDay,
|
||||
platformChangeBindTime: mapped.platformChangeBindTime,
|
||||
message: mapped.message,
|
||||
comparison,
|
||||
comparison: result.decision?.comparison || {
|
||||
verdict: 'unknown',
|
||||
customerRoleName: '',
|
||||
customerRoleId: '',
|
||||
customerZone: '',
|
||||
boundRoleName: '',
|
||||
boundRoleId: '',
|
||||
boundRoleIdKind: 'missing',
|
||||
boundZone: '',
|
||||
verificationBasis: 'manual',
|
||||
message: '当前不是虎牙绑定任务',
|
||||
missing: [],
|
||||
mismatched: [],
|
||||
},
|
||||
bindingDecision: result.decision,
|
||||
bindingFlowState: result.decision?.flowState || updated.binding_flow_state,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -322,7 +322,9 @@ test(
|
||||
bindGameAccount: '集成测试虎牙账号',
|
||||
bindGameRole: '集成测试角色',
|
||||
bindGameRoleToken: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
|
||||
bindGameChannel: '安卓(android) · QQ',
|
||||
bindGameChannel: '安卓(android) · 微信',
|
||||
isBindAccount: true,
|
||||
isBindRole: true,
|
||||
roleIdentitySource: 'huya_outer_current',
|
||||
verificationBasis: 'role_name_zone',
|
||||
},
|
||||
@@ -380,6 +382,39 @@ test(
|
||||
role_identity_source: 'huya_outer_current',
|
||||
verification_basis: 'role_name_zone',
|
||||
})
|
||||
|
||||
const staleConfirmEventId = randomUUID()
|
||||
await applySemiAutoTaskStateSnapshot(
|
||||
{
|
||||
eventId: staleConfirmEventId,
|
||||
taskId,
|
||||
orderNo,
|
||||
loginStatus: 'authenticated',
|
||||
bindingStatus: 'confirmed',
|
||||
huyaUid: `it-huya-${suffix}`,
|
||||
bindGameAccount: '集成测试虎牙账号',
|
||||
bindGameRole: '错误角色',
|
||||
bindGameRoleToken: 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb',
|
||||
bindGameChannel: '安卓(android) · 微信',
|
||||
isBindAccount: true,
|
||||
isBindRole: true,
|
||||
roleIdentitySource: 'huya_outer_current',
|
||||
verificationBasis: 'role_name_zone',
|
||||
},
|
||||
{ eventId: staleConfirmEventId, eventType: 'semi_auto.task_state' },
|
||||
)
|
||||
const decisionGated = await query<{
|
||||
execution_status: string
|
||||
binding_flow_state: string
|
||||
}>(
|
||||
`SELECT execution_status, binding_flow_state
|
||||
FROM semi_auto_tasks WHERE id = $1`,
|
||||
[taskId],
|
||||
)
|
||||
assert.deepEqual(decisionGated.rows[0], {
|
||||
execution_status: 'waiting_customer',
|
||||
binding_flow_state: 'rebind_required',
|
||||
})
|
||||
} finally {
|
||||
if (orderId > 0) {
|
||||
await query('DELETE FROM order_source_snapshots WHERE order_id = $1', [orderId])
|
||||
|
||||
Reference in New Issue
Block a user