Merge branch 'dev_1115_huya'

This commit is contained in:
2026-11-17 14:46:43 +08:00
35 changed files with 6580 additions and 380 deletions
@@ -0,0 +1,837 @@
import { ArrowRightOutlined, CopyOutlined, ReloadOutlined } from '@ant-design/icons'
import {
App,
Button,
Card,
Checkbox,
Col,
Collapse,
Descriptions,
Drawer,
Empty,
Input,
Pagination,
Row,
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 { describeSemiAutoTraceAction } from '@/utils/semi-auto-trace-action'
import { useIsMobile } from '@/utils/use-is-mobile'
const { Text } = Typography
/** 非状态类事件:名称直接写清楚「谁做了什么」。 */
const EVENT_TITLES: Record<string, string> = {
task_created: '创建履约任务',
customer_link_opened: '客户打开授权页',
customer_profile_saved: '客户提交游戏角色',
login_started: '客户开始登录',
task_claimed: '客服领取任务',
customer_reauth_requested: '客服重新发起授权',
browser_session_opened: '客服生成浏览器登录票据',
credential_session_restored: '使用已保存 CK 恢复登录',
credential_invalidated: '平台 CK 已失效',
task_completed: '客服完成履约',
task_cancelled: '任务已取消',
}
/** 状态变更事件:按「变更后的状态」命名,读起来就是一句操作结果。 */
const LOGIN_EVENT_TITLES: Record<string, string> = {
waiting_code: '等待客户输入验证码',
qr_pending: '生成登录二维码',
scanned: '客户已扫码,等待确认',
authenticated: '客户完成平台登录',
failed: '平台登录失败',
expired: '登录二维码已过期',
}
const BINDING_EVENT_TITLES: Record<string, string> = {
not_started: '绑定状态重置',
qr_pending: '生成绑定二维码',
scanned: '客户已扫码绑定',
role_ready: '平台识别到游戏角色',
confirmed: '客户确认绑定角色',
failed: '角色绑定失败',
expired: '绑定二维码已过期',
}
const CHANNEL_LABELS: Record<string, string> = {
customer_api: '客户接口',
admin_api: '运营接口',
huya_wup: '虎牙 WUP',
huya_http: '虎牙 HTTP',
external_connector: '外部 Connector',
}
const CHANNEL_COLORS: Record<string, string> = {
customer_api: 'blue',
admin_api: 'cyan',
huya_wup: 'purple',
huya_http: 'geekblue',
external_connector: 'gold',
}
const CHANNEL_OPTIONS = Object.keys(CHANNEL_LABELS).map((value) => ({
value,
label: CHANNEL_LABELS[value],
}))
const ACTOR_LABELS: Record<string, string> = {
system: '系统',
customer: '客户',
admin: '客服',
connector: '平台连接器',
}
const ACTOR_COLORS: Record<string, string> = {
system: 'default',
customer: 'blue',
admin: 'cyan',
connector: 'purple',
}
const ACTOR_OPTIONS = Object.keys(ACTOR_LABELS).map((value) => ({
value,
label: ACTOR_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: '已取消',
}
/** antd 6 的 Timeline 预设色会被主题色覆盖,这里用固定色值保证语义色稳定。 */
const TIMELINE_COLORS = {
gray: '#8c8c8c',
green: '#52c41a',
blue: '#1677ff',
gold: '#faad14',
cyan: '#13c2c2',
red: '#ff4d4f',
}
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 [eventActor, setEventActor] = useState('')
const [onlyError, setOnlyError] = useState(false)
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')
setEventActor('')
setOnlyError(false)
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 visibleEvents = events.filter((event) => {
if (eventActor && event.actorType !== eventActor) return false
if (onlyError && !eventIsFailure(event)) return false
return true
})
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: 280,
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 ? (
<Card size="small">
<Descriptions
size="small"
column={isMobile ? 1 : 3}
items={[
{
key: 'login',
label: '登录状态',
children: (
<Tag color={loginTagColor(history.task.loginStatus)}>
{LOGIN_STATUS_LABELS[history.task.loginStatus] || history.task.loginStatus}
</Tag>
),
},
{
key: 'binding',
label: '绑定状态',
children: (
<Tag color={bindingTagColor(history.task.bindingStatus)}>
{history.task.platform === 'weibo'
? '登录即授权'
: BINDING_STATUS_LABELS[history.task.bindingStatus] ||
history.task.bindingStatus}
</Tag>
),
},
{
key: 'execution',
label: '执行状态',
children: (
<Tag color={executionTagColor(history.task.executionStatus)}>
{EXECUTION_STATUS_LABELS[history.task.executionStatus] ||
history.task.executionStatus}
</Tag>
),
},
{
key: 'createdAt',
label: '创建时间',
children: formatAdminDateTime(history.task.createdAt),
},
{
key: 'completedAt',
label: '完成时间',
children: history.task.completedAt
? formatAdminDateTime(history.task.completedAt)
: '—',
},
{
key: 'eventTotal',
label: '事件数量',
children: `${history.eventTotal} 条`,
},
]}
/>
</Card>
) : null}
<Space wrap>
<Select
allowClear
placeholder="全部来源"
value={eventActor || undefined}
onChange={(value) => setEventActor(value || '')}
options={ACTOR_OPTIONS}
style={{ width: 140 }}
/>
<Checkbox checked={onlyError} onChange={(event) => setOnlyError(event.target.checked)}>
只看异常
</Checkbox>
<Text type="secondary">
共 {events.length} 个节点,当前显示 {visibleEvents.length} 个
</Text>
{history && history.eventTotal > events.length ? (
<Text type="secondary">
(仅展示最近 {events.length} 条,共 {history.eventTotal} 条)
</Text>
) : null}
</Space>
{historyQuery.isLoading ? (
<Text type="secondary">加载中...</Text>
) : visibleEvents.length === 0 ? (
<Empty
description={
events.length > 0 ? '当前筛选条件下没有节点' : '暂无状态流转记录(客户还未开始操作)'
}
/>
) : (
<Timeline
mode={isMobile ? undefined : 'left'}
items={visibleEvents.map((event) => ({
key: String(event.id),
color: eventDotColor(event),
label: isMobile ? undefined : (
<Text type="secondary" style={{ fontSize: 12 }}>
{formatAdminDateTime(event.createdAt)}
</Text>
),
children: <EventItem event={event} preStyle={preStyle} showTime={isMobile} />,
}))}
/>
)}
</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%' : 1000}
title={
<Space direction="vertical" size={0}>
<Text strong>履约历史</Text>
<Text type="secondary" style={{ fontSize: 12 }}>
{history?.task?.orderNo || '—'}
</Text>
</Space>
}
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,
showTime,
}: {
event: SemiAutoTaskHistoryEvent
preStyle: CSSProperties
showTime: boolean
}) {
const detail = event.detail || {}
const transitions = [
{
key: 'login',
label: '登录',
map: LOGIN_STATUS_LABELS,
from: event.fromLoginStatus,
to: event.toLoginStatus,
},
{
key: 'binding',
label: '绑定',
map: BINDING_STATUS_LABELS,
from: event.fromBindingStatus,
to: event.toBindingStatus,
},
{
key: 'execution',
label: '执行',
map: EXECUTION_STATUS_LABELS,
from: event.fromExecutionStatus,
to: event.toExecutionStatus,
},
].filter((item) => item.from !== item.to && Boolean(item.from || item.to))
const summary = resolveEventSummary(event)
const detailKeys = Object.keys(detail)
return (
<Space direction="vertical" size={4} style={{ width: '100%' }}>
<Space size={6} wrap align="center">
<Text strong>{resolveEventTitle(event)}</Text>
<Tag color={ACTOR_COLORS[event.actorType] || 'default'}>
{ACTOR_LABELS[event.actorType] || event.actorType}
</Tag>
{eventIsFailure(event) ? <Tag color="red">异常</Tag> : null}
</Space>
{showTime ? (
<Text type="secondary" style={{ fontSize: 12 }}>
{formatAdminDateTime(event.createdAt)}
</Text>
) : null}
{transitions.map((item) => (
<Space key={item.key} size={4} wrap>
<Text type="secondary" style={{ fontSize: 12, minWidth: 28 }}>
{item.label}
</Text>
<Tag bordered={false}>{statusLabel(item.map, item.from)}</Tag>
<ArrowRightOutlined style={{ fontSize: 10 }} />
<Tag bordered={false} color={transitionColor(item.key, item.to)}>
{statusLabel(item.map, item.to)}
</Tag>
</Space>
))}
{summary ? <Text style={{ fontSize: 13 }}>{summary}</Text> : null}
{detailKeys.length > 0 ? (
<Collapse
ghost
size="small"
items={[
{
key: 'detail',
label: (
<Text type="secondary" style={{ fontSize: 12 }}>
查看原始详情
</Text>
),
children: <pre style={preStyle}>{JSON.stringify(detail, null, 2)}</pre>,
},
]}
/>
) : null}
</Space>
)
}
function TraceLabel({ item }: { item: SemiAutoTraceItem }) {
const actionLabel = describeSemiAutoTraceAction({
channel: item.channel,
action: item.action,
})
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 color={CHANNEL_COLORS[item.channel] || 'default'}>
{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>
{actionLabel ? <Text strong>{actionLabel}</Text> : null}
<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
}) {
const actionLabel = describeSemiAutoTraceAction({
channel: item.channel,
action: item.action,
})
return (
<Space direction="vertical" size={10} style={{ width: '100%' }}>
<Row gutter={[12, 12]}>
<Col xs={24} lg={12}>
<Space direction="vertical" size={10} style={{ width: '100%' }}>
<PayloadBlock title="请求参数" value={item.requestSummary} preStyle={preStyle} />
<PayloadBlock title="请求原文" value={item.requestBody} preStyle={preStyle} />
</Space>
</Col>
<Col xs={24} lg={12}>
<Space direction="vertical" size={10} style={{ width: '100%' }}>
<PayloadBlock title="响应结果" value={item.responseSummary} preStyle={preStyle} />
<PayloadBlock title="响应原文" value={item.responseBody} preStyle={preStyle} />
</Space>
</Col>
</Row>
<Space size={6} wrap>
<Button
size="small"
icon={<CopyOutlined />}
onClick={() =>
onCopy(
[
`动作:${actionLabel ? `${actionLabel} · ` : ''}${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 resolveEventTitle(event: SemiAutoTaskHistoryEvent) {
if (event.eventType === 'login_status_changed') {
return LOGIN_EVENT_TITLES[event.toLoginStatus || ''] || '登录状态变更'
}
if (event.eventType === 'binding_status_changed') {
if (
event.detail?.rebindUnchanged === true ||
String(event.detail?.rebindConfirmState || '') === 'rejected'
) {
return '换绑被平台拒绝'
}
return BINDING_EVENT_TITLES[event.toBindingStatus || ''] || '绑定状态变更'
}
return EVENT_TITLES[event.eventType] || event.eventType
}
function resolveEventSummary(event: SemiAutoTaskHistoryEvent) {
const detail = event.detail || {}
const text = (value: unknown) => String(value ?? '').trim()
if (event.eventType === 'customer_profile_saved') {
return [
text(detail.roleName) ? `角色:${text(detail.roleName)}` : '',
text(detail.roleId) ? `编号:${text(detail.roleId)}` : '',
text(detail.serverZone) ? `区服:${text(detail.serverZone)}` : '',
]
.filter(Boolean)
.join(' · ')
}
if (event.eventType === 'binding_status_changed') {
const parts: string[] = []
if (text(detail.gameRole)) {
parts.push(
`绑定角色:${text(detail.gameRole)}${
text(detail.gameRoleId) ? `(${text(detail.gameRoleId)})` : ''
}`,
)
}
if (detail.rebindUnchanged === true) parts.push('平台仍返回原绑定角色')
const message = text(detail.message) || text(detail.rebindConfirmMessage)
if (message) parts.push(message)
return parts.join(' · ')
}
if (event.eventType === 'login_status_changed') {
const method = text(detail.method)
const methodLabel = method === 'sms' ? '短信验证码' : method === 'qr' ? '扫码' : ''
return [methodLabel ? `登录方式:${methodLabel}` : '', text(detail.message)]
.filter(Boolean)
.join(' · ')
}
if (event.eventType === 'task_completed') {
return [
text(detail.note),
text(detail.externalOrderNo) ? `外部单号:${text(detail.externalOrderNo)}` : '',
]
.filter(Boolean)
.join(' · ')
}
return text(detail.message) || text(detail.reason) || text(detail.note)
}
function eventIsFailure(event: SemiAutoTaskHistoryEvent) {
if (event.eventType === 'task_cancelled') return false
if (/fail|invalid|error/i.test(event.eventType)) return true
if (event.toLoginStatus === 'failed' || event.toLoginStatus === 'expired') return true
if (event.toBindingStatus === 'failed' || event.toBindingStatus === 'expired') return true
if (
event.detail?.rebindUnchanged === true ||
String(event.detail?.rebindConfirmState || '') === 'rejected'
) {
return true
}
return false
}
function eventDotColor(event: SemiAutoTaskHistoryEvent) {
if (eventIsFailure(event)) return TIMELINE_COLORS.red
switch (event.eventType) {
case 'task_created':
return TIMELINE_COLORS.gray
case 'customer_link_opened':
case 'customer_profile_saved':
return TIMELINE_COLORS.green
case 'login_started':
case 'login_status_changed':
return TIMELINE_COLORS.blue
case 'binding_status_changed':
return TIMELINE_COLORS.gold
case 'task_claimed':
case 'customer_reauth_requested':
case 'browser_session_opened':
return TIMELINE_COLORS.cyan
case 'task_completed':
return TIMELINE_COLORS.green
case 'task_cancelled':
return TIMELINE_COLORS.gray
default:
return TIMELINE_COLORS.blue
}
}
function loginTagColor(status: string) {
if (status === 'authenticated') return 'green'
if (status === 'failed' || status === 'expired') return 'red'
return 'blue'
}
function bindingTagColor(status: string) {
if (status === 'confirmed') return 'green'
if (status === 'role_ready') return 'gold'
if (status === 'failed' || status === 'expired') return 'red'
return 'blue'
}
function executionTagColor(status: string) {
if (status === 'completed') return 'green'
if (status === 'failed') return 'red'
if (status === 'cancelled') return 'default'
if (status === 'waiting_operator') return 'orange'
if (status === 'processing') return 'blue'
return 'blue'
}
function transitionColor(kind: string, value: string | null) {
if (kind === 'login') return loginTagColor(String(value || ''))
if (kind === 'binding') return bindingTagColor(String(value || ''))
return executionTagColor(String(value || ''))
}
function statusLabel(map: Record<string, string>, value: string | null) {
if (!value) return '初始'
return map[value] || value
}