feat(semi-auto): 新增履约历史与全链路报文留痕

运营端历史抽屉展示状态流转与全链路报文:客户/运营接口入站 + 虎牙 WUP/livelink、外部 Connector 出站;轮询按状态变化采样,Cookie/Token/短信验证码不落库,报文保留 180 天。同步收敛登录/绑定事件,避免轮询重复写时间线。
This commit is contained in:
2026-11-16 17:26:35 +08:00
parent f371cc2c8d
commit 08e753ec94
13 changed files with 1648 additions and 101 deletions
@@ -0,0 +1,501 @@
import { CopyOutlined, ReloadOutlined } from '@ant-design/icons'
import {
App,
Button,
Collapse,
Drawer,
Empty,
Input,
Pagination,
Select,
Space,
Tabs,
Tag,
theme,
Timeline,
Typography,
} from 'antd'
import { useQuery } from '@tanstack/react-query'
import { useEffect, useMemo, useState } from 'react'
import type { CSSProperties } from 'react'
import { fetchAdminSemiAutoTaskHistory } from '@/services/admin/semi-auto'
import type { SemiAutoTaskHistoryEvent, SemiAutoTraceItem } from '@/types/admin/semi-auto'
import { formatAdminDateTime } from '@/utils/admin-time'
import { useIsMobile } from '@/utils/use-is-mobile'
const { Text } = Typography
const EVENT_LABELS: Record<string, string> = {
task_created: '任务创建',
customer_link_opened: '客户打开链接',
customer_profile_saved: '客户保存角色资料',
login_started: '开始平台登录',
login_status_changed: '登录状态变更',
binding_status_changed: '绑定状态变更',
task_claimed: '客服领取',
customer_reauth_requested: '重新发起客户授权',
browser_session_opened: '生成浏览器注入票据',
credential_session_restored: '凭证恢复登录',
credential_invalidated: '凭证失效',
task_completed: '订单完成',
task_cancelled: '订单取消',
}
const CHANNEL_LABELS: Record<string, string> = {
customer_api: '客户接口',
admin_api: '运营接口',
huya_wup: '虎牙 WUP',
huya_http: '虎牙 HTTP',
external_connector: '外部 Connector',
}
const CHANNEL_OPTIONS = Object.keys(CHANNEL_LABELS).map((value) => ({
value,
label: CHANNEL_LABELS[value],
}))
const LOGIN_STATUS_LABELS: Record<string, string> = {
waiting_login: '等待登录',
qr_pending: '待扫码',
scanned: '已扫码',
authenticated: '已登录',
failed: '登录失败',
expired: '登录过期',
}
const BINDING_STATUS_LABELS: Record<string, string> = {
not_started: '未开始',
qr_pending: '待扫码',
scanned: '已扫码',
role_ready: '待确认角色',
confirmed: '已确认',
failed: '绑定失败',
expired: '已过期',
}
const EXECUTION_STATUS_LABELS: Record<string, string> = {
waiting_customer: '等待客户',
waiting_operator: '等待客服',
processing: '处理中',
completed: '已完成',
failed: '失败',
cancelled: '已取消',
}
type SemiAutoTaskHistoryDrawerProps = {
open: boolean
taskId: number | null
onClose: () => void
}
export default function SemiAutoTaskHistoryDrawer({
open,
taskId,
onClose,
}: SemiAutoTaskHistoryDrawerProps) {
const { message } = App.useApp()
const isMobile = useIsMobile()
const { token } = theme.useToken()
const [tab, setTab] = useState('events')
const [channel, setChannel] = useState('')
const [status, setStatus] = useState('')
const [keywordDraft, setKeywordDraft] = useState('')
const [keyword, setKeyword] = useState('')
const [requestId, setRequestId] = useState('')
const [page, setPage] = useState(1)
const [pageSize, setPageSize] = useState(50)
useEffect(() => {
if (!open) return
setTab('events')
setChannel('')
setStatus('')
setKeywordDraft('')
setKeyword('')
setRequestId('')
setPage(1)
setPageSize(50)
}, [open, taskId])
const params = useMemo(
() => ({
page,
pageSize,
channel: channel || undefined,
status: status || undefined,
keyword: keyword.trim() || undefined,
requestId: requestId || undefined,
}),
[channel, keyword, page, pageSize, requestId, status],
)
const historyQuery = useQuery({
queryKey: ['admin-semi-auto-task-history', taskId, params],
queryFn: () => fetchAdminSemiAutoTaskHistory(Number(taskId), params),
enabled: open && Boolean(taskId),
refetchInterval: open && Boolean(taskId) ? 8000 : false,
})
const history = historyQuery.data?.data
const events = history?.events || []
const traces = history?.traces
const traceItems = traces?.items || []
const preStyle: CSSProperties = {
margin: '6px 0 0',
padding: 10,
background: token.colorFillQuaternary,
border: `1px solid ${token.colorBorderSecondary}`,
borderRadius: token.borderRadius,
color: token.colorText,
fontSize: 12,
lineHeight: 1.55,
maxHeight: 320,
overflow: 'auto',
whiteSpace: 'pre-wrap',
wordBreak: 'break-all',
}
const copyText = (text: string, label: string) => {
if (!text) {
message.warning(`${label}为空`)
return
}
void navigator.clipboard
.writeText(text)
.then(() => message.success(`${label}已复制`))
.catch(() => message.error('复制失败,请手动选择文本复制'))
}
const eventsPanel = (
<Space direction="vertical" size={12} style={{ width: '100%' }}>
{history?.task ? (
<Space size={6} wrap>
<Tag color="blue">
登录:{LOGIN_STATUS_LABELS[history.task.loginStatus] || history.task.loginStatus}
</Tag>
<Tag color="gold">
绑定:
{history.task.platform === 'weibo'
? '登录即授权'
: BINDING_STATUS_LABELS[history.task.bindingStatus] || history.task.bindingStatus}
</Tag>
<Tag color="purple">
执行:
{EXECUTION_STATUS_LABELS[history.task.executionStatus] || history.task.executionStatus}
</Tag>
<Text type="secondary">创建 {formatAdminDateTime(history.task.createdAt)}</Text>
{history.task.completedAt ? (
<Text type="secondary">完成 {formatAdminDateTime(history.task.completedAt)}</Text>
) : null}
</Space>
) : null}
{history && history.eventTotal > events.length ? (
<Text type="secondary">
仅展示最近 {events.length} 条状态事件,共 {history.eventTotal} 条。
</Text>
) : null}
{historyQuery.isLoading ? (
<Text type="secondary">加载中...</Text>
) : events.length === 0 ? (
<Empty description="暂无状态流转记录" />
) : (
<Timeline
items={events.map((event) => ({
color: /fail|invalid|error|cancel/i.test(event.eventType) ? 'red' : 'blue',
children: <EventItem event={event} preStyle={preStyle} />,
}))}
/>
)}
</Space>
)
const tracesPanel = (
<Space direction="vertical" size={12} style={{ width: '100%' }}>
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, alignItems: 'center' }}>
<Select
allowClear
placeholder="全部渠道"
value={channel || undefined}
onChange={(value) => {
setChannel(value || '')
setPage(1)
}}
options={CHANNEL_OPTIONS}
style={isMobile ? { flex: '1 1 150px', minWidth: 120 } : { width: 160 }}
/>
<Select
allowClear
placeholder="全部结果"
value={status || undefined}
onChange={(value) => {
setStatus(value || '')
setPage(1)
}}
options={[
{ value: 'ok', label: '成功' },
{ value: 'error', label: '失败' },
]}
style={isMobile ? { flex: '1 1 110px', minWidth: 96 } : { width: 120 }}
/>
<Input.Search
allowClear
placeholder="动作 / 报文内容关键字"
value={keywordDraft}
onChange={(event) => setKeywordDraft(event.target.value)}
onSearch={(value) => {
setKeyword(value)
setPage(1)
}}
style={isMobile ? { flex: '1 1 220px' } : { width: 240 }}
/>
<Button icon={<ReloadOutlined />} onClick={() => void historyQuery.refetch()}>
刷新
</Button>
{requestId ? (
<Tag
closable
color="blue"
onClose={() => {
setRequestId('')
setPage(1)
}}
>
同一请求:{requestId}
</Tag>
) : null}
</div>
{traces?.summary?.length ? (
<Space size={4} wrap>
{traces.summary.map((item) => (
<Tag
key={`${item.channel}-${item.status}`}
color={item.status === 'error' ? 'red' : 'default'}
>
{CHANNEL_LABELS[item.channel] || item.channel} ·{' '}
{item.status === 'error' ? '失败' : '成功'} {item.total}
</Tag>
))}
</Space>
) : null}
<Text type="secondary">报文保留 180 天;Cookie、Token、短信验证码和二维码内容不落库。</Text>
{historyQuery.isLoading ? (
<Text type="secondary">加载中...</Text>
) : traceItems.length === 0 ? (
<Empty description="暂无报文记录(当前只记录状态变化与失败,未变化的轮询不落库)" />
) : (
<Collapse
size="small"
items={traceItems.map((item) => ({
key: String(item.id),
label: <TraceLabel item={item} />,
children: (
<TracePayload
item={item}
preStyle={preStyle}
onCopy={copyText}
onFilterRequest={(value) => {
setRequestId(value)
setPage(1)
}}
/>
),
}))}
/>
)}
<Pagination
size={isMobile ? 'small' : undefined}
current={traces?.pagination.page || page}
pageSize={traces?.pagination.pageSize || pageSize}
total={traces?.pagination.total || 0}
showSizeChanger={!isMobile}
showTotal={(total) => `共 ${total} 条`}
onChange={(nextPage, nextPageSize) => {
setPage(nextPage)
setPageSize(nextPageSize)
}}
/>
</Space>
)
return (
<Drawer
open={open}
width={isMobile ? '100%' : 960}
title={history?.task ? `履约历史 · ${history.task.orderNo}` : '履约历史'}
onClose={onClose}
extra={
<Button size="small" icon={<ReloadOutlined />} onClick={() => void historyQuery.refetch()}>
刷新
</Button>
}
>
<Tabs
activeKey={tab}
onChange={setTab}
items={[
{
key: 'events',
label: `状态流转(${history?.eventTotal ?? 0})`,
children: eventsPanel,
},
{
key: 'traces',
label: `全链路报文(${traces?.pagination.total ?? 0})`,
children: tracesPanel,
},
]}
/>
</Drawer>
)
}
function EventItem({
event,
preStyle,
}: {
event: SemiAutoTaskHistoryEvent
preStyle: CSSProperties
}) {
const detail = event.detail || {}
const detailKeys = Object.keys(detail)
const transitions = [
{
label: '登录',
map: LOGIN_STATUS_LABELS,
from: event.fromLoginStatus,
to: event.toLoginStatus,
},
{
label: '绑定',
map: BINDING_STATUS_LABELS,
from: event.fromBindingStatus,
to: event.toBindingStatus,
},
{
label: '执行',
map: EXECUTION_STATUS_LABELS,
from: event.fromExecutionStatus,
to: event.toExecutionStatus,
},
].filter((item) => item.from !== item.to && Boolean(item.from || item.to))
return (
<Space direction="vertical" size={2} style={{ width: '100%' }}>
<Text strong>{EVENT_LABELS[event.eventType] || event.eventType}</Text>
<Text type="secondary">
{formatAdminDateTime(event.createdAt)} · {event.actorType}
{event.actorId ? ` ${event.actorId}` : ''}
</Text>
{transitions.map((item) => (
<Text key={item.label} type="secondary">
{item.label}:{statusLabel(item.map, item.from)} → {statusLabel(item.map, item.to)}
</Text>
))}
{detailKeys.length > 0 ? <pre style={preStyle}>{JSON.stringify(detail, null, 2)}</pre> : null}
</Space>
)
}
function TraceLabel({ item }: { item: SemiAutoTraceItem }) {
return (
<Space direction="vertical" size={2} style={{ width: '100%' }}>
<Space size={6} wrap>
<Tag color={item.direction === 'inbound' ? 'blue' : 'purple'}>
{item.direction === 'inbound' ? '入站' : '出站'}
</Tag>
<Tag>{CHANNEL_LABELS[item.channel] || item.channel}</Tag>
<Tag color={item.status === 'ok' ? 'green' : 'red'}>
{item.status === 'ok' ? '成功' : '失败'}
</Tag>
{item.httpStatus ? <Text type="secondary">HTTP {item.httpStatus}</Text> : null}
{item.durationMs !== null && item.durationMs !== undefined ? (
<Text type="secondary">{item.durationMs}ms</Text>
) : null}
<Text type="secondary">{formatAdminDateTime(item.createdAt)}</Text>
</Space>
<Text code style={{ whiteSpace: 'break-all' }}>
{item.action}
</Text>
{item.errorMessage ? <Text type="danger">{item.errorMessage}</Text> : null}
</Space>
)
}
function TracePayload({
item,
preStyle,
onCopy,
onFilterRequest,
}: {
item: SemiAutoTraceItem
preStyle: CSSProperties
onCopy: (text: string, label: string) => void
onFilterRequest: (requestId: string) => void
}) {
return (
<Space direction="vertical" size={10} style={{ width: '100%' }}>
<PayloadBlock title="请求概要" value={item.requestSummary} preStyle={preStyle} />
<PayloadBlock title="请求报文" value={item.requestBody} preStyle={preStyle} />
<PayloadBlock title="响应概要" value={item.responseSummary} preStyle={preStyle} />
<PayloadBlock title="响应报文" value={item.responseBody} preStyle={preStyle} />
<Space size={6} wrap>
<Button
size="small"
icon={<CopyOutlined />}
onClick={() =>
onCopy(
[
`动作:${item.action}`,
`requestId:${item.requestId}`,
'',
'# 请求',
item.requestBody,
'',
'# 响应',
item.responseBody,
].join('\n'),
'完整报文',
)
}
>
复制完整报文
</Button>
{item.requestId ? (
<Button size="small" onClick={() => onFilterRequest(item.requestId)}>
只看同一请求
</Button>
) : null}
<Text type="secondary">requestId:{item.requestId || '-'}</Text>
</Space>
</Space>
)
}
function PayloadBlock({
title,
value,
preStyle,
}: {
title: string
value: unknown
preStyle: CSSProperties
}) {
const text =
value && typeof value === 'object'
? Object.keys(value as Record<string, unknown>).length > 0
? JSON.stringify(value, null, 2)
: ''
: String(value || '').trim()
return (
<div>
<Text strong>{title}</Text>
{text ? <pre style={preStyle}>{text}</pre> : <Text type="secondary">(空)</Text>}
</div>
)
}
function statusLabel(map: Record<string, string>, value: string | null) {
if (!value) return '—'
return map[value] || value
}
@@ -2,6 +2,7 @@ import {
CheckCircleOutlined,
ChromeOutlined,
CopyOutlined,
HistoryOutlined,
KeyOutlined,
ReloadOutlined,
SendOutlined,
@@ -30,6 +31,7 @@ import { useEffect, useMemo, useState } from 'react'
import ImageUpload from '@/components/files/ImageUpload'
import PageHeader from '@/components/admin/PageHeader'
import SemiAutoTaskHistoryDrawer from '@/components/admin/SemiAutoTaskHistoryDrawer'
import PercentTable from '@/components/common/PercentTable'
import {
cancelAdminSemiAutoTask,
@@ -94,6 +96,7 @@ export default function AdminSemiAutoTasksPage() {
const [page, setPage] = useState(1)
const [pageSize, setPageSize] = useState(20)
const [detailTaskId, setDetailTaskId] = useState<number | null>(null)
const [historyTaskId, setHistoryTaskId] = useState<number | null>(null)
const [completeTask, setCompleteTask] = useState<SemiAutoTask | null>(null)
const [completeFiles, setCompleteFiles] = useState<UploadedFile[]>([])
const [completeForm] = Form.useForm<CompleteFormValues>()
@@ -416,6 +419,13 @@ export default function AdminSemiAutoTasksPage() {
<Button size="small" onClick={() => setDetailTaskId(task.id)}>
详情
</Button>
<Button
size="small"
icon={<HistoryOutlined />}
onClick={() => setHistoryTaskId(task.id)}
>
历史
</Button>
{taskNeedsCustomerReauth(task) ? (
<Button
size="small"
@@ -762,6 +772,12 @@ export default function AdminSemiAutoTasksPage() {
)}
</Drawer>
<SemiAutoTaskHistoryDrawer
open={Boolean(historyTaskId)}
taskId={historyTaskId}
onClose={() => setHistoryTaskId(null)}
/>
<Modal
open={Boolean(completeTask)}
title="确认完成半自动履约"
@@ -2,6 +2,7 @@ import { apiGet, apiPost } from '@/lib/http'
import type {
SemiAutoCredentialExport,
SemiAutoTaskDetail,
SemiAutoTaskHistory,
SemiAutoTaskListResult,
} from '@/types/admin/semi-auto'
@@ -13,6 +14,13 @@ export function fetchAdminSemiAutoTask(taskId: number) {
return apiGet<SemiAutoTaskDetail>(`/api/v1/admin/semi-auto/tasks/${taskId}`)
}
export function fetchAdminSemiAutoTaskHistory(
taskId: number,
params: Record<string, unknown> = {},
) {
return apiGet<SemiAutoTaskHistory>(`/api/v1/admin/semi-auto/tasks/${taskId}/history`, params)
}
export function exportAdminSemiAutoCredential(taskId: number) {
return apiPost<SemiAutoCredentialExport>(
`/api/v1/admin/semi-auto/tasks/${taskId}/credential/export`,
@@ -81,6 +81,65 @@ export type SemiAutoTaskDetail = {
events: SemiAutoTaskEvent[]
}
export type SemiAutoTaskHistoryEvent = {
id: number
eventType: string
actorType: string
actorId: string
fromLoginStatus: string | null
toLoginStatus: string | null
fromBindingStatus: string | null
toBindingStatus: string | null
fromExecutionStatus: string | null
toExecutionStatus: string | null
detail: Record<string, unknown>
createdAt: string
}
export type SemiAutoTraceItem = {
id: number
orderNo: string
requestId: string
direction: 'inbound' | 'outbound' | string
channel: string
action: string
status: 'ok' | 'error' | string
httpStatus: number | null
durationMs: number | null
requestSummary: Record<string, unknown>
requestBody: string
responseSummary: Record<string, unknown>
responseBody: string
errorMessage: string
createdAt: string
}
export type SemiAutoTraceSummaryItem = {
channel: string
status: string
total: number
}
export type SemiAutoTraceQueryParams = {
page?: number
pageSize?: number
channel?: string
status?: string
requestId?: string
keyword?: string
}
export type SemiAutoTaskHistory = {
task: SemiAutoTask
events: SemiAutoTaskHistoryEvent[]
eventTotal: number
traces: {
pagination: { page: number; pageSize: number; total: number }
summary: SemiAutoTraceSummaryItem[]
items: SemiAutoTraceItem[]
}
}
export type SemiAutoCredentialExport = {
credentialId: number
platform: SemiAutoPlatform