优化(直播履约): 改为订单快照事件驱动

This commit is contained in:
yml
2026-11-18 16:57:57 +08:00
parent 623a4ffa05
commit 86c8417d4b
21 changed files with 934 additions and 77 deletions
@@ -458,6 +458,8 @@ export function formatWorkOrderEvent(event: WorkOrderEvent): EventNodeStyle {
}
// —— 其他 ——
case 'auto_publish_queued':
return { title: '订单自动发布已入队', color: 'blue' }
case 'auto_publish_succeeded':
return { title: '订单自动发布成功', color: 'geekblue' }
case 'admin_note_updated':
+12 -6
View File
@@ -5,6 +5,8 @@ export type RealtimeEvent = {
version: number
type:
| 'admin_notification.changed'
| 'customer_order.changed'
| 'fulfillment_pipeline.changed'
| 'order.changed'
| 'work_order.changed'
| 'worker_finance_request.changed'
@@ -18,7 +20,8 @@ export type RealtimeEvent = {
type UseRealtimeEventsOptions = {
url: string
token: string
token?: string
allowAnonymous?: boolean
onEvent: (event: RealtimeEvent) => void
onConnected?: () => void
/**
@@ -38,6 +41,7 @@ const RECONNECT_DELAY_MS = 3_000
export function useRealtimeEvents({
url,
token,
allowAnonymous,
onEvent,
onConnected,
onResync,
@@ -53,7 +57,7 @@ export function useRealtimeEvents({
onAuthExpiredRef.current = onAuthExpired
useEffect(() => {
if (!token) return
if (!token && !allowAnonymous) return
let stopped = false
let abortController: AbortController | null = null
@@ -67,8 +71,8 @@ export function useRealtimeEvents({
const headers: Record<string, string> = {
Accept: 'text/event-stream',
Authorization: `Bearer ${token}`,
}
if (token) headers.Authorization = `Bearer ${token}`
if (lastEventId > 0) headers['Last-Event-ID'] = String(lastEventId)
let authExpired = false
void fetch(url, {
@@ -101,8 +105,8 @@ export function useRealtimeEvents({
if (eventName !== 'realtime') return
const event = normalizeRealtimeEvent(data)
if (event) {
if (event.eventId <= lastEventId) return
lastEventId = Math.max(lastEventId, event.eventId)
if (event.eventId > 0 && event.eventId <= lastEventId) return
if (event.eventId > 0) lastEventId = Math.max(lastEventId, event.eventId)
onEventRef.current(event)
}
})
@@ -131,7 +135,7 @@ export function useRealtimeEvents({
abortController?.abort()
window.clearTimeout(reconnectTimer)
}
}, [token, url])
}, [allowAnonymous, token, url])
}
async function readSseStream(
@@ -189,6 +193,8 @@ function normalizeRealtimeEvent(value: string): RealtimeEvent | null {
if (
![
'admin_notification.changed',
'customer_order.changed',
'fulfillment_pipeline.changed',
'order.changed',
'work_order.changed',
'worker_finance_request.changed',
@@ -559,6 +559,14 @@ function applyAdminRealtimeEvent(
})
}
if (
event.type === 'fulfillment_pipeline.changed' &&
event.scopes.includes('admin_fulfillment_pipelines')
) {
void queryClient.invalidateQueries({ queryKey: ['fulfillment-pipelines'] })
void queryClient.invalidateQueries({ queryKey: ['fulfillment-pending'] })
}
if (event.type === 'work_order.changed' && event.scopes.includes('admin_work_orders')) {
// 拼单明细是独立查询,工单列表快照更新时也要同步刷新当前打开的明细。
void queryClient.invalidateQueries({
@@ -1322,7 +1322,6 @@ function PipelinesPanel() {
const query = useQuery({
queryKey: ['fulfillment-pipelines'],
queryFn: fetchPipelineStatus,
refetchInterval: 30_000,
})
const runMutation = useMutation({
@@ -1338,7 +1337,7 @@ function PipelinesPanel() {
const columns = [
{ title: '管道', dataIndex: 'label', width: 130 },
{
title: '定时任务',
title: '兜底任务',
width: 150,
render: (_: unknown, row: FinancePipelineStatus) =>
row.scheduler ? (
@@ -1402,8 +1401,8 @@ function PipelinesPanel() {
}
>
<Typography.Paragraph type="secondary">
六个管道由定时任务自动执行,无需人工干预;这里只用于查看进度、
排障和补跑。默认间隔:渠道判定/载体 60s,商品/成本 300s,事实/总账 600s。
新订单会由入库事件即时推进渠道判定和载体补建;定时任务只做漏事件兜底。 本页随后台 SSE
自动刷新,用于查看进度、排障和补跑。
</Typography.Paragraph>
<PercentTable
rowKey="pipeline"
@@ -13,7 +13,6 @@ import { useParams } from 'react-router'
import {
confirmDouyuBinding,
fetchDouyuFulfillment,
pollDouyuBinding,
saveDouyuProfile,
startDouyuBinding,
} from '@/services/douyu-fulfillment'
@@ -23,8 +22,8 @@ import type {
DouyuCustomerSystem,
} from '@/types/douyu-fulfillment'
import { formatAdminDateTime } from '@/utils/admin-time'
import { useRealtimeEvents } from '@/hooks/useRealtimeEvents'
const POLL_INTERVAL_MS = 3000
const BINDING_FAILURE_ISSUES = new Set([
'binding_failed',
'account_role_cooldown',
@@ -129,27 +128,29 @@ export default function DouyuFulfillmentPage() {
void load()
}, [load])
useRealtimeEvents({
url: orderNo ? `/api/v1/douyu-fulfillment/${encodeURIComponent(orderNo)}/realtime` : '',
allowAnonymous: true,
onConnected: () => {
void load(true)
},
onResync: () => {
void load(true)
},
onEvent: (event) => {
if (
event.type === 'customer_order.changed' &&
event.scopes.includes(`customer_order:${orderNo}`)
) {
void load(true)
}
},
})
const task = data?.task
const live = data?.live
const needsProfile = Boolean(task && !task.customer_role_name)
const bindingFailed = Boolean(live && BINDING_FAILURE_ISSUES.has(live.issueCode))
const activeBinding = Boolean(
task &&
!needsProfile &&
!bindingFailed &&
!['completed', 'cancelled'].includes(task.status) &&
!live?.bindConfirmed,
)
useEffect(() => {
if (!activeBinding || !orderNo) return
const timer = window.setInterval(() => {
void pollDouyuBinding(orderNo)
.then((response) => applyData(response.data))
.catch(() => undefined)
}, POLL_INTERVAL_MS)
return () => window.clearInterval(timer)
}, [activeBinding, applyData, orderNo])
useEffect(() => {
const url = live?.qrUrl || ''