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
Binary file not shown.

After

Width:  |  Height:  |  Size: 115 KiB

@@ -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
}
+22
View File
@@ -138,6 +138,21 @@ function applySessionExpiryHeaders(
}
}
/** HTTP 状态码兜底文案:避免把英文 statusText(如 Not Found)原样抛给用户 */
const HTTP_STATUS_MESSAGES: Record<number, string> = {
400: '请求参数有误',
401: '登录状态已失效,请重新登录',
403: '没有操作权限',
404: '接口不存在,请刷新页面后重试',
409: '数据已更新,请刷新后重试',
422: '提交的数据不合法',
429: '操作过于频繁,请稍后再试',
500: '服务器开小差了,请稍后重试',
502: '服务暂时不可用,请稍后重试',
503: '服务维护中,请稍后重试',
504: '请求超时,请稍后重试',
}
function resolveFallbackHttpMessage(error: unknown) {
const message = String((error as { message?: string })?.message ?? '')
@@ -149,6 +164,13 @@ function resolveFallbackHttpMessage(error: unknown) {
return '网络连接错误'
}
const status = Number((error as { response?: { status?: number } })?.response?.status || 0)
const statusMessage = status > 0 ? HTTP_STATUS_MESSAGES[status] : ''
if (statusMessage) {
return statusMessage
}
if (typeof (error as { response?: { statusText?: string } })?.response?.statusText === 'string') {
return String((error as { response: { statusText: string } }).response.statusText).trim()
}
@@ -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,
@@ -54,6 +56,8 @@ const STATUS_COLORS: Record<string, string> = {
login_scanned: 'cyan',
waiting_binding: 'gold',
binding_confirm: 'orange',
binding_expired: 'red',
binding_failed: 'red',
waiting_operator: 'volcano',
credential_expired: 'red',
processing: 'processing',
@@ -67,6 +71,16 @@ const PLATFORM_LABELS: Record<string, string> = {
weibo: '微博',
}
const BINDING_STATUS_LABELS: Record<string, string> = {
not_started: '未开始',
qr_pending: '待扫码',
scanned: '已扫码',
role_ready: '待确认角色',
confirmed: '已确认',
failed: '失败',
expired: '已过期',
}
type CompleteFormValues = {
note?: string
externalOrderNo?: string
@@ -82,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>()
@@ -344,6 +359,16 @@ export default function AdminSemiAutoTasksPage() {
<Space direction="vertical" size={2}>
<Tag>{task.displayStatus.label}</Tag>
<Text type="secondary">{task.huyaUid ? `UID ${task.huyaUid}` : '未获取 UID'}</Text>
<Text type="secondary">
{task.platform === 'huya'
? `绑定:${BINDING_STATUS_LABELS[task.bindingStatus] || task.bindingStatus}`
: '微博登录即授权'}
</Text>
{task.platform === 'huya' && (task.bindGameRole || task.bindGameRoleId) ? (
<Text type="secondary">
{`角色:${task.bindGameRole || '-'}${task.bindGameRoleId ? `(${task.bindGameRoleId})` : '(无角色ID)'}`}
</Text>
) : null}
<Text type="secondary">
CK:
{task.credentialStatus === 'valid'
@@ -394,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"
@@ -616,6 +648,24 @@ export default function AdminSemiAutoTasksPage() {
<Descriptions.Item label="登录状态">
{detail.task.loginStatus === 'authenticated' ? 'CK 已获取' : '等待客户登录'}
</Descriptions.Item>
<Descriptions.Item label="绑定状态">
{detail.task.platform === 'weibo'
? '微博登录即授权'
: BINDING_STATUS_LABELS[detail.task.bindingStatus] || detail.task.bindingStatus}
</Descriptions.Item>
<Descriptions.Item label="绑定角色">
{detail.task.bindGameRole
? `${detail.task.bindGameRole}${detail.task.bindGameRoleId ? `(${detail.task.bindGameRoleId})` : '(无角色ID)'}`
: '-'}
</Descriptions.Item>
<Descriptions.Item label="客户填写角色">
{detail.task.customerGameRoleName
? `${detail.task.customerGameRoleName}${detail.task.customerGameRoleId ? `(${detail.task.customerGameRoleId})` : ''}`
: '-'}
</Descriptions.Item>
<Descriptions.Item label="区服">
{detail.task.customerServerZone || '-'}
</Descriptions.Item>
<Descriptions.Item label="客服">
{detail.task.assignedAdminName || '未领取'}
</Descriptions.Item>
@@ -687,6 +737,30 @@ export default function AdminSemiAutoTasksPage() {
{formatAdminDateTime(event.createdAt)} · {event.actorType}
{event.actorId ? ` ${event.actorId}` : ''}
</Text>
{event.eventType === 'binding_status_changed' && event.detail?.message ? (
<Text
type={
event.detail.rebindUnchanged === true ||
event.detail.rebindConfirmState === 'rejected'
? 'warning'
: 'secondary'
}
>
{String(event.detail.message)}
{Number(event.detail.rebindCooldownDays || 0) > 0 &&
event.detail.nextRebindAt
? ` · 下次可换绑 ${formatAdminDateTime(
String(event.detail.nextRebindAt),
)}`
: ''}
</Text>
) : null}
{event.eventType === 'binding_status_changed' &&
event.detail?.rebindConfirmMessage ? (
<Text type="secondary">
虎牙返回:{String(event.detail.rebindConfirmMessage)}
</Text>
) : null}
</Space>
),
}))}
@@ -698,6 +772,12 @@ export default function AdminSemiAutoTasksPage() {
)}
</Drawer>
<SemiAutoTaskHistoryDrawer
open={Boolean(historyTaskId)}
taskId={historyTaskId}
onClose={() => setHistoryTaskId(null)}
/>
<Modal
open={Boolean(completeTask)}
title="确认完成半自动履约"
@@ -765,6 +845,7 @@ function taskNeedsCustomerReauth(task: SemiAutoTask) {
function taskCanUseCredential(task: SemiAutoTask) {
return (
task.loginStatus === 'authenticated' &&
(task.platform === 'weibo' || task.bindingStatus === 'confirmed') &&
task.credentialReady &&
task.credentialStatus !== 'invalid' &&
task.credentialStatus !== 'error'
File diff suppressed because it is too large Load Diff
@@ -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`,
@@ -1,5 +1,9 @@
import { apiGet, apiPost } from '@/lib/http'
import type { CustomerLoginInfo, CustomerSemiAutoTask } from '@/types/customer-fulfillment'
import type {
CustomerBindingInfo,
CustomerLoginInfo,
CustomerSemiAutoTask,
} from '@/types/customer-fulfillment'
export function fetchCustomerFulfillment(orderNo: string) {
return apiGet<CustomerSemiAutoTask[]>(
@@ -14,6 +18,17 @@ export function markCustomerFulfillmentOpened(orderNo: string, taskId: number) {
)
}
export function saveCustomerTaskProfile(
orderNo: string,
taskId: number,
input: { roleName: string; roleId: string; serverZone: string },
) {
return apiPost<{ task: CustomerSemiAutoTask }>(
`/api/v1/customer-fulfillment/${encodeURIComponent(orderNo)}/tasks/${taskId}/profile`,
input,
)
}
export function startCustomerLogin(orderNo: string, taskId: number) {
return apiPost<{ task: CustomerSemiAutoTask; login: CustomerLoginInfo }>(
`/api/v1/customer-fulfillment/${encodeURIComponent(orderNo)}/tasks/${taskId}/login/start`,
@@ -27,6 +42,41 @@ export function pollCustomerLogin(orderNo: string, taskId: number) {
)
}
export function startCustomerBinding(
orderNo: string,
taskId: number,
options: { forceRebind?: boolean } = {},
) {
return apiPost<{ task: CustomerSemiAutoTask; binding: CustomerBindingInfo }>(
`/api/v1/customer-fulfillment/${encodeURIComponent(orderNo)}/tasks/${taskId}/binding/start`,
options.forceRebind ? { forceRebind: true } : {},
)
}
export function pollCustomerBinding(orderNo: string, taskId: number) {
return apiGet<{ task: CustomerSemiAutoTask; binding: CustomerBindingInfo | null }>(
`/api/v1/customer-fulfillment/${encodeURIComponent(orderNo)}/tasks/${taskId}/binding/status`,
)
}
export function confirmCustomerBinding(
orderNo: string,
taskId: number,
options: { acceptExistingRole?: boolean } = {},
) {
return apiPost<{ task: CustomerSemiAutoTask; binding: CustomerBindingInfo }>(
`/api/v1/customer-fulfillment/${encodeURIComponent(orderNo)}/tasks/${taskId}/binding/confirm`,
options.acceptExistingRole ? { acceptExistingRole: true } : {},
)
}
export function submitCustomerRebind(orderNo: string, taskId: number) {
return apiPost<{ task: CustomerSemiAutoTask; binding: CustomerBindingInfo }>(
`/api/v1/customer-fulfillment/${encodeURIComponent(orderNo)}/tasks/${taskId}/binding/rebind`,
{},
)
}
type CustomerHuyaChallengeBase = {
image: string
width: number
File diff suppressed because it is too large Load Diff
@@ -13,6 +13,7 @@ export type SemiAutoTask = {
platform: SemiAutoPlatform
platformLabel: string
loginStatus: string
bindingStatus: string
executionStatus: string
connectorMode: 'embedded' | 'external' | 'mock'
displayStatus: SemiAutoDisplayStatus
@@ -23,6 +24,13 @@ export type SemiAutoTask = {
credentialUpdatedAt: string | null
huyaUid: string
platformNickname: string
bindGameAccount: string
bindGameRole: string
bindGameRoleId: string
bindGameChannel: string
customerGameRoleId: string
customerGameRoleName: string
customerServerZone: string
targetQuantity: number
completedQuantity: number
assignedAdminUserId: number | null
@@ -73,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
@@ -1,3 +1,14 @@
export type CustomerBindingComparison = {
verdict: 'match' | 'mismatch' | 'unknown'
customerRoleName: string
customerRoleId: string
customerZone: string
boundRoleName: string
boundRoleId: string
boundZone: string
message: string
}
export type CustomerSemiAutoTask = {
id: number
platform: 'huya' | 'weibo'
@@ -8,10 +19,18 @@ export type CustomerSemiAutoTask = {
skuCode: string
quantity: number
loginStatus: string
bindingStatus: string
executionStatus: string
displayStatus: { key: string; label: string }
huyaUid: string
platformNickname: string
bindGameAccount: string
bindGameRole: string
bindGameRoleId: string
bindGameChannel: string
customerGameRoleId: string
customerGameRoleName: string
customerServerZone: string
completedAt: string | null
completionNote: string
semiAutoConfig: {
@@ -28,3 +47,31 @@ export type CustomerLoginInfo = {
expiresAt: string
message: string
}
export type CustomerBindingInfo = {
status: string
qrImage: string
qrExpiresAt: string
qrUrl: string
bindGameAccount: string
bindGameRole: string
bindGameRoleId: string
bindGameChannel: string
/** 平台角色 ID 是否可核对(纯数字);false 时客户页只提示联系客服。 */
roleIdVerified?: boolean
/** 已绑定角色但缺少可核对角色 ID,需要客服人工核实。 */
requiresSupport?: boolean
hasExistingBinding: boolean
rebindRequested: boolean
rebindUnchanged: boolean
rebindConfirmState: 'idle' | 'submitting' | 'accepted' | 'rejected'
rebindConfirmMessage: string
bindConfirmState?: 'idle' | 'submitting' | 'accepted' | 'rejected'
bindConfirmMessage?: string
rebindCooldownDays: number
nextRebindAt: string
platformChangeBindDay?: number
platformChangeBindTime?: number
message: string
comparison: CustomerBindingComparison
}
@@ -0,0 +1,157 @@
/**
* 半自动履约报文动作说明。
*
* trace 的 action 是原始格式:入站为「METHOD 路径」,虎牙出站为 WUP 方法名,
* 外部 Connector 为「METHOD 内部路径」。这里只做展示层映射,不写库、不改变报文内容。
*/
export type SemiAutoTraceActionInput = {
channel: string
action: string
}
/** 虎牙 WUP / livelink 出站动作。 */
const HUYA_RPC_ACTIONS: Record<string, string> = {
'webActUI.checkUserBindGameAccount': '查询虎牙账号已绑定角色',
'webActUI.confirmBindActAccount': '向虎牙提交绑定/换绑',
'webActUI.getLiveLinkParam': '获取绑定二维码参数',
'huyauserui.getUserProfile': '获取虎牙账号资料',
'livelink.getMiniAppQrcode': '生成登录二维码',
'livelink.poolingQrcodeStatus': '轮询扫码状态',
}
/** 旧版 Mock Connector 写入的历史动作,保留中文说明避免露出英文。 */
const LEGACY_ACTIONS: Record<string, string> = {
'mock.sms.send': '发送登录验证码(Mock Connector)',
'mock.sms.login': '验证码登录(Mock Connector)',
}
/** 客户接口尾路径 → 用途。 */
const CUSTOMER_ACTIONS: Record<string, string> = {
open: '客户打开履约页',
profile: '提交客户游戏资料',
'login/start': '发起平台登录',
'login/status': '查询登录状态',
'huya/sms/send': '发送虎牙登录验证码',
'huya/sms/login': '虎牙验证码登录',
'huya/sms/verify': '完成虎牙安全验证',
'binding/start': '开始绑定(查询已绑角色)',
'binding/status': '查询绑定状态',
'binding/rebind': '发起扫码换绑',
'binding/confirm': '确认绑定角色(含换绑)',
'weibo/config': '读取微博登录配置',
'weibo/sms/send': '发送微博登录验证码',
'weibo/sms/login': '微博验证码登录',
'weibo/qrcode': '获取微博登录二维码',
'weibo/qrcode/status': '查询微博扫码状态',
}
/** 运营接口尾路径 → 用途。 */
const ADMIN_ACTIONS: Record<string, string> = {
claim: '客服领取任务',
sync: '手动同步平台状态',
reauthorize: '重新发起客户授权',
'browser-session': '生成浏览器登录票据',
complete: '客服完成履约',
cancel: '取消履约任务',
'credential/export': '导出账号 CK',
history: '读取履约历史',
}
const CUSTOMER_PREFIX = '/api/v1/customer-fulfillment'
const ADMIN_PREFIX = '/api/v1/admin/semi-auto'
const CONNECTOR_PREFIX = '/api/internal/huya-semi-auto'
export function describeSemiAutoTraceAction(input: SemiAutoTraceActionInput): string {
const action = String(input?.action || '').trim()
if (!action) return ''
const channel = String(input?.channel || '').trim()
const named = HUYA_RPC_ACTIONS[action] || LEGACY_ACTIONS[action]
if (named) return named
const { method, path } = splitHttpAction(action)
if (!path) return ''
if (path.startsWith(CUSTOMER_PREFIX) || channel === 'customer_api') {
return describeCustomerAction(path)
}
if (path.startsWith(ADMIN_PREFIX) || channel === 'admin_api') {
return describeAdminAction(method, path)
}
if (path.startsWith(CONNECTOR_PREFIX) || channel === 'external_connector') {
return describeConnectorAction(method, path)
}
return ''
}
function splitHttpAction(action: string): { method: string; path: string } {
const match = /^(GET|POST|PUT|PATCH|DELETE)\s+(\S+)/i.exec(action)
if (!match) return { method: '', path: '' }
return {
method: match[1].toUpperCase(),
path: match[2].split('?')[0].split('#')[0],
}
}
function describeCustomerAction(path: string): string {
const match = /^\/api\/v1\/customer-fulfillment\/[^/]+(?:\/tasks\/[^/]+)?(?:\/(.*))?$/.exec(path)
if (!match) return ''
const tail = (match[1] || '').replace(/\/+$/, '')
if (!tail) return '读取履约任务'
return CUSTOMER_ACTIONS[tail] || ''
}
function describeAdminAction(method: string, path: string): string {
if (path === ADMIN_PREFIX + '/tasks') return '读取履约任务列表'
const taskMatch = /^\/api\/v1\/admin\/semi-auto\/tasks\/[^/]+(?:\/(.*))?$/.exec(path)
if (taskMatch) {
const tail = (taskMatch[1] || '').replace(/\/+$/, '')
if (!tail) {
return method === 'POST' || method === 'PUT' || method === 'PATCH'
? '更新履约任务'
: '读取履约任务详情'
}
return ADMIN_ACTIONS[tail] || ''
}
if (/^\/api\/v1\/admin\/semi-auto\/injections\/[^/]+$/.test(path)) {
return '校验浏览器注入票据'
}
return ''
}
function describeConnectorAction(method: string, path: string): string {
if (!path.startsWith(CONNECTOR_PREFIX)) return ''
const rest = path.slice(CONNECTOR_PREFIX.length).split('/').filter(Boolean)
if (rest.length === 0) return ''
if (rest[0] === 'sessions') {
if (rest.length === 1) return method === 'POST' ? '创建平台登录会话' : ''
if (rest.length === 2) {
if (method === 'DELETE') return '释放平台登录会话'
if (method === 'GET') return '查询登录会话'
return ''
}
if (rest.length === 3) {
if (rest[2] === 'binding') {
return method === 'POST' ? '开始绑定(含换绑)' : '查询绑定状态/快照'
}
if (rest[2] === 'browser-ticket') {
return method === 'DELETE' ? '释放浏览器票据' : '生成浏览器票据'
}
if (rest[2] === 'credential') return '读取平台账号 CK'
return ''
}
if (rest.length === 4 && rest[2] === 'binding' && rest[3] === 'confirm') {
return '确认绑定/换绑'
}
return ''
}
if (rest[0] === 'browser-tickets' && rest.length === 2) return '校验浏览器票据'
if (rest[0] === 'sms') {
if (rest[1] === 'send') return '发送平台登录验证码'
if (rest[1] === 'verify') return '完成平台安全验证'
if (rest[1] === 'login') return '平台验证码登录'
}
return ''
}
@@ -0,0 +1,64 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
import test from 'node:test'
const root = dirname(fileURLToPath(import.meta.url))
const source = readFileSync(
join(root, '../src/pages/customer-fulfillment/CustomerFulfillmentPage.tsx'),
'utf8',
)
const styles = readFileSync(join(root, '../src/styles/client.css'), 'utf8')
test('扫码识别角色后,资料不一致也打开对比弹窗', () => {
// 自动弹窗 effect 不再因 mismatch 提前 return。
assert.ok(source.includes('识别到角色(含与资料不一致)都要弹出对比框'))
assert.ok(!source.includes("if (bindingInfo.comparison.verdict === 'mismatch') return"))
// 手动刷新时 mismatch 同样打开弹窗,不再关闭并只弹提示。
assert.ok(source.includes('资料不一致同样打开对比框'))
assert.ok(!source.includes('平台角色与已填资料不一致,请先同步资料'))
})
test('对比弹窗在资料不一致时提供修改资料与同步平台角色入口', () => {
assert.ok(source.includes('修改资料'))
assert.ok(source.includes('同步平台角色'))
assert.ok(source.includes('canSyncBindingProfile'))
assert.ok(source.includes('onClick={openProfileEditor}'))
assert.ok(
source.includes(
"disabled={!bindingCustomerReady || bindingComparison?.verdict === 'mismatch'}",
),
)
assert.ok(styles.includes('.customer-binding-modal-actions.is-mismatch'))
assert.ok(styles.includes('repeat(auto-fit, minmax(140px, 1fr))'))
})
test('保存资料或同步平台角色后会重新打开对比弹窗', () => {
assert.ok(source.includes('function reopenBindingConfirm('))
assert.ok(source.includes("if (nextTask.bindingStatus !== 'role_ready') return false"))
assert.ok(source.includes('reopened = reopenBindingConfirm('))
assert.ok(
source.includes(
'reopenBindingConfirm(bindingResponse.data.task, bindingResponse.data.binding)',
),
)
assert.ok(source.includes('角色资料已保存,请重新核对绑定角色'))
})
test('资料不一致时仍保持后端严格比对:确认按钮禁用并显示原因', () => {
assert.ok(source.includes('两侧角色信息不一致,无法确认绑定'))
assert.ok(source.includes('customer-binding-modal-error'))
})
test('二维码区提示扫码后会核对平台角色与已填资料', () => {
assert.ok(source.includes('扫码后系统会核对平台角色与已填资料'))
})
test('换绑流程刷新二维码必须带 forceRebind,避免直接返回已有角色', () => {
assert.ok(source.includes('function handleRefreshBindingQr()'))
assert.ok(source.includes('handleRefreshBinding(bindingInfo?.rebindRequested === true)'))
// 三处刷新/重新获取入口都不能再固定传 false。
assert.ok(!source.includes('handleRefreshBinding(false)'))
assert.ok(source.includes('onClick={handleRefreshBindingQr}'))
})
@@ -0,0 +1,31 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
import test from 'node:test'
const source = readFileSync(
join(
dirname(fileURLToPath(import.meta.url)),
'../src/pages/customer-fulfillment/CustomerFulfillmentPage.tsx',
),
'utf8',
)
test('换绑失败页用「返回上一步」替换「仍使用原角色」', () => {
assert.ok(source.includes('rebindFailureDismissed'))
assert.ok(source.includes('返回上一步'))
assert.ok(!source.includes('仍使用原角色'))
})
test('返回后展示资料不一致核对界面', () => {
assert.ok(source.includes('showRebindFailure'))
assert.ok(source.includes('!showRebindFailure &&'))
assert.ok(source.includes('同步平台角色并继续'))
assert.ok(source.includes('id="customer-binding-stage"'))
})
test('资料同步后提供确认使用原角色', () => {
assert.ok(source.includes('确认使用原角色'))
assert.ok(source.includes('handleAcceptExistingRole'))
})
@@ -0,0 +1,58 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
import test from 'node:test'
const source = readFileSync(
join(
dirname(fileURLToPath(import.meta.url)),
'../src/pages/customer-fulfillment/CustomerFulfillmentPage.tsx',
),
'utf8',
)
const styles = readFileSync(
join(dirname(fileURLToPath(import.meta.url)), '../src/styles/client.css'),
'utf8',
)
test('微博与虎牙共用同一套登录表单结构', () => {
assert.match(source, /const renderLoginForm = \(options: \{/)
assert.ok(source.includes("platformLabel: '虎牙'"))
assert.ok(source.includes("platformLabel: '微博'"))
assert.ok(!source.includes('customer-auth-tabs'))
assert.ok(!source.includes('SafetyCertificateOutlined'))
})
test('微博保留两种登录方式与全部原有提示', () => {
assert.ok(source.includes('改用二维码登录'))
assert.ok(source.includes('改用手机号登录'))
assert.ok(source.includes('smsMfaRequired'))
assert.ok(source.includes('如安全验证弹窗未出现'))
assert.ok(source.includes('CustomerPrivacyNote'))
assert.ok(source.includes('温馨提示:未成年人禁止下单'))
})
test('二维码切换与虎牙一致:直接切到扫码并发起登录', () => {
assert.ok(source.includes("setLoginMode('qr')"))
assert.ok(source.includes('void handleStartLogin()'))
})
test('微博订单卡只展示订单号/商品/平台/状态,不含游戏和角色名称', () => {
const weiboBranch = source.slice(
source.indexOf("if (task.platform === 'weibo')"),
source.indexOf('const zone = task.customerServerZone'),
)
assert.ok(weiboBranch.includes('<span>订单号</span>'))
assert.ok(weiboBranch.includes('<span>商品</span>'))
assert.ok(weiboBranch.includes('<span>平台</span>'))
assert.ok(weiboBranch.includes('<span>状态</span>'))
assert.ok(!weiboBranch.includes('角色名称'))
assert.ok(!weiboBranch.includes('游戏名称'))
})
test('微博顶部使用 inside-kv 背景,虎牙保持纯色', () => {
assert.ok(styles.includes('.customer-auth-page.is-weibo .customer-auth-hero'))
assert.ok(styles.includes("url('/images/customer/inside-kv.jpg')"))
assert.ok(!styles.includes('.customer-auth-page.is-huya .customer-auth-hero'))
})
@@ -0,0 +1,121 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { describeSemiAutoTraceAction } from '../src/utils/semi-auto-trace-action.ts'
const label = (channel: string, action: string) => describeSemiAutoTraceAction({ channel, action })
test('客户接口:绑定与登录动作都有中文说明', () => {
assert.equal(
label('customer_api', 'POST /api/v1/customer-fulfillment/MOCKSA1/tasks/51/binding/confirm'),
'确认绑定角色(含换绑)',
)
assert.equal(
label('customer_api', 'GET /api/v1/customer-fulfillment/MOCKSA1/tasks/51/binding/status?x=1'),
'查询绑定状态',
)
assert.equal(
label('customer_api', 'POST /api/v1/customer-fulfillment/MOCKSA1/tasks/51/binding/start'),
'开始绑定(查询已绑角色)',
)
assert.equal(
label('customer_api', 'POST /api/v1/customer-fulfillment/MOCKSA1/tasks/51/profile'),
'提交客户游戏资料',
)
assert.equal(
label('customer_api', 'POST /api/v1/customer-fulfillment/MOCKSA1/tasks/51/open'),
'客户打开履约页',
)
assert.equal(
label('customer_api', 'GET /api/v1/customer-fulfillment/MOCKSA1/tasks/51/login/status'),
'查询登录状态',
)
assert.equal(label('customer_api', 'GET /api/v1/customer-fulfillment/MOCKSA1'), '读取履约任务')
})
test('客户接口:短信与微博动作', () => {
assert.equal(
label('customer_api', 'POST /api/v1/customer-fulfillment/MOCKSA1/tasks/51/huya/sms/send'),
'发送虎牙登录验证码',
)
assert.equal(
label('customer_api', 'POST /api/v1/customer-fulfillment/MOCKSA1/tasks/51/huya/sms/verify'),
'完成虎牙安全验证',
)
assert.equal(
label('customer_api', 'GET /api/v1/customer-fulfillment/MOCKSA1/tasks/51/weibo/qrcode/status'),
'查询微博扫码状态',
)
})
test('运营接口:领取、同步、完成与详情', () => {
assert.equal(label('admin_api', 'POST /api/v1/admin/semi-auto/tasks/39/claim'), '客服领取任务')
assert.equal(label('admin_api', 'POST /api/v1/admin/semi-auto/tasks/39/sync'), '手动同步平台状态')
assert.equal(label('admin_api', 'GET /api/v1/admin/semi-auto/tasks/39'), '读取履约任务详情')
assert.equal(label('admin_api', 'POST /api/v1/admin/semi-auto/tasks/39'), '更新履约任务')
assert.equal(
label('admin_api', 'GET /api/v1/admin/semi-auto/injections/ticket-1'),
'校验浏览器注入票据',
)
})
test('虎牙 WUP 与 livelink 动作', () => {
assert.equal(label('huya_wup', 'webActUI.checkUserBindGameAccount'), '查询虎牙账号已绑定角色')
assert.equal(label('huya_wup', 'webActUI.confirmBindActAccount'), '向虎牙提交绑定/换绑')
assert.equal(label('huya_wup', 'huyauserui.getUserProfile'), '获取虎牙账号资料')
assert.equal(label('huya_http', 'livelink.getMiniAppQrcode'), '生成登录二维码')
assert.equal(label('huya_http', 'livelink.poolingQrcodeStatus'), '轮询扫码状态')
})
test('外部 Connector:会话、绑定与票据', () => {
const sessionId = '32aabcb6-27af-420b-b223-a47db63861bf'
assert.equal(
label('external_connector', 'POST /api/internal/huya-semi-auto/sessions'),
'创建平台登录会话',
)
assert.equal(
label('external_connector', `POST /api/internal/huya-semi-auto/sessions/${sessionId}/binding`),
'开始绑定(含换绑)',
)
assert.equal(
label('external_connector', `GET /api/internal/huya-semi-auto/sessions/${sessionId}/binding`),
'查询绑定状态/快照',
)
assert.equal(
label(
'external_connector',
`POST /api/internal/huya-semi-auto/sessions/${sessionId}/binding/confirm`,
),
'确认绑定/换绑',
)
assert.equal(
label('external_connector', 'GET /api/internal/huya-semi-auto/browser-tickets/ticket-1'),
'校验浏览器票据',
)
assert.equal(
label('external_connector', 'POST /api/internal/huya-semi-auto/sms/login'),
'平台验证码登录',
)
})
test('未知动作与空值不展示噪音', () => {
assert.equal(label('customer_api', 'POST /api/v1/customer-fulfillment/X/tasks/1/unknown'), '')
assert.equal(label('huya_wup', 'some.unknown.method'), '')
assert.equal(label('external_connector', 'GET /api/internal/huya-semi-auto/unknown'), '')
assert.equal(label('', ''), '')
assert.equal(label('customer_api', 'POST /api/v1/other/endpoint'), '')
})
test('渠道缺失时按路径兜底识别', () => {
assert.equal(
label('', 'POST /api/v1/customer-fulfillment/MOCKSA1/tasks/51/binding/rebind'),
'发起扫码换绑',
)
assert.equal(label('', 'POST /api/v1/admin/semi-auto/tasks/39/cancel'), '取消履约任务')
assert.equal(label('', 'DELETE /api/internal/huya-semi-auto/sessions/abc'), '释放平台登录会话')
})
test('历史 Mock 动作保留中文说明', () => {
assert.equal(label('external_connector', 'mock.sms.send'), '发送登录验证码(Mock Connector)')
assert.equal(label('external_connector', 'mock.sms.login'), '验证码登录(Mock Connector)')
})