修复(半自动履约): 收口虎牙确认恢复与任务切换
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
|
||||
|
||||
Reference in New Issue
Block a user