fix(douyu): 同步履约状态并补齐角色资料重置流程

- 接收 order_site 客户资料重置标记,清理旧角色并恢复待填写状态
- 统一绑定失败、待人工和已分配状态的投影与页面文案
- 新增 allocated 状态迁移,避免已分配账号被折叠为准备账号
- 立即同步时同时刷新直播履约状态,主动校正历史状态差异
- 补充状态优先级、资料重置和已分配状态测试
This commit is contained in:
yml
2026-11-18 11:00:28 +08:00
parent 919fb2767b
commit 1bc4931508
8 changed files with 149 additions and 13 deletions
@@ -0,0 +1,24 @@
-- 174_douyu_fulfillment_allocated_status.sql
--
-- 直播账号履约工作台的 allocated 是正式状态,order_site 需要原样投影,
-- 不能折叠成 preparing,否则两边状态不一致。
ALTER TABLE douyu_fulfillment_tasks
DROP CONSTRAINT IF EXISTS douyu_fulfillment_tasks_status_check;
ALTER TABLE douyu_fulfillment_tasks
ADD CONSTRAINT douyu_fulfillment_tasks_status_check
CHECK (status IN (
'waiting_profile',
'preparing',
'allocated',
'qr_pending',
'role_ready',
'bound',
'waiting_operator',
'processing',
'completed',
'failed',
'manual_required',
'cancelled'
));
@@ -1,11 +1,11 @@
import { Router } from 'express'
import {
ensureDouyuFulfillmentTasks,
getDouyuFulfillmentDetail,
listDouyuFulfillmentTasks,
refreshDouyuCustomerBinding,
startDouyuCustomerBinding,
syncDouyuFulfillmentTasks,
} from '../../services/douyu-fulfillment/douyu-fulfillment-service.js'
import { createJsonHandler, requireAdminRoles } from './session.js'
@@ -24,7 +24,7 @@ router.get(
router.post(
'/douyu-fulfillment/sync',
createJsonHandler(() => ensureDouyuFulfillmentTasks(), {
createJsonHandler(() => syncDouyuFulfillmentTasks(), {
successMessage: '斗鱼领取任务已同步',
errorMessage: '同步斗鱼领取任务失败',
scope: '[admin/douyu-fulfillment/sync]',
@@ -66,6 +66,8 @@ type LiveBindingState = {
platName: string
bindReadyForConfirm: boolean
bindConfirmed: boolean
customerProfileReset?: boolean
resetReason?: string
completedAt: string | null
updatedAt: string
}
@@ -321,14 +323,24 @@ export function compareCustomerRole(task: DouyuTaskRow, live: LiveBindingState)
}
}
function statusForLive(live: LiveBindingState): string {
const BINDING_FAILURE_ISSUES = new Set([
'binding_failed',
'account_role_cooldown',
'customer_role_cooldown',
])
export function statusForLive(live: LiveBindingState): string {
if (live.customerProfileReset === true) return 'waiting_profile'
if (live.executionStatus === 'completed') return 'completed'
if (live.executionStatus === 'cancelled') return 'cancelled'
if (live.bindingStatus === 'failed' || BINDING_FAILURE_ISSUES.has(live.issueCode)) {
return 'failed'
}
if (live.executionStatus === 'manual_required') return 'manual_required'
if (live.executionStatus === 'allocated') return 'allocated'
if (live.bindConfirmed) return 'waiting_operator'
if (live.bindReadyForConfirm) return 'role_ready'
if (live.qrUrl) return 'qr_pending'
if (live.executionStatus === 'manual_required') return 'manual_required'
if (live.issueCode === 'binding_failed') return 'failed'
if (
live.issueCode === 'mapping_missing' ||
live.issueCode === 'no_eligible_account' ||
@@ -348,6 +360,7 @@ async function updateTaskFromLiveState(
live: LiveBindingState,
now: string,
) {
const resetCustomerProfile = live.customerProfileReset === true
const nextStatus = statusForLive(live)
await client.query(
`
@@ -363,17 +376,23 @@ async function updateTaskFromLiveState(
bound_area_name = $10,
bound_plat_name = $11,
binding_started_at = CASE
WHEN $19 THEN NULL
WHEN $12 <> '' THEN COALESCE(binding_started_at, NOW())
ELSE binding_started_at
END,
bound_at = CASE
WHEN $19 THEN NULL
WHEN $13 THEN COALESCE(bound_at, NOW())
ELSE bound_at
END,
completed_at = CASE
WHEN $19 THEN NULL
WHEN $14 THEN COALESCE(completed_at, NOW())
ELSE completed_at
END,
customer_role_name = CASE WHEN $19 THEN '' ELSE customer_role_name END,
customer_platform = CASE WHEN $19 THEN '' ELSE customer_platform END,
customer_system = CASE WHEN $19 THEN '' ELSE customer_system END,
qr_url = $15,
qr_generated_at = NULLIF($16, '')::timestamptz,
qr_expires_at = NULLIF($17, '')::timestamptz,
@@ -400,6 +419,7 @@ async function updateTaskFromLiveState(
live.qrGeneratedAt,
live.qrExpiresAt,
now,
resetCustomerProfile,
],
)
if (nextStatus !== task.status) {
@@ -409,6 +429,11 @@ async function updateTaskFromLiveState(
bindPhase: live.bindPhase,
})
}
if (resetCustomerProfile) {
await appendEvent(client, task.id, 'customer_profile_reset', 'integration', {
reason: String(live.resetReason || ''),
})
}
}
async function applyLiveState(task: DouyuTaskRow, live: LiveBindingState) {
@@ -760,6 +785,12 @@ export async function reconcileDouyuFulfillmentStates() {
return { checked: rows.rows.length }
}
export async function syncDouyuFulfillmentTasks() {
const synced = await ensureDouyuFulfillmentTasks()
const states = await reconcileDouyuFulfillmentStates()
return { ...synced, checked: states.checked }
}
export async function listDouyuFulfillmentTasks(
input: {
keyword?: unknown
@@ -1,7 +1,11 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { applyLiveBindingStateSnapshot, compareCustomerRole } from './douyu-fulfillment-service.js'
import {
applyLiveBindingStateSnapshot,
compareCustomerRole,
statusForLive,
} from './douyu-fulfillment-service.js'
const task = {
customer_role_name: '狗鼻子弗尼亚bd',
@@ -38,6 +42,45 @@ test('斗鱼客户资料角色名不一致时禁止确认', () => {
assert.equal(result.roleMatched, false)
})
test('绑定失败优先于旧角色确认标记', () => {
const status = statusForLive({
executionStatus: 'manual_required',
bindingStatus: 'failed',
issueCode: 'customer_role_cooldown',
bindReadyForConfirm: true,
bindConfirmed: false,
qrUrl: 'https://example.com/old-qr',
accountReady: true,
} as never)
assert.equal(status, 'failed')
})
test('绑定失败代码优先于旧待确认状态', () => {
const status = statusForLive({
executionStatus: 'role_ready',
bindingStatus: 'role_ready',
issueCode: 'binding_failed',
bindReadyForConfirm: true,
bindConfirmed: false,
qrUrl: '',
accountReady: true,
} as never)
assert.equal(status, 'failed')
})
test('已分配账号保持 allocated,不折叠成准备账号', () => {
const status = statusForLive({
executionStatus: 'allocated',
bindingStatus: 'not_started',
issueCode: '',
bindReadyForConfirm: false,
bindConfirmed: false,
qrUrl: '',
accountReady: true,
} as never)
assert.equal(status, 'allocated')
})
test('直播账号状态推送忽略空数据和无效任务', async () => {
assert.deepEqual(await applyLiveBindingStateSnapshot({ items: [] }), {
received: 0,
@@ -40,13 +40,14 @@ const { Text } = Typography
const STATUS_LABELS: Record<string, string> = {
waiting_profile: '待客户填资料',
preparing: '准备账号',
allocated: '已分配',
qr_pending: '待扫码',
role_ready: '待确认角色',
bound: '角色已绑定',
waiting_operator: '待客服处理',
processing: '处理中',
completed: '已完成',
failed: '失败',
failed: '绑定失败',
manual_required: '人工处理',
cancelled: '已取消',
}
@@ -54,6 +55,7 @@ const STATUS_LABELS: Record<string, string> = {
const STATUS_COLORS: Record<string, string> = {
waiting_profile: 'blue',
preparing: 'gold',
allocated: 'geekblue',
qr_pending: 'cyan',
role_ready: 'orange',
bound: 'green',
@@ -75,6 +77,14 @@ const SYSTEM_LABELS: Record<string, string> = {
android: '安卓',
}
const EVENT_LABELS: Record<string, string> = {
task_created: '订单进入斗鱼领取队列',
customer_link_opened: '客户打开领取链接',
customer_profile_saved: '客户保存游戏资料',
customer_profile_reset: '客服重置客户角色资料',
status_changed: '领取状态更新',
}
export default function AdminDouyuFulfillmentPage() {
const { message } = App.useApp()
const queryClient = useQueryClient()
@@ -118,7 +128,9 @@ export default function AdminDouyuFulfillmentPage() {
const syncMutation = useMutation({
mutationFn: syncAdminDouyuFulfillmentTasks,
onSuccess: async (response) => {
message.success(`同步完成:新增 ${response.data.created},更新 ${response.data.updated}`)
message.success(
`同步完成:新增 ${response.data.created},更新 ${response.data.updated},核验状态 ${response.data.checked}`,
)
await refreshAll()
},
onError: (error) => message.error(error instanceof Error ? error.message : '同步失败'),
@@ -371,7 +383,11 @@ export default function AdminDouyuFulfillmentPage() {
color: event.event_type.includes('failed') ? 'red' : 'blue',
children: (
<Space direction="vertical" size={2}>
<Text strong>{event.event_type}</Text>
<Text strong>{EVENT_LABELS[event.event_type] || event.event_type}</Text>
{event.event_type === 'customer_profile_reset' &&
event.detail_json.reason ? (
<Text>{String(event.detail_json.reason)}</Text>
) : null}
<Text type="secondary">
{formatAdminDateTime(event.created_at)} · {event.actor_type}
</Text>
@@ -34,13 +34,14 @@ const BINDING_FAILURE_ISSUES = new Set([
const STATUS_LABELS: Record<string, string> = {
waiting_profile: '等待填写资料',
preparing: '正在准备账号',
allocated: '账号已分配',
qr_pending: '等待扫码绑定',
role_ready: '请确认游戏角色',
bound: '角色已绑定',
waiting_operator: '待客服处理',
processing: '正在兑换',
completed: '领取完成',
failed: '处理失败',
failed: '角色绑定失败',
manual_required: '等待人工处理',
cancelled: '订单已取消',
}
@@ -79,10 +80,20 @@ export default function DouyuFulfillmentPage() {
const [bindingQrExpanded, setBindingQrExpanded] = useState(false)
const [nowMs, setNowMs] = useState(() => Date.now())
const autoStartRef = useRef('')
const customerRoleRef = useRef('')
const applyData = useCallback((next: DouyuCustomerFulfillment) => {
const previousRole = customerRoleRef.current
const nextRole = next.task.customer_role_name || ''
customerRoleRef.current = nextRole
setData(next)
setRoleName((current) => current || next.task.customer_role_name || '')
if (previousRole && !nextRole) {
setRoleName('')
setPlatform('wechat')
setSystem('android')
} else {
setRoleName((current) => current || nextRole)
}
if (next.task.customer_platform === 'qq' || next.task.customer_platform === 'wechat') {
setPlatform(next.task.customer_platform)
}
@@ -167,7 +178,13 @@ export default function DouyuFulfillmentPage() {
useEffect(() => {
if (!task || !live || needsProfile || live.qrUrl || live.bindConfirmed) return
if (!live.accountReady) return
if (task.status !== 'preparing' && task.status !== 'waiting_profile') return
if (
task.status !== 'preparing' &&
task.status !== 'allocated' &&
task.status !== 'waiting_profile'
) {
return
}
if (autoStartRef.current === orderNo) return
autoStartRef.current = orderNo
let cancelled = false
@@ -14,7 +14,10 @@ export function fetchAdminDouyuFulfillmentTasks(params: {
}
export function syncAdminDouyuFulfillmentTasks() {
return apiPost<{ created: number; updated: number }>('/api/v1/admin/douyu-fulfillment/sync', {})
return apiPost<{ created: number; updated: number; checked: number }>(
'/api/v1/admin/douyu-fulfillment/sync',
{},
)
}
export function fetchAdminDouyuFulfillmentDetail(orderNo: string) {
@@ -58,6 +58,8 @@ export type DouyuLiveBindingState = {
platName: string
bindReadyForConfirm: boolean
bindConfirmed: boolean
customerProfileReset?: boolean
resetReason?: string
completedAt: string | null
updatedAt: string
}