完善接单平台通知配置

This commit is contained in:
yml2213
2026-08-17 13:54:01 +08:00
parent bca2e4a801
commit 5330b55b75
27 changed files with 1390 additions and 10 deletions
+255 -4
View File
@@ -1,5 +1,6 @@
import {
AuditOutlined,
BellOutlined,
BugOutlined,
DashboardOutlined,
FileSearchOutlined,
@@ -10,18 +11,36 @@ import {
SafetyCertificateOutlined,
SettingOutlined,
ShopOutlined,
SoundOutlined,
TeamOutlined,
TrophyOutlined,
UnorderedListOutlined,
UserOutlined,
} from '@ant-design/icons'
import { App, Button, Dropdown, Layout, Menu, Space, Typography } from 'antd'
import {
App,
Badge,
Button,
Dropdown,
Layout,
List,
Menu,
Popover,
Space,
Tooltip,
Typography,
} from 'antd'
import type { MenuProps } from 'antd'
import { useQuery } from '@tanstack/react-query'
import { useMemo, useState } from 'react'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { useEffect, useMemo, useRef, useState } from 'react'
import { Outlet, useLocation, useNavigate } from 'react-router'
import { fetchDevMockStatus, logoutAdmin } from '@/services/admin'
import {
fetchAdminNotifications,
fetchDevMockStatus,
logoutAdmin,
type AdminNotification,
} from '@/services/admin'
import {
clearAdminSession,
getAdminRole,
@@ -31,17 +50,25 @@ import {
import { formatAdminDateTime } from '@/utils/admin-time'
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()
const location = useLocation()
const { message } = App.useApp()
const queryClient = useQueryClient()
const [collapsed, setCollapsed] = useState(
() => window.localStorage.getItem(SIDEBAR_COLLAPSED_KEY) === '1',
)
const role = getAdminRole()
const username = getAdminUsername() || 'admin'
const expiresAt = getAdminTokenExpiresAt()
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'],
@@ -50,6 +77,43 @@ export default function AdminLayout() {
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 || []
const pendingNotificationCount = Number(notificationsQuery.data?.data.pendingCount || 0)
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'] = [
@@ -121,6 +185,64 @@ export default function AdminLayout() {
window.localStorage.setItem(SIDEBAR_COLLAPSED_KEY, next ? '1' : '0')
}
function toggleNotificationSound() {
const next = !soundEnabled
setSoundEnabled(next)
window.localStorage.setItem(NOTIFICATION_SOUND_KEY, next ? '1' : '0')
if (next) {
playNotificationSound('default')
message.success('通知声音已开启')
} else {
message.info('通知声音已关闭')
}
}
function openNotification(notification: AdminNotification) {
const actionPath = buildNotificationActionPath(notification)
if (actionPath) {
void navigate(actionPath)
}
}
const notificationContent = (
<div className="admin-notification-popover">
{notifications.length === 0 ? (
<Typography.Text type="secondary"></Typography.Text>
) : (
<List
size="small"
dataSource={notifications.slice(0, 8)}
renderItem={(notification) => (
<List.Item
className="admin-notification-item"
onClick={() => openNotification(notification)}
>
<div>
<Space size={6} wrap>
<Typography.Text strong>{notification.title}</Typography.Text>
{notification.priority === 'high' || notification.priority === 'urgent' ? (
<span className="admin-notification-priority"></span>
) : null}
{notification.reminderCount > 0 ? (
<Typography.Text type="secondary">
{notification.reminderCount}
</Typography.Text>
) : null}
</Space>
<Typography.Paragraph type="secondary" ellipsis={{ rows: 2 }}>
{notification.body}
</Typography.Paragraph>
<Typography.Text type="secondary" className="admin-notification-time">
{formatAdminDateTime(notification.updatedAt)}
</Typography.Text>
</div>
</List.Item>
)}
/>
)}
</div>
)
const selectedKey = resolveSelectedKey(location.pathname)
return (
@@ -182,6 +304,24 @@ export default function AdminLayout() {
<Layout className="admin-main-shell">
<Layout.Header className="admin-topbar">
<Space className="admin-user" size={12}>
<Tooltip title={soundEnabled ? '关闭通知声音' : '开启通知声音'}>
<Button
type="text"
aria-label={soundEnabled ? '关闭通知声音' : '开启通知声音'}
icon={<SoundOutlined className={soundEnabled ? '' : 'admin-sound-muted'} />}
onClick={toggleNotificationSound}
/>
</Tooltip>
<Popover
content={notificationContent}
title="待处理事项"
trigger="click"
placement="bottomRight"
>
<Badge count={pendingNotificationCount} size="small" overflowCount={99}>
<Button type="text" aria-label="待处理事项" icon={<BellOutlined />} />
</Badge>
</Popover>
<Dropdown
menu={{
items: [{ key: 'logout', label: '退出登录' }],
@@ -203,6 +343,99 @@ export default function AdminLayout() {
)
}
type NotificationAlertKind =
| 'withdraw'
| 'recharge'
| 'acceptance'
| 'material'
| '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()
const oscillator = audio.createOscillator()
const gain = audio.createGain()
oscillator.type = 'sine'
const notes: Record<NotificationAlertKind, number[]> = {
withdraw: [740, 988],
recharge: [587, 740],
acceptance: [660, 784],
material: [523, 659],
reminder: [880, 1047, 1319],
default: [880],
}
const duration = 0.12
const sequence = notes[kind]
sequence.forEach((frequency, index) => {
oscillator.frequency.setValueAtTime(frequency, audio.currentTime + index * duration)
})
gain.gain.setValueAtTime(0.08, audio.currentTime)
gain.gain.exponentialRampToValueAtTime(0.001, audio.currentTime + sequence.length * duration)
oscillator.connect(gain)
gain.connect(audio.destination)
oscillator.start()
oscillator.stop(audio.currentTime + sequence.length * duration)
oscillator.addEventListener('ended', () => void audio.close())
} catch {
// 部分浏览器禁止音频或不支持 Web Audio,不影响待办轮询。
}
}
function resolveSelectedKey(pathname: string) {
if (pathname.startsWith('/admin/orders')) return '/admin/orders'
if (pathname.startsWith('/admin/tasks')) return '/admin/tasks'
@@ -212,6 +445,24 @@ function resolveSelectedKey(pathname: string) {
return pathname
}
function buildNotificationActionPath(notification: AdminNotification) {
if (!notification.entityId) {
return notification.actionPath
}
const [pathname, query = ''] = notification.actionPath.split('?')
const searchParams = new URLSearchParams(query)
if (notification.entityType === 'work_order') {
searchParams.set('tab', 'orders')
searchParams.set('workOrderId', String(notification.entityId))
} else if (notification.entityType === 'worker_finance_request') {
searchParams.set('tab', 'finance')
searchParams.set('financeRequestId', String(notification.entityId))
} else {
return notification.actionPath
}
return `${pathname}?${searchParams.toString()}`
}
function roleLabel(role: string) {
if (role === 'admin') return '管理员'
if (role === 'operator') return '普通运营'