修复(半自动履约): 收口虎牙确认恢复与任务切换
This commit is contained in:
@@ -0,0 +1,165 @@
|
||||
-- 178_semi_auto_huya_lifecycle_hardening.sql
|
||||
--
|
||||
-- 1. Connector 状态快照增加任务级单调版本,拒绝乱序旧快照覆盖新事实。
|
||||
-- 2. 同一订单项允许多条历史任务,但只允许一条非取消任务。
|
||||
-- 3. 重新按客户资料核对历史 waiting_operator 任务,错误的 confirmed 不再占用客服待办。
|
||||
|
||||
ALTER TABLE semi_auto_tasks
|
||||
ADD COLUMN IF NOT EXISTS connector_state_version BIGINT NOT NULL DEFAULT 0;
|
||||
|
||||
ALTER TABLE semi_auto_tasks
|
||||
DROP CONSTRAINT IF EXISTS semi_auto_tasks_order_item_id_key;
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uq_semi_auto_tasks_active_order_item
|
||||
ON semi_auto_tasks (order_item_id)
|
||||
WHERE execution_status <> 'cancelled';
|
||||
|
||||
WITH evaluated AS (
|
||||
SELECT
|
||||
task.id,
|
||||
task.execution_status,
|
||||
task.binding_status,
|
||||
BTRIM(task.customer_game_role_name) AS customer_role_name,
|
||||
BTRIM(task.customer_game_server_zone) AS customer_zone,
|
||||
LOWER(REGEXP_REPLACE(COALESCE(task.customer_game_role_name, ''), '\s+', '', 'g'))
|
||||
AS normalized_customer_role,
|
||||
LOWER(REGEXP_REPLACE(COALESCE(task.bind_game_role, ''), '\s+', '', 'g'))
|
||||
AS normalized_bound_role,
|
||||
CASE
|
||||
WHEN LOWER(REGEXP_REPLACE(COALESCE(task.bind_game_channel, ''), '\s+', '', 'g'))
|
||||
~ '(苹果|ios)'
|
||||
AND LOWER(REGEXP_REPLACE(COALESCE(task.bind_game_channel, ''), '\s+', '', 'g'))
|
||||
~ '(qq|q区|手q)' THEN '苹果Q区'
|
||||
WHEN LOWER(REGEXP_REPLACE(COALESCE(task.bind_game_channel, ''), '\s+', '', 'g'))
|
||||
~ '(苹果|ios)'
|
||||
AND LOWER(REGEXP_REPLACE(COALESCE(task.bind_game_channel, ''), '\s+', '', 'g'))
|
||||
~ '(微信|wechat|v区)' THEN '苹果V区'
|
||||
WHEN LOWER(REGEXP_REPLACE(COALESCE(task.bind_game_channel, ''), '\s+', '', 'g'))
|
||||
~ '(安卓|android)'
|
||||
AND LOWER(REGEXP_REPLACE(COALESCE(task.bind_game_channel, ''), '\s+', '', 'g'))
|
||||
~ '(qq|q区|手q)' THEN '安卓Q区'
|
||||
WHEN LOWER(REGEXP_REPLACE(COALESCE(task.bind_game_channel, ''), '\s+', '', 'g'))
|
||||
~ '(安卓|android)'
|
||||
AND LOWER(REGEXP_REPLACE(COALESCE(task.bind_game_channel, ''), '\s+', '', 'g'))
|
||||
~ '(微信|wechat|v区)' THEN '安卓V区'
|
||||
ELSE ''
|
||||
END AS resolved_zone
|
||||
FROM semi_auto_tasks task
|
||||
WHERE task.platform = 'huya'
|
||||
AND task.execution_status = 'waiting_operator'
|
||||
AND task.binding_status = 'confirmed'
|
||||
),
|
||||
repairs AS (
|
||||
SELECT
|
||||
evaluated.*,
|
||||
CASE
|
||||
WHEN customer_role_name = ''
|
||||
OR customer_zone = ''
|
||||
OR resolved_zone = '' THEN 'manual_review'
|
||||
ELSE 'rebind_required'
|
||||
END AS next_binding_flow_state,
|
||||
CASE
|
||||
WHEN customer_role_name = ''
|
||||
OR customer_zone = ''
|
||||
OR resolved_zone = '' THEN 'unknown'
|
||||
ELSE 'mismatch'
|
||||
END AS next_target_role_match
|
||||
FROM evaluated
|
||||
WHERE customer_role_name = ''
|
||||
OR customer_zone = ''
|
||||
OR resolved_zone = ''
|
||||
OR normalized_customer_role <> normalized_bound_role
|
||||
OR customer_zone <> resolved_zone
|
||||
)
|
||||
INSERT INTO semi_auto_task_events (
|
||||
task_id,
|
||||
event_type,
|
||||
actor_type,
|
||||
actor_id,
|
||||
from_binding_status,
|
||||
to_binding_status,
|
||||
from_execution_status,
|
||||
to_execution_status,
|
||||
detail_json,
|
||||
created_at
|
||||
)
|
||||
SELECT
|
||||
id,
|
||||
'huya_binding_confirmed_reaudited',
|
||||
'system',
|
||||
'',
|
||||
binding_status,
|
||||
binding_status,
|
||||
execution_status,
|
||||
'waiting_customer',
|
||||
JSONB_BUILD_OBJECT(
|
||||
'reason', 'confirmed_requires_customer_role_match',
|
||||
'bindingFlowState', next_binding_flow_state,
|
||||
'targetRoleMatch', next_target_role_match
|
||||
),
|
||||
NOW()
|
||||
FROM repairs;
|
||||
|
||||
WITH evaluated AS (
|
||||
SELECT
|
||||
task.id,
|
||||
BTRIM(task.customer_game_role_name) AS customer_role_name,
|
||||
BTRIM(task.customer_game_server_zone) AS customer_zone,
|
||||
LOWER(REGEXP_REPLACE(COALESCE(task.customer_game_role_name, ''), '\s+', '', 'g'))
|
||||
AS normalized_customer_role,
|
||||
LOWER(REGEXP_REPLACE(COALESCE(task.bind_game_role, ''), '\s+', '', 'g'))
|
||||
AS normalized_bound_role,
|
||||
CASE
|
||||
WHEN LOWER(REGEXP_REPLACE(COALESCE(task.bind_game_channel, ''), '\s+', '', 'g'))
|
||||
~ '(苹果|ios)'
|
||||
AND LOWER(REGEXP_REPLACE(COALESCE(task.bind_game_channel, ''), '\s+', '', 'g'))
|
||||
~ '(qq|q区|手q)' THEN '苹果Q区'
|
||||
WHEN LOWER(REGEXP_REPLACE(COALESCE(task.bind_game_channel, ''), '\s+', '', 'g'))
|
||||
~ '(苹果|ios)'
|
||||
AND LOWER(REGEXP_REPLACE(COALESCE(task.bind_game_channel, ''), '\s+', '', 'g'))
|
||||
~ '(微信|wechat|v区)' THEN '苹果V区'
|
||||
WHEN LOWER(REGEXP_REPLACE(COALESCE(task.bind_game_channel, ''), '\s+', '', 'g'))
|
||||
~ '(安卓|android)'
|
||||
AND LOWER(REGEXP_REPLACE(COALESCE(task.bind_game_channel, ''), '\s+', '', 'g'))
|
||||
~ '(qq|q区|手q)' THEN '安卓Q区'
|
||||
WHEN LOWER(REGEXP_REPLACE(COALESCE(task.bind_game_channel, ''), '\s+', '', 'g'))
|
||||
~ '(安卓|android)'
|
||||
AND LOWER(REGEXP_REPLACE(COALESCE(task.bind_game_channel, ''), '\s+', '', 'g'))
|
||||
~ '(微信|wechat|v区)' THEN '安卓V区'
|
||||
ELSE ''
|
||||
END AS resolved_zone
|
||||
FROM semi_auto_tasks task
|
||||
WHERE task.platform = 'huya'
|
||||
AND task.execution_status = 'waiting_operator'
|
||||
AND task.binding_status = 'confirmed'
|
||||
)
|
||||
UPDATE semi_auto_tasks task
|
||||
SET binding_flow_state = CASE
|
||||
WHEN evaluated.customer_role_name = ''
|
||||
OR evaluated.customer_zone = ''
|
||||
OR evaluated.resolved_zone = '' THEN 'manual_review'
|
||||
ELSE 'rebind_required'
|
||||
END,
|
||||
target_role_match = CASE
|
||||
WHEN evaluated.customer_role_name = ''
|
||||
OR evaluated.customer_zone = ''
|
||||
OR evaluated.resolved_zone = '' THEN 'unknown'
|
||||
ELSE 'mismatch'
|
||||
END,
|
||||
execution_status = 'waiting_customer',
|
||||
bound_at = NULL,
|
||||
updated_at = NOW()
|
||||
FROM evaluated
|
||||
WHERE task.id = evaluated.id
|
||||
AND (
|
||||
evaluated.customer_role_name = ''
|
||||
OR evaluated.customer_zone = ''
|
||||
OR evaluated.resolved_zone = ''
|
||||
OR evaluated.normalized_customer_role <> evaluated.normalized_bound_role
|
||||
OR evaluated.customer_zone <> evaluated.resolved_zone
|
||||
);
|
||||
|
||||
COMMENT ON COLUMN semi_auto_tasks.connector_state_version IS
|
||||
'外部 Connector 状态快照的任务级单调版本;旧版本不得覆盖新版本';
|
||||
COMMENT ON INDEX uq_semi_auto_tasks_active_order_item IS
|
||||
'同一订单项最多一条非取消半自动任务;取消任务作为可审计历史保留';
|
||||
@@ -24,7 +24,10 @@ import {
|
||||
parseManualChannelQuantity,
|
||||
} from './manual-credit-quantity.js'
|
||||
import { productSourceFilterSql } from './cost-center-mappers.js'
|
||||
import { ensureSemiAutoTasksForOrderItems } from '../semi-auto/semi-auto-task-service.js'
|
||||
import {
|
||||
ensureSemiAutoTasksForOrderItems,
|
||||
reconcileSemiAutoTasksForManualConfig,
|
||||
} from '../semi-auto/semi-auto-task-service.js'
|
||||
|
||||
/**
|
||||
* 人工履约 SKU 配置服务。
|
||||
@@ -632,6 +635,7 @@ export async function saveManualFulfillmentConfig(payload: JsonObject) {
|
||||
dateFrom: shiftDate(today, -29),
|
||||
dateTo: today,
|
||||
})
|
||||
await reconcileSemiAutoTasksForManualConfig(config.id)
|
||||
return {
|
||||
...mapManualConfig(config, unitPrices),
|
||||
syncSummary: {
|
||||
|
||||
@@ -251,6 +251,78 @@ test('绑定标志不一致时统一进入客服人工核实', () => {
|
||||
assert.equal(decision.primaryAction, 'contact_support')
|
||||
})
|
||||
|
||||
test('首次绑定被平台受理后即使尚未出现 current 角色也保持等待生效', () => {
|
||||
const pending = role({
|
||||
isBindAccount: false,
|
||||
isBindRole: false,
|
||||
roleName: TARGET.roleName,
|
||||
roleToken: 'eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee',
|
||||
})
|
||||
const decision = resolveHuyaBindingDecision(
|
||||
input({
|
||||
pending,
|
||||
bindingStatus: 'scanned',
|
||||
bindConfirmState: 'accepted',
|
||||
bindingEffectDeadlineAt: new Date(NOW + 60_000).toISOString(),
|
||||
}),
|
||||
)
|
||||
assert.equal(decision.flowState, 'rebind_effect_pending')
|
||||
assert.equal(decision.canConfirmBinding, false)
|
||||
assert.equal(decision.canCompleteTask, false)
|
||||
})
|
||||
|
||||
test('首次绑定回查 current 与 pending 一致后才收敛为 confirmed', () => {
|
||||
const pending = role({
|
||||
isBindAccount: false,
|
||||
isBindRole: false,
|
||||
roleName: TARGET.roleName,
|
||||
roleToken: 'eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee',
|
||||
})
|
||||
const decision = resolveHuyaBindingDecision(
|
||||
input({
|
||||
current: role({
|
||||
roleName: TARGET.roleName,
|
||||
roleToken: 'eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee',
|
||||
channel: '安卓(android) · 微信',
|
||||
}),
|
||||
pending,
|
||||
bindingStatus: 'scanned',
|
||||
bindConfirmState: 'accepted',
|
||||
bindingEffectDeadlineAt: new Date(NOW + 60_000).toISOString(),
|
||||
}),
|
||||
)
|
||||
assert.equal(decision.flowState, 'confirmed')
|
||||
assert.equal(decision.canCompleteTask, true)
|
||||
})
|
||||
|
||||
test('确认写平台超时后不能永久卡在提交中', () => {
|
||||
const pending = role({
|
||||
isBindAccount: false,
|
||||
isBindRole: false,
|
||||
roleName: TARGET.roleName,
|
||||
roleToken: 'eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee',
|
||||
})
|
||||
const waiting = resolveHuyaBindingDecision(
|
||||
input({
|
||||
pending,
|
||||
bindingStatus: 'scanned',
|
||||
bindConfirmState: 'submitting',
|
||||
bindingEffectDeadlineAt: new Date(NOW + 60_000).toISOString(),
|
||||
}),
|
||||
)
|
||||
assert.equal(waiting.flowState, 'rebind_effect_pending')
|
||||
|
||||
const timedOut = resolveHuyaBindingDecision(
|
||||
input({
|
||||
pending,
|
||||
bindingStatus: 'scanned',
|
||||
bindConfirmState: 'submitting',
|
||||
bindingEffectDeadlineAt: new Date(NOW - 1).toISOString(),
|
||||
}),
|
||||
)
|
||||
assert.equal(timedOut.flowState, 'rebind_effect_failed')
|
||||
})
|
||||
|
||||
test('冷却计算和目标匹配器保持唯一实现', () => {
|
||||
const availability = resolveHuyaRoleRebindAvailability(
|
||||
role({
|
||||
|
||||
@@ -462,6 +462,53 @@ export function resolveHuyaBindingDecision(input: HuyaBindingDecisionInput): Huy
|
||||
})
|
||||
}
|
||||
|
||||
const confirmationInFlight =
|
||||
Boolean(input.pending) &&
|
||||
(input.bindConfirmState === 'submitting' || input.bindConfirmState === 'accepted')
|
||||
if (confirmationInFlight) {
|
||||
if (
|
||||
flow === 'confirmed' ||
|
||||
(base.accountRoleState === 'bound' &&
|
||||
base.currentComparison?.verdict === 'match' &&
|
||||
base.pendingComparison?.verdict === 'match')
|
||||
) {
|
||||
return decision(input, base, {
|
||||
flowState: 'confirmed',
|
||||
primaryAction: 'none',
|
||||
allowedActions: actions('none'),
|
||||
message: '目标角色已绑定,等待客服处理',
|
||||
})
|
||||
}
|
||||
const deadlineMs = Date.parse(input.bindingEffectDeadlineAt || '')
|
||||
const deadlineValid = Number.isFinite(deadlineMs)
|
||||
const deadlineExpired = deadlineValid && nowMs >= deadlineMs
|
||||
if (input.bindConfirmState === 'submitting' && deadlineValid && !deadlineExpired) {
|
||||
return decision(input, base, {
|
||||
flowState: 'rebind_effect_pending',
|
||||
primaryAction: 'refresh_binding_status',
|
||||
allowedActions: actions('refresh_binding_status'),
|
||||
message: '绑定确认已提交,正在回查虎牙平台状态',
|
||||
})
|
||||
}
|
||||
if (input.bindConfirmState === 'accepted' && deadlineValid && !deadlineExpired) {
|
||||
return decision(input, base, {
|
||||
flowState: 'rebind_effect_pending',
|
||||
primaryAction: 'refresh_binding_status',
|
||||
allowedActions: actions('refresh_binding_status'),
|
||||
message: '虎牙已受理绑定,正在等待目标角色生效',
|
||||
})
|
||||
}
|
||||
return decision(input, base, {
|
||||
flowState: 'rebind_effect_failed',
|
||||
primaryAction: 'start_rebind',
|
||||
allowedActions: actions('start_rebind', 'edit_profile', 'contact_support'),
|
||||
message:
|
||||
input.bindConfirmState === 'submitting'
|
||||
? '绑定提交超时且未回查到目标角色,请重新扫码选择角色'
|
||||
: '虎牙已受理绑定,但目标角色未生效,请重新扫码选择角色',
|
||||
})
|
||||
}
|
||||
|
||||
if (base.accountRoleState === 'bound') {
|
||||
if (base.currentComparison?.verdict === 'match') {
|
||||
if (flow === 'confirmed') {
|
||||
|
||||
@@ -471,6 +471,20 @@ export async function applySemiAutoTaskStateSnapshot(
|
||||
BINDING_STATUSES,
|
||||
'绑定状态',
|
||||
)
|
||||
const stateVersionRaw = input.stateVersion ?? input.state_version
|
||||
const stateVersion = Number(stateVersionRaw)
|
||||
if (
|
||||
stateVersionRaw === undefined ||
|
||||
stateVersionRaw === null ||
|
||||
String(stateVersionRaw).trim() === '' ||
|
||||
!Number.isSafeInteger(stateVersion) ||
|
||||
stateVersion <= 0
|
||||
) {
|
||||
throw createHttpError('状态快照版本必须为正整数', {
|
||||
statusCode: 400,
|
||||
errorCode: 'semi_auto_snapshot_state_version_required',
|
||||
})
|
||||
}
|
||||
if (!eventId) {
|
||||
throw createHttpError('状态快照事件编号不能为空', {
|
||||
statusCode: 400,
|
||||
@@ -498,6 +512,9 @@ export async function applySemiAutoTaskStateSnapshot(
|
||||
if (task.execution_status === 'completed' || task.execution_status === 'cancelled') {
|
||||
return { applied: false, terminal: true }
|
||||
}
|
||||
if (stateVersion <= Number(task.connector_state_version || 0)) {
|
||||
return { applied: false, stale: true, stateVersion }
|
||||
}
|
||||
|
||||
const uid = String(input.huyaUid ?? input.huya_uid ?? '').trim()
|
||||
const nickname = String(input.platformNickname ?? input.platform_nickname ?? '').trim()
|
||||
@@ -682,9 +699,10 @@ export async function applySemiAutoTaskStateSnapshot(
|
||||
ELSE authenticated_at
|
||||
END,
|
||||
last_error = CASE WHEN $2 IN ('failed', 'expired') THEN $5 ELSE last_error END,
|
||||
connector_state_version = $6,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1`,
|
||||
[task.id, loginStatus, uid, nickname, message],
|
||||
[task.id, loginStatus, uid, nickname, message, stateVersion],
|
||||
)
|
||||
if (
|
||||
loginStatus !== task.login_status ||
|
||||
@@ -718,6 +736,7 @@ export async function applySemiAutoTaskStateSnapshot(
|
||||
terminal: false,
|
||||
taskId: task.id,
|
||||
orderId: task.order_id,
|
||||
stateVersion,
|
||||
executionStatus: bindingResult.executionStatus,
|
||||
}
|
||||
})
|
||||
|
||||
@@ -37,6 +37,7 @@ import {
|
||||
getBindingForTask,
|
||||
getLoginSessionForTask,
|
||||
hasCustomerProfile,
|
||||
isHuyaBindingConfirmationInFlight,
|
||||
isTaskBindingConfirmed,
|
||||
loadTask,
|
||||
loadTaskForOrder,
|
||||
@@ -558,6 +559,32 @@ export async function startPublicBinding(
|
||||
}
|
||||
|
||||
const forceRebind = wantsRebind || decision.flowState.startsWith('rebind_')
|
||||
if (forceRebind && isHuyaBindingConfirmationInFlight(inspectedTask)) {
|
||||
await withTransaction(async (client) => {
|
||||
const current = await loadTaskForUpdateWithClient(client, task.id)
|
||||
if (!isHuyaBindingConfirmationInFlight(current)) return
|
||||
await client.query(
|
||||
`
|
||||
UPDATE semi_auto_tasks
|
||||
SET bind_confirm_state = 'idle',
|
||||
bind_confirm_message = '',
|
||||
binding_effect_deadline_at = NULL,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1
|
||||
`,
|
||||
[current.id],
|
||||
)
|
||||
await appendTaskEvent(client, current.id, {
|
||||
eventType: 'huya_binding_retry_started',
|
||||
actorType: 'customer',
|
||||
fromBindingStatus: current.binding_status,
|
||||
toBindingStatus: current.binding_status,
|
||||
fromExecutionStatus: current.execution_status,
|
||||
toExecutionStatus: current.execution_status,
|
||||
detail: { previousBindConfirmState: current.bind_confirm_state },
|
||||
})
|
||||
})
|
||||
}
|
||||
let session: ConnectorBindingSession
|
||||
try {
|
||||
session = await startHuyaBinding(task.connector_session_id, task.connector_mode, {
|
||||
@@ -716,6 +743,65 @@ export async function pollPublicBinding(orderNoInput: unknown, taskIdInput: unkn
|
||||
return { task: mapTask(updated), binding }
|
||||
}
|
||||
|
||||
async function markHuyaBindingConfirmationSubmitting(input: {
|
||||
taskId: number
|
||||
actorType: TaskActorType
|
||||
expectedRoleName: string
|
||||
expectedRoleToken: string
|
||||
expectedRoleChannel: string
|
||||
}) {
|
||||
return withTransaction(async (client) => {
|
||||
const current = await loadTaskForUpdateWithClient(client, input.taskId)
|
||||
if (current.execution_status === 'completed' || current.execution_status === 'cancelled') {
|
||||
throw createHttpError('当前订单已结束,不能确认绑定', {
|
||||
statusCode: 409,
|
||||
errorCode: 'semi_auto_task_closed',
|
||||
})
|
||||
}
|
||||
if (isHuyaBindingConfirmationInFlight(current)) return { alreadyInFlight: true }
|
||||
const pendingRole = resolveTaskHuyaBindingDecision(current)?.pendingRoleComparison
|
||||
const pendingName = String(current.pending_bind_game_role || '').trim()
|
||||
const pendingToken = String(current.pending_bind_game_role_token || '').trim()
|
||||
const pendingChannel = String(current.pending_bind_game_channel || '').trim()
|
||||
if (
|
||||
!pendingRole ||
|
||||
pendingName !== input.expectedRoleName ||
|
||||
pendingChannel !== input.expectedRoleChannel ||
|
||||
(input.expectedRoleToken && pendingToken !== input.expectedRoleToken)
|
||||
) {
|
||||
throw createHttpError('待确认角色已变化,请重新核对后再提交', {
|
||||
statusCode: 409,
|
||||
errorCode: 'huya_bind_pending_role_changed',
|
||||
})
|
||||
}
|
||||
await client.query(
|
||||
`
|
||||
UPDATE semi_auto_tasks
|
||||
SET bind_confirm_state = 'submitting',
|
||||
bind_confirm_message = '',
|
||||
binding_effect_deadline_at = NOW() + INTERVAL '60 seconds',
|
||||
updated_at = NOW()
|
||||
WHERE id = $1
|
||||
`,
|
||||
[current.id],
|
||||
)
|
||||
await appendTaskEvent(client, current.id, {
|
||||
eventType: 'huya_binding_confirm_submitted',
|
||||
actorType: input.actorType,
|
||||
fromBindingStatus: current.binding_status,
|
||||
toBindingStatus: current.binding_status,
|
||||
fromExecutionStatus: current.execution_status,
|
||||
toExecutionStatus: current.execution_status,
|
||||
detail: {
|
||||
roleName: input.expectedRoleName,
|
||||
roleToken: input.expectedRoleToken,
|
||||
roleChannel: input.expectedRoleChannel,
|
||||
},
|
||||
})
|
||||
return { alreadyInFlight: false }
|
||||
})
|
||||
}
|
||||
|
||||
export async function confirmPublicBinding(
|
||||
orderNoInput: unknown,
|
||||
taskIdInput: unknown,
|
||||
@@ -728,6 +814,9 @@ export async function confirmPublicBinding(
|
||||
const orderNo = normalizeOrderNo(orderNoInput)
|
||||
const taskId = normalizeId(taskIdInput)
|
||||
const task = await ensureConnectorSessionForTask(await loadTaskForOrder(orderNo, taskId))
|
||||
const expectedRoleName = String(options.expectedRoleName || '').trim()
|
||||
const expectedRoleToken = String(options.expectedRoleToken || '').trim()
|
||||
const expectedRoleChannel = String(options.expectedRoleChannel || '').trim()
|
||||
const bindingPolicy = getAccountBindingPolicy(task.platform)
|
||||
if (bindingPolicy.confirmationMode !== 'customer_match') {
|
||||
throw createHttpError('当前平台由平台事实直接确认绑定,无需客户提交', {
|
||||
@@ -748,6 +837,12 @@ export async function confirmPublicBinding(
|
||||
})
|
||||
}
|
||||
assertCustomerProfileReady(task)
|
||||
if (isHuyaBindingConfirmationInFlight(task)) {
|
||||
const session = await getBindingForTask(task, task.connector_session_id)
|
||||
const binding = await updateBindingTask(task, session, 'customer')
|
||||
const updated = await loadTask(task.id)
|
||||
return { task: mapTask(updated), binding }
|
||||
}
|
||||
const session =
|
||||
task.platform === 'huya'
|
||||
? await getHuyaBindingSnapshot(task.connector_session_id, task.connector_mode)
|
||||
@@ -768,9 +863,6 @@ export async function confirmPublicBinding(
|
||||
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,
|
||||
@@ -791,12 +883,33 @@ export async function confirmPublicBinding(
|
||||
errorCode: 'huya_bind_pending_role_changed',
|
||||
})
|
||||
}
|
||||
if (!expectedRoleToken && targetRole.roleToken) {
|
||||
throw createHttpError('缺少角色标识快照,请刷新绑定角色后重试', {
|
||||
statusCode: 409,
|
||||
errorCode: 'semi_auto_binding_snapshot_required',
|
||||
})
|
||||
}
|
||||
} else if (session.status !== 'confirmed') {
|
||||
throw createHttpError('当前没有可确认的绑定角色', {
|
||||
statusCode: 409,
|
||||
errorCode: 'semi_auto_binding_not_ready',
|
||||
})
|
||||
}
|
||||
if (task.platform === 'huya' && session.pendingRole) {
|
||||
const marked = await markHuyaBindingConfirmationSubmitting({
|
||||
taskId: task.id,
|
||||
actorType: 'customer',
|
||||
expectedRoleName,
|
||||
expectedRoleToken: expectedRoleToken,
|
||||
expectedRoleChannel,
|
||||
})
|
||||
if (marked.alreadyInFlight) {
|
||||
const inFlightSession = await getBindingForTask(task, task.connector_session_id!)
|
||||
const binding = await updateBindingTask(task, inFlightSession, 'customer')
|
||||
const updated = await loadTask(task.id)
|
||||
return { task: mapTask(updated), binding }
|
||||
}
|
||||
}
|
||||
const confirmedSession =
|
||||
task.platform === 'huya'
|
||||
? await confirmHuyaBinding(task.connector_session_id, task.connector_mode, {
|
||||
|
||||
@@ -61,7 +61,7 @@ import {
|
||||
} from './semi-auto-credential-service.js'
|
||||
import { querySemiAutoTraces } from './semi-auto-trace.js'
|
||||
import { isHuyaRoleToken, isNumericBindingRoleId } from './binding-role-id.js'
|
||||
import { resolveServerZone } from '../account-binding/binding-identity.js'
|
||||
import { normalizeBindingRoleName, resolveServerZone } from '../account-binding/binding-identity.js'
|
||||
import { getAccountBindingPolicy } from '../account-binding/platform-policy.js'
|
||||
import {
|
||||
compareHuyaBindingRole,
|
||||
@@ -145,6 +145,7 @@ export type TaskRow = {
|
||||
bind_confirm_message: string
|
||||
binding_qr_issued_at: string | null
|
||||
binding_effect_deadline_at: string | null
|
||||
connector_state_version: number
|
||||
pending_role_observed_at: string | null
|
||||
confirmed_role_observed_at: string | null
|
||||
role_identity_source: string
|
||||
@@ -328,6 +329,14 @@ export function isTaskBindingConfirmed(task: TaskRow): boolean {
|
||||
)
|
||||
}
|
||||
|
||||
export function isHuyaBindingConfirmationInFlight(task: TaskRow): boolean {
|
||||
return (
|
||||
task.platform === 'huya' &&
|
||||
['submitting', 'accepted'].includes(task.bind_confirm_state) &&
|
||||
Boolean(String(task.pending_bind_game_role || '').trim())
|
||||
)
|
||||
}
|
||||
|
||||
export async function refreshHuyaBindingDecisionForTask(
|
||||
taskIdInput: unknown,
|
||||
actorType: TaskActorType = 'system',
|
||||
@@ -454,7 +463,7 @@ export function displayStatus(task: TaskRow, decision = resolveTaskHuyaBindingDe
|
||||
'修改目标资料或等待冷却结束',
|
||||
)
|
||||
case 'rebind_effect_pending':
|
||||
return status('rebind_effect_pending', '换绑生效中', 'system', '稍后刷新绑定状态')
|
||||
return status('rebind_effect_pending', '绑定生效中', 'system', '稍后刷新绑定状态')
|
||||
case 'manual_review':
|
||||
case 'first_bind_role_mismatch':
|
||||
return status('binding_support', '绑定需人工核实', 'operator', '客服核对角色信息')
|
||||
@@ -469,7 +478,12 @@ export function displayStatus(task: TaskRow, decision = resolveTaskHuyaBindingDe
|
||||
case 'rebind_qr_pending':
|
||||
return status('waiting_binding', '等待客户绑定角色', 'customer', '完成角色扫码绑定')
|
||||
case 'binding_query_required':
|
||||
return status('waiting_binding', '等待查询绑定状态', 'system', '刷新绑定状态')
|
||||
return status(
|
||||
'waiting_binding',
|
||||
'等待客户绑定角色',
|
||||
'customer',
|
||||
'系统正在自动查询虎牙账号角色',
|
||||
)
|
||||
}
|
||||
}
|
||||
// 微博以平台事实确认;虎牙已在上方由唯一决策器处理。
|
||||
@@ -520,6 +534,7 @@ export function mapTask(task: TaskRow) {
|
||||
bindingStatus: task.binding_status,
|
||||
executionStatus: task.execution_status,
|
||||
connectorMode: task.connector_mode,
|
||||
connectorStateVersion: Number(task.connector_state_version || 0),
|
||||
displayStatus: displayStatus(task, bindingDecision),
|
||||
connectorReady: Boolean(task.connector_session_id || task.credential_id),
|
||||
credentialReady: Boolean(task.credential_id),
|
||||
@@ -1021,6 +1036,77 @@ type SemiAutoCandidate = {
|
||||
quantity: number
|
||||
}
|
||||
|
||||
type ExistingSemiAutoTask = {
|
||||
id: number
|
||||
fulfillment_id: number | null
|
||||
manual_fulfillment_config_id: number | null
|
||||
platform: SemiAutoPlatform
|
||||
target_quantity: number
|
||||
execution_status: ExecutionStatus
|
||||
}
|
||||
|
||||
async function cancelIneligibleSemiAutoTasksWithClient(client: PoolClient, orderItemIds: number[]) {
|
||||
if (orderItemIds.length === 0) return { orderIds: [] as number[] }
|
||||
const active = await client.query<{
|
||||
id: number
|
||||
order_id: number
|
||||
execution_status: ExecutionStatus
|
||||
desired_config_id: number | null
|
||||
desired_platform: string
|
||||
config_eligible: boolean
|
||||
}>(
|
||||
`
|
||||
SELECT
|
||||
task.id,
|
||||
task.order_id,
|
||||
task.execution_status,
|
||||
f.fulfillment_config_id AS desired_config_id,
|
||||
cfg.semi_auto_platform AS desired_platform,
|
||||
(
|
||||
f.channel = 'manual'
|
||||
AND f.status = 'assigned'
|
||||
AND cfg.enabled = TRUE
|
||||
AND cfg.semi_auto_enabled = TRUE
|
||||
AND cfg.semi_auto_platform IN ('huya', 'weibo')
|
||||
) AS config_eligible
|
||||
FROM semi_auto_tasks task
|
||||
JOIN fulfillments f ON f.order_item_id = task.order_item_id
|
||||
LEFT JOIN manual_fulfillment_configs cfg ON cfg.id = f.fulfillment_config_id
|
||||
WHERE task.order_item_id = ANY($1::bigint[])
|
||||
AND task.execution_status <> 'cancelled'
|
||||
FOR UPDATE OF task
|
||||
`,
|
||||
[orderItemIds],
|
||||
)
|
||||
const orderIds = new Set<number>()
|
||||
for (const task of active.rows) {
|
||||
if (task.config_eligible) continue
|
||||
await client.query(
|
||||
`
|
||||
UPDATE semi_auto_tasks
|
||||
SET execution_status = 'cancelled',
|
||||
last_error = '人工履约配置已停用半自动履约或不再满足人工渠道条件',
|
||||
updated_at = NOW()
|
||||
WHERE id = $1
|
||||
`,
|
||||
[task.id],
|
||||
)
|
||||
await appendTaskEvent(client, task.id, {
|
||||
eventType: 'task_cancelled_config_ineligible',
|
||||
actorType: 'system',
|
||||
fromExecutionStatus: task.execution_status,
|
||||
toExecutionStatus: 'cancelled',
|
||||
detail: {
|
||||
reason: 'manual_semi_auto_config_ineligible',
|
||||
desiredConfigId: task.desired_config_id,
|
||||
desiredPlatform: task.desired_platform,
|
||||
},
|
||||
})
|
||||
orderIds.add(Number(task.order_id))
|
||||
}
|
||||
return { orderIds: [...orderIds] }
|
||||
}
|
||||
|
||||
async function insertMissingSemiAutoTasksWithClient(
|
||||
client: PoolClient,
|
||||
orderNo?: string,
|
||||
@@ -1029,6 +1115,7 @@ async function insertMissingSemiAutoTasksWithClient(
|
||||
) {
|
||||
const params: unknown[] = []
|
||||
const filters: string[] = []
|
||||
const reconciledOrderIds = new Set<number>()
|
||||
if (orderNo) {
|
||||
params.push(orderNo)
|
||||
filters.push(`o.platform_order_id = $${params.length}`)
|
||||
@@ -1039,6 +1126,8 @@ async function insertMissingSemiAutoTasksWithClient(
|
||||
if (normalizedItemIds.length > 0) {
|
||||
params.push(normalizedItemIds)
|
||||
filters.push(`oi.id = ANY($${params.length}::bigint[])`)
|
||||
const ineligible = await cancelIneligibleSemiAutoTasksWithClient(client, normalizedItemIds)
|
||||
for (const orderId of ineligible.orderIds) reconciledOrderIds.add(orderId)
|
||||
}
|
||||
if (options.createdAfter) {
|
||||
params.push(options.createdAfter)
|
||||
@@ -1071,7 +1160,12 @@ async function insertMissingSemiAutoTasksWithClient(
|
||||
AND cfg.semi_auto_platform IN ('huya', 'weibo')
|
||||
${itemFilter}
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM semi_auto_tasks existing WHERE existing.order_item_id = oi.id
|
||||
SELECT 1
|
||||
FROM semi_auto_tasks existing
|
||||
WHERE existing.order_item_id = oi.id
|
||||
AND existing.execution_status <> 'cancelled'
|
||||
AND existing.manual_fulfillment_config_id = cfg.id
|
||||
AND existing.platform = cfg.semi_auto_platform
|
||||
)
|
||||
ORDER BY o.id DESC, oi.id ASC
|
||||
${limitSql}
|
||||
@@ -1080,16 +1174,71 @@ async function insertMissingSemiAutoTasksWithClient(
|
||||
)
|
||||
|
||||
const createdIds: number[] = []
|
||||
const orderIds = new Set<number>()
|
||||
const orderIds = new Set<number>(reconciledOrderIds)
|
||||
for (const row of candidates.rows) {
|
||||
const connectorMode = row.platform === 'weibo' ? 'embedded' : defaultSemiAutoConnectorMode()
|
||||
const activeTasks = await client.query<ExistingSemiAutoTask>(
|
||||
`
|
||||
SELECT id, fulfillment_id, manual_fulfillment_config_id, platform,
|
||||
target_quantity, execution_status
|
||||
FROM semi_auto_tasks
|
||||
WHERE order_item_id = $1
|
||||
AND execution_status <> 'cancelled'
|
||||
ORDER BY id DESC
|
||||
FOR UPDATE
|
||||
`,
|
||||
[Number(row.order_item_id)],
|
||||
)
|
||||
const matching = activeTasks.rows.find(
|
||||
(task) =>
|
||||
Number(task.manual_fulfillment_config_id) === Number(row.manual_fulfillment_config_id) &&
|
||||
task.platform === row.platform,
|
||||
)
|
||||
if (matching) {
|
||||
await client.query(
|
||||
`
|
||||
UPDATE semi_auto_tasks
|
||||
SET fulfillment_id = $2,
|
||||
target_quantity = $3,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1
|
||||
`,
|
||||
[matching.id, Number(row.fulfillment_id), Number(row.quantity || 1)],
|
||||
)
|
||||
continue
|
||||
}
|
||||
for (const stale of activeTasks.rows) {
|
||||
await client.query(
|
||||
`
|
||||
UPDATE semi_auto_tasks
|
||||
SET execution_status = 'cancelled',
|
||||
last_error = '人工履约配置已切换半自动平台,旧任务自动终止',
|
||||
updated_at = NOW()
|
||||
WHERE id = $1
|
||||
`,
|
||||
[stale.id],
|
||||
)
|
||||
await appendTaskEvent(client, stale.id, {
|
||||
eventType: 'task_cancelled_config_changed',
|
||||
actorType: 'system',
|
||||
fromExecutionStatus: stale.execution_status,
|
||||
toExecutionStatus: 'cancelled',
|
||||
detail: {
|
||||
reason: 'manual_semi_auto_config_changed',
|
||||
fromConfigId: Number(stale.manual_fulfillment_config_id || 0),
|
||||
fromPlatform: stale.platform,
|
||||
toConfigId: Number(row.manual_fulfillment_config_id),
|
||||
toPlatform: row.platform,
|
||||
},
|
||||
})
|
||||
}
|
||||
const inserted = await client.query<{ id: number }>(
|
||||
`
|
||||
INSERT INTO semi_auto_tasks (
|
||||
order_id, order_item_id, fulfillment_id, manual_fulfillment_config_id,
|
||||
platform, connector_mode, target_quantity, created_at, updated_at
|
||||
) VALUES ($1, $2, $3, $4, $5, $6, $7, NOW(), NOW())
|
||||
ON CONFLICT (order_item_id) DO NOTHING
|
||||
ON CONFLICT (order_item_id) WHERE execution_status <> 'cancelled' DO NOTHING
|
||||
RETURNING id
|
||||
`,
|
||||
[
|
||||
@@ -1166,6 +1315,29 @@ export async function backfillSemiAutoTasks(
|
||||
return { createdIds: result.createdIds, orderIds: result.orderIds }
|
||||
}
|
||||
|
||||
/**
|
||||
* 人工配置保存后按当前 fulfillment_config_id 重新收敛该 SKU 的既有任务。
|
||||
* 平台切换会终止旧任务并创建新任务;停用半自动会终止仍活跃的旧任务。
|
||||
*/
|
||||
export async function reconcileSemiAutoTasksForManualConfig(configIdInput: unknown) {
|
||||
const configId = Number(configIdInput)
|
||||
if (!Number.isSafeInteger(configId) || configId <= 0) {
|
||||
return { createdIds: [], orderIds: [] }
|
||||
}
|
||||
const items = await query<{ id: number }>(
|
||||
`
|
||||
SELECT f.order_item_id AS id
|
||||
FROM fulfillments f
|
||||
WHERE f.fulfillment_config_id = $1
|
||||
AND f.channel = 'manual'
|
||||
AND f.status = 'assigned'
|
||||
ORDER BY f.order_item_id
|
||||
`,
|
||||
[configId],
|
||||
)
|
||||
return ensureSemiAutoTasksForOrderItems(items.rows.map((row) => Number(row.id)))
|
||||
}
|
||||
|
||||
export type BindingRoleComparison = ReturnType<typeof compareHuyaBindingRole>
|
||||
|
||||
/**
|
||||
@@ -1298,6 +1470,96 @@ function mapBindingUpdate(session: ConnectorBindingSession) {
|
||||
}
|
||||
}
|
||||
|
||||
function persistedHuyaPendingRole(task: TaskRow): HuyaRoleSnapshot | null {
|
||||
return huyaRoleSnapshots(task).pending
|
||||
}
|
||||
|
||||
function currentRoleMatchesPending(
|
||||
current: HuyaRoleSnapshot | null,
|
||||
pending: HuyaRoleSnapshot | null,
|
||||
) {
|
||||
if (!current || !pending) return false
|
||||
if (!current.isBindAccount || !current.isBindRole) return false
|
||||
if (normalizeBindingRoleName(current.roleName) !== normalizeBindingRoleName(pending.roleName)) {
|
||||
return false
|
||||
}
|
||||
const currentZone = resolveServerZone(current.channel)
|
||||
const pendingZone = resolveServerZone(pending.channel)
|
||||
if (!currentZone || currentZone !== pendingZone) return false
|
||||
const currentToken = String(current.roleToken || '')
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
const pendingToken = String(pending.roleToken || '')
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
return Boolean(currentToken && pendingToken && currentToken === pendingToken)
|
||||
}
|
||||
|
||||
/**
|
||||
* Connector 的绑定确认状态是短期内存态,数据库才是跨进程真源。
|
||||
* 轮询结果缺少 confirmed/accepted 时,用持久化确认意图恢复等待态;
|
||||
* 一旦回查到 current 已与 pending 一致,则在这里原子收敛为 confirmed。
|
||||
*/
|
||||
function stabilizePersistedHuyaBindingSession(
|
||||
task: TaskRow,
|
||||
session: ConnectorBindingSession,
|
||||
): ConnectorBindingSession {
|
||||
if (!isHuyaBindingConfirmationInFlight(task)) return session
|
||||
const persistedPending = persistedHuyaPendingRole(task)
|
||||
const pending = session.pendingRole || persistedPending
|
||||
if (session.bindConfirmState === 'rejected') {
|
||||
return {
|
||||
...session,
|
||||
pendingRole: pending,
|
||||
bindConfirmState: 'rejected',
|
||||
bindConfirmMessage: session.bindConfirmMessage || task.bind_confirm_message,
|
||||
}
|
||||
}
|
||||
if (currentRoleMatchesPending(session.currentRole || null, pending)) {
|
||||
return {
|
||||
...session,
|
||||
status: 'confirmed',
|
||||
pendingRole: null,
|
||||
pendingBindGameAccount: '',
|
||||
pendingBindGameRole: '',
|
||||
pendingBindGameRoleToken: '',
|
||||
pendingBindGameChannel: '',
|
||||
pendingChangeBindTime: 0,
|
||||
pendingChangeBindDay: 0,
|
||||
bindConfirmState: 'idle',
|
||||
bindConfirmMessage: '',
|
||||
bindEffectDeadlineAt: '',
|
||||
message: '虎牙角色绑定已确认',
|
||||
}
|
||||
}
|
||||
return {
|
||||
...session,
|
||||
status: ['failed', 'expired'].includes(session.status) ? session.status : 'scanned',
|
||||
pendingRole: pending,
|
||||
pendingBindGameAccount:
|
||||
session.pendingBindGameAccount || (pending?.roleName ? task.pending_bind_game_account : ''),
|
||||
pendingBindGameRole: session.pendingBindGameRole || pending?.roleName || '',
|
||||
pendingBindGameRoleToken:
|
||||
session.pendingBindGameRoleToken || pending?.roleToken || task.pending_bind_game_role_token,
|
||||
pendingBindGameChannel:
|
||||
session.pendingBindGameChannel || pending?.channel || task.pending_bind_game_channel,
|
||||
pendingChangeBindTime:
|
||||
Number(session.pendingChangeBindTime || pending?.changeBindTime || 0) ||
|
||||
Number(task.pending_bind_game_change_bind_time || 0),
|
||||
pendingChangeBindDay:
|
||||
Number(session.pendingChangeBindDay || pending?.changeBindDay || 0) ||
|
||||
Number(task.pending_bind_game_change_bind_day || 0),
|
||||
bindConfirmState: task.bind_confirm_state,
|
||||
bindConfirmMessage: session.bindConfirmMessage || task.bind_confirm_message,
|
||||
bindEffectDeadlineAt: session.bindEffectDeadlineAt || task.binding_effect_deadline_at || '',
|
||||
message:
|
||||
session.message ||
|
||||
(task.bind_confirm_state === 'submitting'
|
||||
? '绑定确认已提交,正在回查平台状态'
|
||||
: '虎牙已受理绑定,正在等待角色生效'),
|
||||
}
|
||||
}
|
||||
|
||||
export function deriveSemiAutoExecutionStatus(
|
||||
task: TaskRow,
|
||||
bindingStatus: BindingStatus,
|
||||
@@ -1329,8 +1591,9 @@ export async function updateBindingTaskWithClient(
|
||||
actorType: TaskActorType,
|
||||
options: BindingUpdateOptions = {},
|
||||
) {
|
||||
const mapped = mapBindingUpdate(session)
|
||||
const current = await loadTaskForUpdateWithClient(client, taskId)
|
||||
const stabilizedSession = stabilizePersistedHuyaBindingSession(current, session)
|
||||
const mapped = mapBindingUpdate(stabilizedSession)
|
||||
const currentDecision = resolveTaskHuyaBindingDecision(current)
|
||||
if (current.execution_status === 'completed' || current.execution_status === 'cancelled') {
|
||||
return { current, decision: currentDecision, executionStatus: current.execution_status, mapped }
|
||||
@@ -1468,6 +1731,9 @@ export async function updateBindingTaskWithClient(
|
||||
mapped.status !== current.binding_status ||
|
||||
executionStatus !== current.execution_status ||
|
||||
bindingFlowState !== current.binding_flow_state ||
|
||||
mapped.bindConfirmState !== current.bind_confirm_state ||
|
||||
mapped.bindConfirmMessage !== current.bind_confirm_message ||
|
||||
(mapped.bindingEffectDeadlineAt || null) !== current.binding_effect_deadline_at ||
|
||||
mapped.rebindUnchanged ||
|
||||
mapped.rebindConfirmState === 'rejected'
|
||||
if (bindingChanged) {
|
||||
|
||||
@@ -310,10 +310,27 @@ test(
|
||||
reauthorized.events.some((event) => event.eventType === 'customer_reauth_requested'),
|
||||
)
|
||||
|
||||
const missingVersionEventId = randomUUID()
|
||||
await expectErrorCode(
|
||||
() =>
|
||||
applySemiAutoTaskStateSnapshot(
|
||||
{
|
||||
eventId: missingVersionEventId,
|
||||
taskId,
|
||||
orderNo,
|
||||
loginStatus: 'authenticated',
|
||||
bindingStatus: 'not_started',
|
||||
},
|
||||
{ eventId: missingVersionEventId, eventType: 'semi_auto.task_state' },
|
||||
),
|
||||
'semi_auto_snapshot_state_version_required',
|
||||
)
|
||||
|
||||
const snapshotEventId = randomUUID()
|
||||
const snapshot = await applySemiAutoTaskStateSnapshot(
|
||||
{
|
||||
eventId: snapshotEventId,
|
||||
stateVersion: 2,
|
||||
taskId,
|
||||
orderNo,
|
||||
loginStatus: 'authenticated',
|
||||
@@ -337,6 +354,7 @@ test(
|
||||
applySemiAutoTaskStateSnapshot(
|
||||
{
|
||||
eventId: reusedUidEventId,
|
||||
stateVersion: 3,
|
||||
taskId,
|
||||
orderNo,
|
||||
loginStatus: 'authenticated',
|
||||
@@ -353,6 +371,7 @@ test(
|
||||
const duplicateSnapshot = await applySemiAutoTaskStateSnapshot(
|
||||
{
|
||||
eventId: snapshotEventId,
|
||||
stateVersion: 2,
|
||||
taskId,
|
||||
orderNo,
|
||||
loginStatus: 'authenticated',
|
||||
@@ -387,6 +406,7 @@ test(
|
||||
await applySemiAutoTaskStateSnapshot(
|
||||
{
|
||||
eventId: staleConfirmEventId,
|
||||
stateVersion: 3,
|
||||
taskId,
|
||||
orderNo,
|
||||
loginStatus: 'authenticated',
|
||||
@@ -415,6 +435,37 @@ test(
|
||||
execution_status: 'waiting_customer',
|
||||
binding_flow_state: 'rebind_required',
|
||||
})
|
||||
const outOfOrderEventId = randomUUID()
|
||||
const outOfOrder = await applySemiAutoTaskStateSnapshot(
|
||||
{
|
||||
eventId: outOfOrderEventId,
|
||||
stateVersion: 2,
|
||||
taskId,
|
||||
orderNo,
|
||||
loginStatus: 'authenticated',
|
||||
bindingStatus: 'confirmed',
|
||||
huyaUid: `it-huya-${suffix}`,
|
||||
bindGameAccount: '集成测试虎牙账号',
|
||||
bindGameRole: '集成测试角色',
|
||||
bindGameRoleToken: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
|
||||
bindGameChannel: '安卓(android) · 微信',
|
||||
isBindAccount: true,
|
||||
isBindRole: true,
|
||||
roleIdentitySource: 'huya_outer_current',
|
||||
verificationBasis: 'role_name_zone',
|
||||
},
|
||||
{ eventId: outOfOrderEventId, eventType: 'semi_auto.task_state' },
|
||||
)
|
||||
assert.equal(outOfOrder.applied, false)
|
||||
assert.equal(outOfOrder.stale, true)
|
||||
const afterOutOfOrder = await query<{ binding_flow_state: string; execution_status: string }>(
|
||||
`SELECT binding_flow_state, execution_status FROM semi_auto_tasks WHERE id = $1`,
|
||||
[taskId],
|
||||
)
|
||||
assert.deepEqual(afterOutOfOrder.rows[0], {
|
||||
binding_flow_state: 'rebind_required',
|
||||
execution_status: 'waiting_customer',
|
||||
})
|
||||
} finally {
|
||||
if (orderId > 0) {
|
||||
await query('DELETE FROM order_source_snapshots WHERE order_id = $1', [orderId])
|
||||
@@ -542,8 +593,18 @@ test(
|
||||
UPDATE semi_auto_tasks
|
||||
SET credential_id = $2,
|
||||
login_status = 'authenticated',
|
||||
binding_status = 'not_started',
|
||||
binding_status = 'confirmed',
|
||||
binding_flow_state = 'confirmed',
|
||||
execution_status = 'waiting_operator',
|
||||
customer_game_role_name = '半自动原子性角色',
|
||||
customer_game_role_id = '1192083858',
|
||||
customer_game_server_zone = '安卓V区',
|
||||
bind_game_role = '半自动原子性角色',
|
||||
bind_game_role_token = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
|
||||
bind_game_channel = '安卓(android) · 微信',
|
||||
is_bind_account = TRUE,
|
||||
is_bind_role = TRUE,
|
||||
bound_at = NOW(),
|
||||
authenticated_at = NOW(),
|
||||
updated_at = NOW()
|
||||
WHERE id = $1
|
||||
@@ -677,6 +738,183 @@ test(
|
||||
},
|
||||
)
|
||||
|
||||
test(
|
||||
'人工配置切换半自动平台会终止旧任务并创建新的活动任务',
|
||||
{ skip: !TEST_DATABASE_URL ? '未设置 SEMI_AUTO_TASK_TEST_DATABASE_URL' : false },
|
||||
async () => {
|
||||
process.env.DATABASE_URL = TEST_DATABASE_URL
|
||||
process.env.ENABLE_DEV_MOCK = '1'
|
||||
const { closeDb, query } = await import('../../db/client.js')
|
||||
const { createSemiAutoMock } = await import('../dev-mock/dev-mock-service.js')
|
||||
const { reconcileSemiAutoTasksForManualConfig } = await import('./semi-auto-task-service.js')
|
||||
const suffix = `${Date.now()}_${Math.floor(Math.random() * 1_000_000)}`
|
||||
const orderNo = `IT-SEMI-AUTO-PLATFORM-SWITCH-${suffix}`
|
||||
let orderId = 0
|
||||
let configId = 0
|
||||
try {
|
||||
const result = await createSemiAutoMock({
|
||||
orderNo,
|
||||
skuName: `半自动平台切换-${suffix}`,
|
||||
quantity: 1,
|
||||
connectorMode: 'embedded',
|
||||
})
|
||||
orderId = result.orderId
|
||||
configId = result.configId
|
||||
await query(
|
||||
`UPDATE manual_fulfillment_configs
|
||||
SET semi_auto_platform = 'weibo', updated_at = NOW()
|
||||
WHERE id = $1`,
|
||||
[configId],
|
||||
)
|
||||
const reconciled = await reconcileSemiAutoTasksForManualConfig(configId)
|
||||
assert.equal(reconciled.createdIds.length, 1)
|
||||
|
||||
const tasks = await query<{
|
||||
id: number
|
||||
platform: string
|
||||
execution_status: string
|
||||
last_error: string
|
||||
}>(
|
||||
`SELECT id, platform, execution_status, last_error
|
||||
FROM semi_auto_tasks
|
||||
WHERE order_id = $1
|
||||
ORDER BY id`,
|
||||
[orderId],
|
||||
)
|
||||
assert.equal(tasks.rows.length, 2)
|
||||
assert.equal(tasks.rows[0]?.platform, 'huya')
|
||||
assert.equal(tasks.rows[0]?.execution_status, 'cancelled')
|
||||
assert.match(tasks.rows[0]?.last_error || '', /切换半自动平台/)
|
||||
assert.equal(tasks.rows[1]?.platform, 'weibo')
|
||||
assert.equal(tasks.rows[1]?.execution_status, 'waiting_customer')
|
||||
|
||||
await query(
|
||||
`UPDATE manual_fulfillment_configs
|
||||
SET semi_auto_enabled = FALSE, updated_at = NOW()
|
||||
WHERE id = $1`,
|
||||
[configId],
|
||||
)
|
||||
await reconcileSemiAutoTasksForManualConfig(configId)
|
||||
const disabled = await query<{ platform: string; execution_status: string }>(
|
||||
`SELECT platform, execution_status
|
||||
FROM semi_auto_tasks
|
||||
WHERE order_id = $1
|
||||
ORDER BY id`,
|
||||
[orderId],
|
||||
)
|
||||
assert.deepEqual(disabled.rows, [
|
||||
{ platform: 'huya', execution_status: 'cancelled' },
|
||||
{ platform: 'weibo', execution_status: 'cancelled' },
|
||||
])
|
||||
} finally {
|
||||
if (orderId > 0) await query('DELETE FROM orders WHERE id = $1', [orderId])
|
||||
if (configId > 0) {
|
||||
await query('DELETE FROM manual_fulfillment_configs WHERE id = $1', [configId])
|
||||
}
|
||||
delete process.env.ENABLE_DEV_MOCK
|
||||
await closeDb()
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
test(
|
||||
'虎牙确认状态可从数据库恢复并在回查角色一致后收敛为已确认',
|
||||
{ skip: !TEST_DATABASE_URL ? '未设置 SEMI_AUTO_TASK_TEST_DATABASE_URL' : false },
|
||||
async () => {
|
||||
process.env.DATABASE_URL = TEST_DATABASE_URL
|
||||
process.env.ENABLE_DEV_MOCK = '1'
|
||||
const { closeDb, query, withTransaction } = await import('../../db/client.js')
|
||||
const { createSemiAutoMock } = await import('../dev-mock/dev-mock-service.js')
|
||||
const { loadTask, updateBindingTaskWithClient } = await import('./semi-auto-task-core.js')
|
||||
const suffix = `${Date.now()}_${Math.floor(Math.random() * 1_000_000)}`
|
||||
const orderNo = `IT-HUYA-CONFIRM-RECOVERY-${suffix}`
|
||||
const targetRoleToken = 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'
|
||||
let orderId = 0
|
||||
let configId = 0
|
||||
try {
|
||||
const result = await createSemiAutoMock({
|
||||
orderNo,
|
||||
skuName: `虎牙确认恢复-${suffix}`,
|
||||
quantity: 1,
|
||||
connectorMode: 'embedded',
|
||||
})
|
||||
orderId = result.orderId
|
||||
configId = result.configId
|
||||
await query(
|
||||
`
|
||||
UPDATE semi_auto_tasks
|
||||
SET login_status = 'authenticated',
|
||||
customer_game_role_name = '恢复目标角色',
|
||||
customer_game_role_id = '1192083858',
|
||||
customer_game_server_zone = '安卓V区',
|
||||
binding_status = 'scanned',
|
||||
bind_game_role = '旧角色',
|
||||
bind_game_role_token = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
|
||||
bind_game_channel = '安卓(android) · 微信',
|
||||
is_bind_account = TRUE,
|
||||
is_bind_role = TRUE,
|
||||
pending_bind_game_role = '恢复目标角色',
|
||||
pending_bind_game_role_token = $2,
|
||||
pending_bind_game_channel = '安卓(android) · 微信',
|
||||
bind_confirm_state = 'accepted',
|
||||
binding_effect_deadline_at = NOW() + INTERVAL '1 minute',
|
||||
execution_status = 'waiting_customer',
|
||||
updated_at = NOW()
|
||||
WHERE id = $1
|
||||
`,
|
||||
[result.taskId, targetRoleToken],
|
||||
)
|
||||
const task = await loadTask(result.taskId)
|
||||
await withTransaction((client) =>
|
||||
updateBindingTaskWithClient(
|
||||
client,
|
||||
task.id,
|
||||
{
|
||||
sessionId: task.connector_session_id,
|
||||
status: 'role_ready',
|
||||
qrImage: '',
|
||||
qrExpiresAt: '',
|
||||
qrUrl: '',
|
||||
bindGameAccount: '恢复目标账号',
|
||||
bindGameRole: '恢复目标角色',
|
||||
bindGameRoleId: targetRoleToken,
|
||||
bindGameRoleToken: targetRoleToken,
|
||||
bindGameChannel: '安卓(android) · 微信',
|
||||
currentRole: {
|
||||
isBindAccount: true,
|
||||
isBindRole: true,
|
||||
roleName: '恢复目标角色',
|
||||
roleToken: targetRoleToken,
|
||||
channel: '安卓(android) · 微信',
|
||||
changeBindTime: 0,
|
||||
changeBindDay: 7,
|
||||
},
|
||||
pendingRole: null,
|
||||
hasExistingBinding: true,
|
||||
rebindRequested: false,
|
||||
message: '平台角色已生效',
|
||||
},
|
||||
'connector',
|
||||
),
|
||||
)
|
||||
const recovered = await loadTask(result.taskId)
|
||||
assert.equal(recovered.binding_status, 'confirmed')
|
||||
assert.equal(recovered.binding_flow_state, 'confirmed')
|
||||
assert.equal(recovered.execution_status, 'waiting_operator')
|
||||
assert.equal(recovered.bind_confirm_state, 'idle')
|
||||
assert.equal(recovered.pending_bind_game_role, '')
|
||||
assert.ok(recovered.bound_at)
|
||||
} finally {
|
||||
if (orderId > 0) await query('DELETE FROM orders WHERE id = $1', [orderId])
|
||||
if (configId > 0) {
|
||||
await query('DELETE FROM manual_fulfillment_configs WHERE id = $1', [configId])
|
||||
}
|
||||
delete process.env.ENABLE_DEV_MOCK
|
||||
await closeDb()
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
test(
|
||||
'微博账号 CK 以账号级 Cookie JSON 保存并可加载',
|
||||
{ skip: !TEST_DATABASE_URL ? '未设置 SEMI_AUTO_TASK_TEST_DATABASE_URL' : false },
|
||||
@@ -1011,7 +1249,8 @@ test(
|
||||
)
|
||||
|
||||
assert.equal(binding.status, 'confirmed')
|
||||
assert.equal(binding.comparison.verdict, 'match')
|
||||
assert.equal(binding.comparison.verdict, 'unknown')
|
||||
assert.equal(binding.comparison.message, '当前不是虎牙绑定任务')
|
||||
const stored = await query<{
|
||||
binding_status: string
|
||||
execution_status: string
|
||||
|
||||
@@ -101,7 +101,7 @@ const BINDING_FLOW_LABELS: Record<string, string> = {
|
||||
rebind_required: '需要换绑',
|
||||
rebind_qr_pending: '换绑待扫码',
|
||||
rebind_role_ready: '换绑待确认',
|
||||
rebind_effect_pending: '换绑生效中',
|
||||
rebind_effect_pending: '绑定生效中',
|
||||
rebind_blocked_account: '虎牙账号换绑冷却中',
|
||||
rebind_blocked_target_role: '目标角色冷却',
|
||||
rebind_rejected: '虎牙拒绝换绑',
|
||||
@@ -849,7 +849,9 @@ export default function AdminSemiAutoTasksPage() {
|
||||
}
|
||||
>
|
||||
{detail.comparison?.verdict === 'match'
|
||||
? '三项一致,可提交平台绑定'
|
||||
? detail.comparison.verificationBasis === 'platform_numeric_uid'
|
||||
? '角色名、区服和平台角色 UID 一致,可提交平台绑定'
|
||||
: '角色名与区服一致,可提交平台绑定'
|
||||
: detail.comparison?.verdict === 'mismatch'
|
||||
? '资料与平台角色不一致'
|
||||
: '信息不完整,需人工核实'}
|
||||
|
||||
@@ -110,9 +110,9 @@ export default function CustomerFulfillmentPage({
|
||||
const huyaBindingConfirmed = bindingDecision?.flowState === 'confirmed'
|
||||
const huyaBindingPolling = Boolean(
|
||||
selectedTask?.platform === 'huya' &&
|
||||
(bindingActions.has('refresh_binding_status') ||
|
||||
bindingActions.has('refresh_first_binding_qr') ||
|
||||
bindingActions.has('refresh_rebind_qr')),
|
||||
['first_bind_qr_pending', 'rebind_qr_pending', 'rebind_effect_pending'].includes(
|
||||
bindingDecision?.flowState || '',
|
||||
),
|
||||
)
|
||||
const isWeibo = selectedTask?.platform === 'weibo'
|
||||
// 虎牙流程:登录 → 填写资料(区服/游戏角色 UID/角色名)→ 绑定角色。
|
||||
|
||||
@@ -46,6 +46,16 @@ test('登录和绑定专用同步阶段暂停整单轮询', () => {
|
||||
assert.ok(source.includes('}, 10_000)'))
|
||||
})
|
||||
|
||||
test('虎牙绑定只在二维码或平台生效等待态轮询,过期二维码不再持续请求', () => {
|
||||
assert.ok(source.includes("'first_bind_qr_pending'"))
|
||||
assert.ok(source.includes("'rebind_qr_pending'"))
|
||||
assert.ok(source.includes("'rebind_effect_pending'"))
|
||||
const pollingStart = source.indexOf('const huyaBindingPolling')
|
||||
const pollingEnd = source.indexOf('const isWeibo', pollingStart)
|
||||
const pollingSource = source.slice(pollingStart, pollingEnd)
|
||||
assert.ok(!pollingSource.includes('bindingActions.has('))
|
||||
})
|
||||
|
||||
test('角色名和区服一致才出现确认绑定,不一致时展示原因', () => {
|
||||
assert.ok(source.includes('确认绑定此角色'))
|
||||
assert.ok(source.includes('canConfirmDecision'))
|
||||
|
||||
@@ -59,3 +59,9 @@ test('注入按钮和完成按钮使用各自的门槛', () => {
|
||||
test('换绑冷却明确指向虎牙登录账号', () => {
|
||||
assert.ok(adminPage.includes("rebind_blocked_account: '虎牙账号换绑冷却中'"))
|
||||
})
|
||||
|
||||
test('虎牙默认只声明角色名与区服一致,不把客户角色 UID 冒充已核验', () => {
|
||||
assert.ok(!adminPage.includes('三项一致,可提交平台绑定'))
|
||||
assert.ok(adminPage.includes('角色名与区服一致,可提交平台绑定'))
|
||||
assert.ok(adminPage.includes('角色名、区服和平台角色 UID 一致,可提交平台绑定'))
|
||||
})
|
||||
|
||||
+19
-6
@@ -3,16 +3,16 @@ type: 权威架构与实施计划
|
||||
description: 订单、内部 SKU、履约路由、履约执行、商品、成本与财务的唯一权威口径及重构计划。
|
||||
tags: [订单, 内部SKU, 履约, 商品, 成本, 财务, 迁移]
|
||||
status: authoritative
|
||||
version: 2.31
|
||||
updated_at: 2026-11-19
|
||||
version: 2.32
|
||||
updated_at: 2026-11-20
|
||||
---
|
||||
|
||||
# 统一订单、履约与财务模型
|
||||
|
||||
> 状态:**唯一权威文档**。
|
||||
> 最后校准:2026-11-19。
|
||||
> 最后校准:2026-11-20。
|
||||
> 生产基线:迁移 `175`(2026-11-19 核对)。
|
||||
> 开发基线:迁移 `177`(仅本地,尚未部署生产)。
|
||||
> 开发基线:迁移 `178`(仅本地,尚未部署生产)。
|
||||
>
|
||||
> 从本文件生效起,订单、内部 SKU、履约渠道、履约载体、标准商品、成本和财务相关实现,
|
||||
> 只能以本文件为业务口径。其他旧分析只作为历史资料,不再具备设计或验收效力。
|
||||
@@ -420,7 +420,15 @@ manual fulfillment
|
||||
`flowState / rebindBlockScope / allowedActions`,各写入口不得自行分类。
|
||||
- 外部 Connector 通过签名 Webhook `POST /api/integration/platform-fulfillment/semi-auto/task-state`
|
||||
提交登录与绑定快照,事件 ID 使用 `integration_inbox` 幂等;Connector 只提交平台观察到的事实,
|
||||
不得直接声明业务履约完成。执行状态由登录、绑定和人工确认规则推导。
|
||||
不得直接声明业务履约完成。每个快照必须携带任务级单调 `stateVersion`;同一任务的旧版本或
|
||||
同版本重复快照不得覆盖当前事实。执行状态由登录、绑定和人工确认规则推导。
|
||||
- 虎牙确认绑定必须先持久化 `bind_confirm_state = submitting`,再调用平台写接口;平台受理后持久化
|
||||
`accepted` 与生效截止时间。Connector 重启或请求超时后,以数据库中的 pending 角色和确认状态恢复,
|
||||
只读回查平台角色;current 与 pending 的角色名、区服和 role token 一致后才收敛为 `confirmed`,
|
||||
不得因 Connector 内存丢失重新放行第二次平台写操作。
|
||||
- 人工履约配置切换半自动平台或停用半自动时,必须按当前 `fulfillments.fulfillment_config_id`
|
||||
主动收敛既有任务:旧活动任务先写取消事件并保留为历史,再按新配置创建新的活动任务。
|
||||
同一订单项最多一条非取消任务,取消任务不得阻止后续重新物化。
|
||||
- order_site 与 live-hub 的通信职责必须区分:
|
||||
① order_site → live-hub 的正常路径走事务 `integration_outbox`,事件必须携带目标订单项的有界
|
||||
业务快照和稳定去重指纹,由 worker 投递签名
|
||||
@@ -1168,7 +1176,7 @@ docs/archive/
|
||||
|
||||
## 十三、当前下一步
|
||||
|
||||
截至 2026-11-19,生产基线为 `175`,当前开发基线为 `176`。迁移 `152` 保护订单来源快照,
|
||||
截至 2026-11-20,生产基线为 `175`,当前开发基线为 `178`。迁移 `152` 保护订单来源快照,
|
||||
迁移 `158–160` 收口寄卖登记人同步、寄卖平台与自动匹配设置;
|
||||
迁移 `161` 一次建立人工渠道半自动任务、内置 Connector 默认值、账号级 Cookie JSON 凭证、
|
||||
任务凭证引用和最终约束;迁移 `162` 建立履约待办四桶只读投影、补载体专用索引和新单优先扫描口径。
|
||||
@@ -1190,6 +1198,11 @@ pending 角色快照、`role_identity_source` 与 `verification_basis`。
|
||||
确认与换绑请求状态及二维码/生效时间;同时修复“登录成功但绑定未确认却进入 `waiting_operator`”
|
||||
和“未确认任务过早写入 `bound_at`”的历史错位。结构化快照仍只提交平台观察到的事实,
|
||||
执行状态与完成门禁由统一决策器重新推导。
|
||||
迁移 `178` 为外部 Connector 快照增加任务级 `connector_state_version` 单调闸门,将同一订单项约束
|
||||
收敛为“最多一条非取消任务”,并重新核对历史 `waiting_operator + confirmed` 任务:客户资料缺失、
|
||||
区服无法解析或角色名/区服不一致时退出客服待办,进入客户补资料或换绑流程;无取消任务的唯一索引
|
||||
允许旧任务保留审计、新配置创建新的活动任务。确认绑定写平台前先持久化 `submitting`,重启或超时后
|
||||
只按数据库 pending 与平台 current 回查收敛,不得重复提交平台写操作。
|
||||
迁移 `169` 增加客户游戏角色资料三项(`customer_game_role_name` / `customer_game_role_id` /
|
||||
`customer_game_server_zone`),并允许从工单素材回退合并;客户页流程收敛为
|
||||
「登录 → 填写资料 → 绑定角色」,资料未填全不得生成绑定二维码。
|
||||
|
||||
Reference in New Issue
Block a user