改造实时事件缓存同步
This commit is contained in:
@@ -2,6 +2,7 @@ import { useEffect, useRef } from 'react'
|
||||
|
||||
export type RealtimeEvent = {
|
||||
eventId: number
|
||||
version: number
|
||||
type:
|
||||
| 'admin_notification.changed'
|
||||
| 'order.changed'
|
||||
@@ -10,6 +11,8 @@ export type RealtimeEvent = {
|
||||
| 'worker_wallet.changed'
|
||||
entityId: number
|
||||
scopes: string[]
|
||||
operation: 'upsert' | 'remove' | 'refresh'
|
||||
data?: unknown
|
||||
occurredAt: string
|
||||
}
|
||||
|
||||
@@ -35,18 +38,21 @@ export function useRealtimeEvents({ url, token, onEvent, onConnected }: UseRealt
|
||||
let stopped = false
|
||||
let abortController: AbortController | null = null
|
||||
let reconnectTimer = 0
|
||||
let lastEventId = 0
|
||||
|
||||
const connect = () => {
|
||||
if (stopped || document.visibilityState !== 'visible') return
|
||||
abortController?.abort()
|
||||
abortController = new AbortController()
|
||||
|
||||
const headers: Record<string, string> = {
|
||||
Accept: 'text/event-stream',
|
||||
Authorization: `Bearer ${token}`,
|
||||
}
|
||||
if (lastEventId > 0) headers['Last-Event-ID'] = String(lastEventId)
|
||||
void fetch(url, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
Accept: 'text/event-stream',
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
headers,
|
||||
cache: 'no-store',
|
||||
signal: abortController.signal,
|
||||
})
|
||||
@@ -58,7 +64,11 @@ export function useRealtimeEvents({ url, token, onEvent, onConnected }: UseRealt
|
||||
await readSseStream(response.body, (eventName, data) => {
|
||||
if (eventName !== 'realtime') return
|
||||
const event = normalizeRealtimeEvent(data)
|
||||
if (event) onEventRef.current(event)
|
||||
if (event) {
|
||||
if (event.eventId <= lastEventId) return
|
||||
lastEventId = Math.max(lastEventId, event.eventId)
|
||||
onEventRef.current(event)
|
||||
}
|
||||
})
|
||||
})
|
||||
.catch(() => undefined)
|
||||
@@ -153,11 +163,17 @@ function normalizeRealtimeEvent(value: string): RealtimeEvent | null {
|
||||
}
|
||||
return {
|
||||
eventId: Number(parsed.eventId || 0),
|
||||
version: Number(parsed.version || parsed.eventId || 0),
|
||||
type: type as RealtimeEvent['type'],
|
||||
entityId: Number(parsed.entityId || 0),
|
||||
scopes: Array.isArray(parsed.scopes)
|
||||
? parsed.scopes.map((item) => String(item || '')).filter(Boolean)
|
||||
: [],
|
||||
operation:
|
||||
parsed.operation === 'upsert' || parsed.operation === 'remove'
|
||||
? parsed.operation
|
||||
: 'refresh',
|
||||
data: parsed.data,
|
||||
occurredAt: String(parsed.occurredAt || ''),
|
||||
}
|
||||
} catch {
|
||||
|
||||
@@ -32,7 +32,7 @@ import {
|
||||
} from 'antd'
|
||||
import type { MenuProps } from 'antd'
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { useMemo, useState } from 'react'
|
||||
import { Outlet, useLocation, useNavigate } from 'react-router'
|
||||
|
||||
import {
|
||||
@@ -53,7 +53,6 @@ import { useRealtimeEvents, type RealtimeEvent } from '@/hooks/useRealtimeEvents
|
||||
|
||||
const SIDEBAR_COLLAPSED_KEY = 'react-admin-sidebar-collapsed'
|
||||
const NOTIFICATION_SOUND_KEY = 'admin-notification-sound-enabled'
|
||||
const NOTIFICATION_SOUND_COOLDOWN_MS = 30_000
|
||||
|
||||
export default function AdminLayout() {
|
||||
const navigate = useNavigate()
|
||||
@@ -69,22 +68,16 @@ export default function AdminLayout() {
|
||||
const [soundEnabled, setSoundEnabled] = useState(
|
||||
() => window.localStorage.getItem(NOTIFICATION_SOUND_KEY) === '1',
|
||||
)
|
||||
const seenNotificationVersions = useRef<Map<number, string> | null>(null)
|
||||
const lastSoundAt = useRef(0)
|
||||
|
||||
const devMockStatusQuery = useQuery({
|
||||
queryKey: ['admin-dev-mock-status'],
|
||||
queryFn: () => fetchDevMockStatus(),
|
||||
staleTime: 60_000,
|
||||
retry: false,
|
||||
})
|
||||
const devMockEnabled = Boolean(devMockStatusQuery.data?.data?.enabled)
|
||||
const notificationsQuery = useQuery({
|
||||
queryKey: ['admin-notifications'],
|
||||
queryFn: fetchAdminNotifications,
|
||||
refetchInterval: 10_000,
|
||||
refetchIntervalInBackground: false,
|
||||
refetchOnWindowFocus: true,
|
||||
retry: false,
|
||||
})
|
||||
const notifications = notificationsQuery.data?.data.items || []
|
||||
@@ -93,39 +86,9 @@ export default function AdminLayout() {
|
||||
useRealtimeEvents({
|
||||
url: '/api/v1/admin/realtime',
|
||||
token: getAdminToken(),
|
||||
onEvent: (event) => handleAdminRealtimeEvent(event, queryClient),
|
||||
onConnected: () => {
|
||||
void invalidateAdminRealtimeQueries(queryClient)
|
||||
},
|
||||
onEvent: (event) => applyAdminRealtimeEvent(event, queryClient),
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
const currentVersions = new Map(
|
||||
notifications.map((notification) => [notification.notificationId, notification.updatedAt]),
|
||||
)
|
||||
if (seenNotificationVersions.current === null) {
|
||||
seenNotificationVersions.current = currentVersions
|
||||
return
|
||||
}
|
||||
const changedNotifications = notifications.filter(
|
||||
(notification) =>
|
||||
seenNotificationVersions.current?.get(notification.notificationId) !==
|
||||
notification.updatedAt,
|
||||
)
|
||||
seenNotificationVersions.current = currentVersions
|
||||
if (changedNotifications.length === 0) return
|
||||
|
||||
void Promise.all([
|
||||
queryClient.invalidateQueries({ queryKey: ['admin-worker-platform-finance-requests'] }),
|
||||
queryClient.invalidateQueries({ queryKey: ['admin-worker-platform-orders'] }),
|
||||
queryClient.invalidateQueries({ queryKey: ['admin-worker-platform-summary'] }),
|
||||
])
|
||||
if (soundEnabled && Date.now() - lastSoundAt.current >= NOTIFICATION_SOUND_COOLDOWN_MS) {
|
||||
lastSoundAt.current = Date.now()
|
||||
announceNotification(selectNotificationToAnnounce(changedNotifications))
|
||||
}
|
||||
}, [notifications, queryClient, soundEnabled])
|
||||
|
||||
const menuItems = useMemo<MenuProps['items']>(() => {
|
||||
const operationItems: MenuProps['items'] = [
|
||||
{ key: '/admin/dashboard', icon: <DashboardOutlined />, label: '概览' },
|
||||
@@ -354,38 +317,215 @@ export default function AdminLayout() {
|
||||
)
|
||||
}
|
||||
|
||||
function handleAdminRealtimeEvent(
|
||||
function applyAdminRealtimeEvent(
|
||||
event: RealtimeEvent,
|
||||
queryClient: ReturnType<typeof useQueryClient>,
|
||||
) {
|
||||
if (event.type === 'admin_notification.changed') {
|
||||
void queryClient.invalidateQueries({ queryKey: ['admin-notifications'] })
|
||||
if (event.type === 'admin_notification.changed' && isRecord(event.data)) {
|
||||
queryClient.setQueryData(['admin-notifications'], (current: unknown) => {
|
||||
if (!isRecord(current) || !isRecord(current.data)) return current
|
||||
const currentData = current.data as { items?: unknown[]; pendingCount?: number }
|
||||
const items = Array.isArray(currentData.items) ? currentData.items : []
|
||||
const notification = event.data as Record<string, unknown>
|
||||
const notificationId = Number(notification.notificationId || event.entityId)
|
||||
const nextItems =
|
||||
event.operation === 'remove'
|
||||
? items.filter(
|
||||
(item) =>
|
||||
Number((item as { notificationId?: unknown })?.notificationId) !== notificationId,
|
||||
)
|
||||
: upsertById(items, notification, 'notificationId', true)
|
||||
return {
|
||||
...current,
|
||||
data: {
|
||||
...currentData,
|
||||
items: nextItems,
|
||||
pendingCount:
|
||||
event.operation === 'remove'
|
||||
? Math.max(0, Number(currentData.pendingCount || 0) - 1)
|
||||
: currentData.pendingCount,
|
||||
},
|
||||
}
|
||||
})
|
||||
}
|
||||
if (event.type === 'order.changed') {
|
||||
void queryClient.invalidateQueries({ queryKey: ['admin-orders'] })
|
||||
void queryClient.invalidateQueries({ queryKey: ['admin-order-detail', String(event.entityId)] })
|
||||
void queryClient.invalidateQueries({ queryKey: ['admin-tasks'] })
|
||||
void queryClient.invalidateQueries({ queryKey: ['admin-dashboard-summary'] })
|
||||
|
||||
if (
|
||||
event.type === 'work_order.changed' &&
|
||||
event.scopes.includes('admin_work_orders') &&
|
||||
isRecord(event.data)
|
||||
) {
|
||||
const data = event.data
|
||||
patchAdminWorkOrderCaches(queryClient, { ...event, data })
|
||||
}
|
||||
if (event.type === 'work_order.changed') {
|
||||
void queryClient.invalidateQueries({ queryKey: ['admin-worker-platform-orders'] })
|
||||
void queryClient.invalidateQueries({ queryKey: ['admin-worker-platform-summary'] })
|
||||
|
||||
if (
|
||||
event.type === 'worker_finance_request.changed' &&
|
||||
event.scopes.includes('admin_worker_finance') &&
|
||||
isRecord(event.data)
|
||||
) {
|
||||
const data = event.data
|
||||
queryClient.setQueriesData(
|
||||
{ queryKey: ['admin-worker-platform-finance-requests'] },
|
||||
(current: unknown) => patchFinanceRequestListEnvelope(current, { ...event, data }),
|
||||
)
|
||||
}
|
||||
if (event.type === 'worker_finance_request.changed') {
|
||||
void queryClient.invalidateQueries({ queryKey: ['admin-worker-platform-finance-requests'] })
|
||||
|
||||
if (
|
||||
event.type === 'order.changed' &&
|
||||
event.scopes.includes('admin_orders') &&
|
||||
isRecord(event.data)
|
||||
) {
|
||||
const payload = event.data
|
||||
if (isRecord(payload.order)) {
|
||||
patchAdminOrderCaches(queryClient, { ...event, data: payload.order })
|
||||
}
|
||||
if (isRecord(payload.dashboard)) {
|
||||
queryClient.setQueryData(['admin-dashboard-summary'], (current: unknown) => {
|
||||
if (!isRecord(current)) return current
|
||||
return { ...current, data: payload.dashboard }
|
||||
})
|
||||
}
|
||||
if (Array.isArray(payload.tasks)) {
|
||||
patchAdminTaskCaches(queryClient, payload.tasks)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function invalidateAdminRealtimeQueries(queryClient: ReturnType<typeof useQueryClient>) {
|
||||
return Promise.all([
|
||||
queryClient.invalidateQueries({ queryKey: ['admin-notifications'] }),
|
||||
queryClient.invalidateQueries({ queryKey: ['admin-orders'] }),
|
||||
queryClient.invalidateQueries({ queryKey: ['admin-tasks'] }),
|
||||
queryClient.invalidateQueries({ queryKey: ['admin-dashboard-summary'] }),
|
||||
queryClient.invalidateQueries({ queryKey: ['admin-worker-platform-orders'] }),
|
||||
queryClient.invalidateQueries({ queryKey: ['admin-worker-platform-finance-requests'] }),
|
||||
queryClient.invalidateQueries({ queryKey: ['admin-worker-platform-summary'] }),
|
||||
])
|
||||
function patchAdminWorkOrderCaches(
|
||||
queryClient: ReturnType<typeof useQueryClient>,
|
||||
event: RealtimeEvent,
|
||||
) {
|
||||
const item = event.data as {
|
||||
workOrderId?: unknown
|
||||
status?: unknown
|
||||
productName?: unknown
|
||||
platformOrderId?: unknown
|
||||
worker?: { workerId?: unknown } | null
|
||||
}
|
||||
for (const [queryKey, current] of queryClient.getQueriesData({
|
||||
queryKey: ['admin-worker-platform-orders'],
|
||||
})) {
|
||||
const statuses = String(queryKey[1] || '')
|
||||
.split(',')
|
||||
.filter(Boolean)
|
||||
const keyword = String(queryKey[2] || '')
|
||||
const workerId = Number(queryKey[3] || 0)
|
||||
const targetWorkOrderId = Number(queryKey[4] || 0)
|
||||
const page = Number(queryKey[5] || 1)
|
||||
const matches =
|
||||
(!statuses.length || statuses.includes(String(item.status || ''))) &&
|
||||
matchesWorkOrderKeyword(item, keyword) &&
|
||||
(!workerId || workerId === Number(item.worker?.workerId || 0)) &&
|
||||
(!targetWorkOrderId || targetWorkOrderId === Number(item.workOrderId || 0))
|
||||
const shouldInsert = event.operation === 'upsert' && page === 1 && matches
|
||||
const operation = event.operation === 'remove' || !matches ? 'remove' : 'upsert'
|
||||
queryClient.setQueryData(
|
||||
queryKey,
|
||||
patchWorkOrderListEnvelope(current, { ...event, operation }, shouldInsert),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
function patchAdminTaskCaches(queryClient: ReturnType<typeof useQueryClient>, tasks: unknown[]) {
|
||||
queryClient.setQueriesData({ queryKey: ['admin-tasks'] }, (current: unknown) => {
|
||||
if (!isRecord(current) || !isRecord(current.data) || !Array.isArray(current.data.items)) {
|
||||
return current
|
||||
}
|
||||
const items = current.data.items as unknown[]
|
||||
const nextItems = items.map((item) => {
|
||||
const taskId = Number((item as { taskId?: unknown }).taskId || 0)
|
||||
return (
|
||||
tasks.find((task) => Number((task as { taskId?: unknown }).taskId || 0) === taskId) || item
|
||||
)
|
||||
})
|
||||
return { ...current, data: { ...current.data, items: nextItems } }
|
||||
})
|
||||
}
|
||||
|
||||
function patchAdminOrderCaches(
|
||||
queryClient: ReturnType<typeof useQueryClient>,
|
||||
event: RealtimeEvent,
|
||||
) {
|
||||
const item = event.data as { orderId?: unknown; platformOrderId?: unknown; payStatus?: unknown }
|
||||
for (const [queryKey, current] of queryClient.getQueriesData({ queryKey: ['admin-orders'] })) {
|
||||
const params = isRecord(queryKey[1]) ? queryKey[1] : {}
|
||||
const page = Number(params.page || 1)
|
||||
const matches =
|
||||
(!String(params.platformOrderId || '').trim() ||
|
||||
String(item.platformOrderId || '') === String(params.platformOrderId || '').trim()) &&
|
||||
(!String(params.payStatus || '').trim() ||
|
||||
String(item.payStatus || '') === String(params.payStatus || '').trim())
|
||||
const shouldInsert = event.operation === 'upsert' && page === 1 && matches && !params.skuCode
|
||||
const operation = event.operation === 'remove' || !matches ? 'remove' : 'upsert'
|
||||
queryClient.setQueryData(
|
||||
queryKey,
|
||||
patchAdminOrderListEnvelope(current, { ...event, operation }, shouldInsert),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
function patchAdminOrderListEnvelope(current: unknown, event: RealtimeEvent, insert = false) {
|
||||
if (!isRecord(current) || !isRecord(current.data) || !Array.isArray(current.data.items)) {
|
||||
return current
|
||||
}
|
||||
const id = Number((event.data as { orderId?: unknown }).orderId || event.entityId)
|
||||
const items = current.data.items as unknown[]
|
||||
const nextItems =
|
||||
event.operation === 'remove'
|
||||
? items.filter((entry) => Number((entry as { orderId?: unknown })?.orderId) !== id)
|
||||
: upsertById(items, event.data, 'orderId', insert)
|
||||
return { ...current, data: { ...current.data, items: nextItems } }
|
||||
}
|
||||
|
||||
function patchWorkOrderListEnvelope(current: unknown, event: RealtimeEvent, insert = false) {
|
||||
if (!isRecord(current) || !isRecord(current.data) || !Array.isArray(current.data.items)) {
|
||||
return current
|
||||
}
|
||||
const item = event.data
|
||||
const id = Number((item as { workOrderId?: unknown }).workOrderId || event.entityId)
|
||||
const items = current.data.items as unknown[]
|
||||
const nextItems =
|
||||
event.operation === 'remove'
|
||||
? items.filter((entry) => Number((entry as { workOrderId?: unknown })?.workOrderId) !== id)
|
||||
: upsertById(items, item, 'workOrderId', insert)
|
||||
return { ...current, data: { ...current.data, items: nextItems } }
|
||||
}
|
||||
|
||||
function patchFinanceRequestListEnvelope(current: unknown, event: RealtimeEvent) {
|
||||
if (!isRecord(current) || !isRecord(current.data) || !Array.isArray(current.data.items)) {
|
||||
return current
|
||||
}
|
||||
const id = Number((event.data as { requestId?: unknown }).requestId || event.entityId)
|
||||
const items = current.data.items as unknown[]
|
||||
const nextItems =
|
||||
event.operation === 'remove'
|
||||
? items.filter((entry) => Number((entry as { requestId?: unknown })?.requestId) !== id)
|
||||
: upsertById(items, event.data, 'requestId')
|
||||
return { ...current, data: { ...current.data, items: nextItems } }
|
||||
}
|
||||
|
||||
function upsertById(items: unknown[], nextItem: unknown, idKey: string, insert = false) {
|
||||
const id = Number((nextItem as Record<string, unknown>)[idKey] || 0)
|
||||
const index = items.findIndex(
|
||||
(item) => Number((item as Record<string, unknown>)?.[idKey] || 0) === id,
|
||||
)
|
||||
if (index < 0) return insert ? [nextItem, ...items] : items
|
||||
return items.map((item, itemIndex) => (itemIndex === index ? nextItem : item))
|
||||
}
|
||||
|
||||
function matchesWorkOrderKeyword(
|
||||
item: { productName?: unknown; platformOrderId?: unknown },
|
||||
keyword: string,
|
||||
) {
|
||||
const normalizedKeyword = keyword.trim().toLowerCase()
|
||||
if (!normalizedKeyword) return true
|
||||
return [item.productName, item.platformOrderId]
|
||||
.map((value) => String(value || '').toLowerCase())
|
||||
.some((value) => value.includes(normalizedKeyword))
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return Boolean(value && typeof value === 'object' && !Array.isArray(value))
|
||||
}
|
||||
|
||||
type NotificationAlertKind =
|
||||
@@ -396,60 +536,6 @@ type NotificationAlertKind =
|
||||
| 'reminder'
|
||||
| 'default'
|
||||
|
||||
function selectNotificationToAnnounce(notifications: AdminNotification[]) {
|
||||
return [...notifications].sort((left, right) => {
|
||||
const priorityDiff = notificationAlertRank(right) - notificationAlertRank(left)
|
||||
if (priorityDiff !== 0) return priorityDiff
|
||||
return right.notificationId - left.notificationId
|
||||
})[0]
|
||||
}
|
||||
|
||||
function notificationAlertRank(notification: AdminNotification) {
|
||||
if (notification.notificationType === 'worker_acceptance_reminded') return 3
|
||||
if (notification.notificationType === 'worker_withdraw_requested') return 2
|
||||
return 1
|
||||
}
|
||||
|
||||
function announceNotification(notification?: AdminNotification) {
|
||||
if (!notification?.soundEnabled) return
|
||||
const { text, kind } = resolveNotificationAnnouncement(notification)
|
||||
playNotificationSound(kind)
|
||||
if (!('speechSynthesis' in window) || typeof SpeechSynthesisUtterance === 'undefined') return
|
||||
|
||||
try {
|
||||
window.speechSynthesis.cancel()
|
||||
const utterance = new SpeechSynthesisUtterance(text)
|
||||
utterance.lang = 'zh-CN'
|
||||
utterance.rate = 1.05
|
||||
utterance.volume = 0.9
|
||||
window.speechSynthesis.speak(utterance)
|
||||
} catch {
|
||||
// 语音播报不可用时,前面的区分音调仍会提示新待办。
|
||||
}
|
||||
}
|
||||
|
||||
function resolveNotificationAnnouncement(notification?: AdminNotification): {
|
||||
text: string
|
||||
kind: NotificationAlertKind
|
||||
} {
|
||||
if (notification?.notificationType === 'worker_acceptance_reminded') {
|
||||
return { text: '你有新的催验收工单', kind: 'reminder' }
|
||||
}
|
||||
if (notification?.notificationType === 'worker_withdraw_requested') {
|
||||
return { text: '你有新的提现申请', kind: 'withdraw' }
|
||||
}
|
||||
if (notification?.notificationType === 'worker_recharge_requested') {
|
||||
return { text: '你有新的充值申请', kind: 'recharge' }
|
||||
}
|
||||
if (notification?.notificationType === 'worker_acceptance_submitted') {
|
||||
return { text: '你有新的待验收工单', kind: 'acceptance' }
|
||||
}
|
||||
if (notification?.notificationType === 'work_order_material_required') {
|
||||
return { text: '你有工单待补资料', kind: 'material' }
|
||||
}
|
||||
return { text: '你有新的待处理事项', kind: 'default' }
|
||||
}
|
||||
|
||||
function playNotificationSound(kind: NotificationAlertKind) {
|
||||
try {
|
||||
const audio = new AudioContext()
|
||||
@@ -477,7 +563,7 @@ function playNotificationSound(kind: NotificationAlertKind) {
|
||||
oscillator.stop(audio.currentTime + sequence.length * duration)
|
||||
oscillator.addEventListener('ended', () => void audio.close())
|
||||
} catch {
|
||||
// 部分浏览器禁止音频或不支持 Web Audio,不影响待办轮询。
|
||||
// 部分浏览器禁止音频或不支持 Web Audio,不影响待办展示。
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -32,18 +32,15 @@ export default function WorkerLayout() {
|
||||
const location = useLocation()
|
||||
const isMobile = useIsMobile()
|
||||
const { message, modal } = App.useApp()
|
||||
const queryClient = useQueryClient()
|
||||
const username = getWorkerUsername() || '打手'
|
||||
const status = getWorkerStatus()
|
||||
const queryClient = useQueryClient()
|
||||
const currentKey = resolveSelectedKey(location.pathname)
|
||||
|
||||
useRealtimeEvents({
|
||||
url: '/api/v1/worker/realtime',
|
||||
token: getWorkerToken(),
|
||||
onEvent: (event) => handleWorkerRealtimeEvent(event, queryClient),
|
||||
onConnected: () => {
|
||||
void invalidateWorkerRealtimeQueries(queryClient)
|
||||
},
|
||||
onEvent: (event) => applyWorkerRealtimeEvent(event, queryClient),
|
||||
})
|
||||
|
||||
async function submitLogout() {
|
||||
@@ -156,40 +153,179 @@ export default function WorkerLayout() {
|
||||
)
|
||||
}
|
||||
|
||||
function handleWorkerRealtimeEvent(
|
||||
function applyWorkerRealtimeEvent(
|
||||
event: RealtimeEvent,
|
||||
queryClient: ReturnType<typeof useQueryClient>,
|
||||
) {
|
||||
if (event.type === 'work_order.changed') {
|
||||
if (event.scopes.includes('worker_hall')) {
|
||||
void queryClient.invalidateQueries({ queryKey: ['worker-hall-orders'] })
|
||||
void queryClient.invalidateQueries({ queryKey: ['worker-hall-summary'] })
|
||||
}
|
||||
if (event.type === 'work_order.changed' && isRecord(event.data)) {
|
||||
const data = event.data
|
||||
if (event.scopes.includes('worker_my_orders')) {
|
||||
void queryClient.invalidateQueries({ queryKey: ['worker-my-orders'] })
|
||||
void queryClient.invalidateQueries({ queryKey: ['worker-my-orders-overview'] })
|
||||
patchWorkerMyOrderCaches(queryClient, { ...event, data })
|
||||
}
|
||||
if (event.scopes.includes('worker_hall')) {
|
||||
patchWorkerHallCaches(queryClient, { ...event, data })
|
||||
}
|
||||
}
|
||||
if (event.type === 'worker_finance_request.changed') {
|
||||
void queryClient.invalidateQueries({ queryKey: ['worker-finance-requests'] })
|
||||
void queryClient.invalidateQueries({ queryKey: ['worker-profile'] })
|
||||
|
||||
if (event.type === 'worker_wallet.changed' && isRecord(event.data)) {
|
||||
const walletData = event.data
|
||||
queryClient.setQueryData(['worker-profile'], (current: unknown) => {
|
||||
if (!isRecord(current) || !isRecord(current.data) || !isRecord(current.data.worker))
|
||||
return current
|
||||
return {
|
||||
...current,
|
||||
data: {
|
||||
...current.data,
|
||||
worker: { ...current.data.worker, wallet: walletData.wallet || walletData },
|
||||
},
|
||||
}
|
||||
})
|
||||
}
|
||||
if (event.type === 'worker_wallet.changed') {
|
||||
void queryClient.invalidateQueries({ queryKey: ['worker-wallet-ledgers'] })
|
||||
void queryClient.invalidateQueries({ queryKey: ['worker-profile'] })
|
||||
|
||||
if (event.type === 'worker_finance_request.changed' && isRecord(event.data)) {
|
||||
const data = event.data
|
||||
queryClient.setQueriesData({ queryKey: ['worker-finance-requests'] }, (current: unknown) =>
|
||||
patchFinanceRequestListEnvelope(current, { ...event, data }),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
function invalidateWorkerRealtimeQueries(queryClient: ReturnType<typeof useQueryClient>) {
|
||||
return Promise.all([
|
||||
queryClient.invalidateQueries({ queryKey: ['worker-hall-orders'] }),
|
||||
queryClient.invalidateQueries({ queryKey: ['worker-hall-summary'] }),
|
||||
queryClient.invalidateQueries({ queryKey: ['worker-my-orders'] }),
|
||||
queryClient.invalidateQueries({ queryKey: ['worker-my-orders-overview'] }),
|
||||
queryClient.invalidateQueries({ queryKey: ['worker-profile'] }),
|
||||
queryClient.invalidateQueries({ queryKey: ['worker-wallet-ledgers'] }),
|
||||
queryClient.invalidateQueries({ queryKey: ['worker-finance-requests'] }),
|
||||
])
|
||||
function patchWorkerMyOrderCaches(
|
||||
queryClient: ReturnType<typeof useQueryClient>,
|
||||
event: RealtimeEvent,
|
||||
) {
|
||||
for (const [queryKey, current] of queryClient.getQueriesData({
|
||||
queryKey: ['worker-my-orders'],
|
||||
})) {
|
||||
const status = String(queryKey[1] || '')
|
||||
const keyword = String(queryKey[2] || '')
|
||||
const page = Number(queryKey[3] || 1)
|
||||
const item = event.data as {
|
||||
status?: unknown
|
||||
productName?: unknown
|
||||
platformOrderId?: unknown
|
||||
}
|
||||
const matchesStatus = !status || status === String(item.status || '')
|
||||
const matchesKeyword = matchesWorkOrderKeyword(item, keyword)
|
||||
const matches = matchesStatus && matchesKeyword
|
||||
const shouldInsert = event.operation === 'upsert' && page === 1 && matches
|
||||
const operation = event.operation === 'remove' || !matches ? 'remove' : 'upsert'
|
||||
queryClient.setQueryData(
|
||||
queryKey,
|
||||
patchWorkOrderListEnvelope(current, { ...event, operation }, shouldInsert),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
function patchWorkerHallCaches(
|
||||
queryClient: ReturnType<typeof useQueryClient>,
|
||||
event: RealtimeEvent,
|
||||
) {
|
||||
const workerSnapshot = applyWorkerDepositRule(queryClient, event.data)
|
||||
const item = workerSnapshot as {
|
||||
status?: unknown
|
||||
categoryId?: unknown
|
||||
productName?: unknown
|
||||
platformOrderId?: unknown
|
||||
}
|
||||
for (const [queryKey, current] of queryClient.getQueriesData({
|
||||
queryKey: ['worker-hall-orders'],
|
||||
})) {
|
||||
const keyword = String(queryKey[1] || '')
|
||||
const categoryId = Number(queryKey[2] || 0)
|
||||
const matchesCategory = !categoryId || categoryId === Number(item.categoryId || 0)
|
||||
const matches =
|
||||
String(item.status || '') === 'open' &&
|
||||
matchesCategory &&
|
||||
matchesWorkOrderKeyword(item, keyword)
|
||||
const shouldInsert = event.operation === 'upsert' && matches
|
||||
const operation = event.operation === 'remove' || !matches ? 'remove' : 'upsert'
|
||||
queryClient.setQueryData(
|
||||
queryKey,
|
||||
patchInfiniteWorkOrderEnvelope(
|
||||
current,
|
||||
{ ...event, data: workerSnapshot, operation },
|
||||
shouldInsert,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
function applyWorkerDepositRule(queryClient: ReturnType<typeof useQueryClient>, data: unknown) {
|
||||
if (!isRecord(data)) return data
|
||||
const profile = queryClient.getQueryData(['worker-profile'])
|
||||
const depositFreeAmount =
|
||||
isRecord(profile) && isRecord(profile.data) && isRecord(profile.data.worker)
|
||||
? Number(
|
||||
(profile.data.worker.level as { permissions?: { depositFreeAmount?: unknown } } | null)
|
||||
?.permissions?.depositFreeAmount || 0,
|
||||
)
|
||||
: 0
|
||||
const requiredDepositAmount = Number(data.requiredDepositAmount || 0)
|
||||
return {
|
||||
...data,
|
||||
freezeDepositAmount: Math.max(0, requiredDepositAmount - depositFreeAmount),
|
||||
}
|
||||
}
|
||||
|
||||
function matchesWorkOrderKeyword(
|
||||
item: { productName?: unknown; platformOrderId?: unknown },
|
||||
keyword: string,
|
||||
) {
|
||||
const normalizedKeyword = keyword.trim().toLowerCase()
|
||||
if (!normalizedKeyword) return true
|
||||
return [item.productName, item.platformOrderId]
|
||||
.map((value) => String(value || '').toLowerCase())
|
||||
.some((value) => value.includes(normalizedKeyword))
|
||||
}
|
||||
|
||||
function patchWorkOrderListEnvelope(current: unknown, event: RealtimeEvent, insert = false) {
|
||||
if (!isRecord(current) || !isRecord(current.data) || !Array.isArray(current.data.items)) {
|
||||
return current
|
||||
}
|
||||
const id = Number((event.data as { workOrderId?: unknown }).workOrderId || event.entityId)
|
||||
const items = current.data.items as unknown[]
|
||||
const nextItems =
|
||||
event.operation === 'remove'
|
||||
? items.filter((entry) => Number((entry as { workOrderId?: unknown })?.workOrderId) !== id)
|
||||
: upsertById(items, event.data, 'workOrderId', insert)
|
||||
return { ...current, data: { ...current.data, items: nextItems } }
|
||||
}
|
||||
|
||||
function patchInfiniteWorkOrderEnvelope(current: unknown, event: RealtimeEvent, insert = false) {
|
||||
if (!isRecord(current) || !Array.isArray(current.pages)) return current
|
||||
return {
|
||||
...current,
|
||||
pages: current.pages.map((page: unknown, index) =>
|
||||
patchWorkOrderListEnvelope(page, event, insert && index === 0),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
function patchFinanceRequestListEnvelope(current: unknown, event: RealtimeEvent) {
|
||||
if (!isRecord(current) || !isRecord(current.data) || !Array.isArray(current.data.items)) {
|
||||
return current
|
||||
}
|
||||
const id = Number((event.data as { requestId?: unknown }).requestId || event.entityId)
|
||||
const items = current.data.items as unknown[]
|
||||
const nextItems =
|
||||
event.operation === 'remove'
|
||||
? items.filter((entry) => Number((entry as { requestId?: unknown })?.requestId) !== id)
|
||||
: upsertById(items, event.data, 'requestId')
|
||||
return { ...current, data: { ...current.data, items: nextItems } }
|
||||
}
|
||||
|
||||
function upsertById(items: unknown[], nextItem: unknown, idKey: string, insert = false) {
|
||||
const id = Number((nextItem as Record<string, unknown>)[idKey] || 0)
|
||||
const index = items.findIndex(
|
||||
(item) => Number((item as Record<string, unknown>)?.[idKey] || 0) === id,
|
||||
)
|
||||
if (index < 0) return insert ? [nextItem, ...items] : items
|
||||
return items.map((item, itemIndex) => (itemIndex === index ? nextItem : item))
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return Boolean(value && typeof value === 'object' && !Array.isArray(value))
|
||||
}
|
||||
|
||||
function resolveSelectedKey(pathname: string) {
|
||||
|
||||
@@ -14,7 +14,10 @@ import './styles/main.css'
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
// 页面切换和网络恢复不主动重新请求,数据由首次加载、用户操作或手动刷新触发更新。
|
||||
staleTime: Infinity,
|
||||
refetchOnWindowFocus: false,
|
||||
refetchOnReconnect: false,
|
||||
retry: 1,
|
||||
},
|
||||
},
|
||||
|
||||
@@ -19,7 +19,6 @@ import {
|
||||
Modal,
|
||||
Space,
|
||||
Spin,
|
||||
Switch,
|
||||
Tabs,
|
||||
Tag,
|
||||
Tooltip,
|
||||
@@ -57,22 +56,8 @@ export default function WorkerHallPage() {
|
||||
const [leaderboardOpen, setLeaderboardOpen] = useState(false)
|
||||
const [sharingQuantity, setSharingQuantity] = useState(1)
|
||||
const [submittingSharing, setSubmittingSharing] = useState(false)
|
||||
const [autoRefresh, setAutoRefresh] = useState(loadAutoRefreshPreference)
|
||||
const loadMoreRef = useRef<HTMLDivElement | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (!autoRefresh) return
|
||||
const timer = window.setInterval(() => {
|
||||
void refreshAll()
|
||||
}, 5000)
|
||||
return () => window.clearInterval(timer)
|
||||
}, [autoRefresh])
|
||||
|
||||
function toggleAutoRefresh(enabled: boolean) {
|
||||
setAutoRefresh(enabled)
|
||||
localStorage.setItem(AUTO_REFRESH_STORAGE_KEY, enabled ? '1' : '0')
|
||||
}
|
||||
|
||||
const ordersQuery = useInfiniteQuery({
|
||||
queryKey: ['worker-hall-orders', keyword, categoryId],
|
||||
initialPageParam: 1,
|
||||
@@ -129,7 +114,6 @@ export default function WorkerHallPage() {
|
||||
queryKey: ['worker-hall-leaderboard'],
|
||||
queryFn: () => fetchWorkerHallLeaderboard(),
|
||||
enabled: leaderboardOpen,
|
||||
staleTime: 30_000,
|
||||
retry: false,
|
||||
})
|
||||
|
||||
@@ -299,10 +283,6 @@ export default function WorkerHallPage() {
|
||||
onClick={() => setLeaderboardOpen(true)}
|
||||
/>
|
||||
</Tooltip>
|
||||
<div className="worker-hall-mobile-autorefresh-switch">
|
||||
<span className="worker-hall-mobile-autorefresh-text">自动刷新</span>
|
||||
<Switch size="small" checked={autoRefresh} onChange={toggleAutoRefresh} />
|
||||
</div>
|
||||
<Button
|
||||
size="small"
|
||||
shape="circle"
|
||||
@@ -513,18 +493,6 @@ export default function WorkerHallPage() {
|
||||
<Typography.Title level={3}>抢单大厅</Typography.Title>
|
||||
<div className="worker-hall-page-actions">
|
||||
<div className="worker-hall-head-controls">
|
||||
<Tooltip
|
||||
title={
|
||||
autoRefresh
|
||||
? '已开启自动刷新,每 5 秒刷新一次'
|
||||
: '开启后每 5 秒自动刷新订单列表'
|
||||
}
|
||||
>
|
||||
<div className="worker-hall-autorefresh-box">
|
||||
<span className="worker-hall-autorefresh-label">自动刷新</span>
|
||||
<Switch size="small" checked={autoRefresh} onChange={toggleAutoRefresh} />
|
||||
</div>
|
||||
</Tooltip>
|
||||
<Button
|
||||
icon={<ReloadOutlined />}
|
||||
loading={
|
||||
@@ -884,12 +852,6 @@ function getDisplayOrderNo(order: Pick<WorkOrder, 'platformOrderId'> | null | un
|
||||
return String(order?.platformOrderId || '').trim() || '-'
|
||||
}
|
||||
|
||||
const AUTO_REFRESH_STORAGE_KEY = 'worker-hall-auto-refresh'
|
||||
|
||||
function loadAutoRefreshPreference(): boolean {
|
||||
return localStorage.getItem(AUTO_REFRESH_STORAGE_KEY) === '1'
|
||||
}
|
||||
|
||||
function formatMoney(value: number | undefined) {
|
||||
return `¥${((Number(value || 0) || 0) / 100).toFixed(2)}`
|
||||
}
|
||||
|
||||
@@ -42,22 +42,6 @@
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.worker-hall-autorefresh-box {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
background: #f1f5f9;
|
||||
padding: 4px 10px;
|
||||
border-radius: 6px;
|
||||
font-size: 12px;
|
||||
color: #475569;
|
||||
}
|
||||
|
||||
.worker-hall-autorefresh-label {
|
||||
font-size: 12px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.worker-hall-search-bar {
|
||||
grid-area: search;
|
||||
width: 100%;
|
||||
@@ -1717,23 +1701,6 @@ body {
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.worker-hall-mobile-autorefresh-switch {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
background: #ffffff;
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: 999px;
|
||||
padding: 4px 10px;
|
||||
font-size: 11px;
|
||||
color: #64748b;
|
||||
}
|
||||
|
||||
.worker-hall-mobile-autorefresh-text {
|
||||
font-size: 11px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* 分类横向滑动胶囊条 */
|
||||
.worker-hall-mobile-category-bar {
|
||||
display: flex;
|
||||
|
||||
Reference in New Issue
Block a user