Files
order_site/apps/frontend/src/pages/admin/AdminSemiAutoTasksPage.tsx
T

1051 lines
37 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import {
CheckCircleOutlined,
ChromeOutlined,
CopyOutlined,
HistoryOutlined,
KeyOutlined,
ReloadOutlined,
SendOutlined,
UserSwitchOutlined,
} from '@ant-design/icons'
import {
Alert,
App,
Button,
Card,
Descriptions,
Drawer,
Form,
Input,
InputNumber,
Modal,
Select,
Space,
Tag,
Timeline,
Typography,
} from 'antd'
import type { TableColumnsType } from 'antd'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useEffect, useMemo, useRef, 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,
claimAdminSemiAutoTask,
completeAdminSemiAutoTask,
createAdminSemiAutoBrowserSession,
exportAdminSemiAutoCredential,
fetchAdminSemiAutoTask,
fetchAdminSemiAutoTasks,
requestAdminSemiAutoCustomerReauth,
syncAdminSemiAutoTask,
} from '@/services/admin/semi-auto'
import type { SemiAutoTask } from '@/types/admin/semi-auto'
import type { UploadedFile } from '@/types/worker-platform'
import { formatAdminDateTime } from '@/utils/admin-time'
import { buildCustomerFulfillmentPath } from '@/utils/customer-fulfillment-link'
import { resolvePostInjectionUrl } from '@/utils/semi-auto-injection'
import { canCompleteSemiAutoTask, canInjectSemiAutoBrowser } from '@/utils/semi-auto-task-readiness'
const { Text } = Typography
const STATUS_COLORS: Record<string, string> = {
waiting_profile: 'gold',
waiting_customer: 'blue',
waiting_login: 'blue',
login_scanned: 'cyan',
waiting_binding: 'gold',
binding_confirm: 'orange',
rebind_required: 'gold',
rebind_blocked_account: 'red',
rebind_blocked_target_role: 'red',
rebind_effect_pending: 'processing',
binding_support: 'magenta',
binding_expired: 'red',
binding_failed: 'red',
waiting_operator: 'volcano',
credential_expired: 'red',
processing: 'processing',
completed: 'success',
failed: 'error',
cancelled: 'default',
}
const PLATFORM_LABELS: Record<string, string> = {
huya: '虎牙',
weibo: '微博',
}
const BINDING_STATUS_LABELS: Record<string, string> = {
not_started: '未开始',
qr_pending: '待扫码',
scanned: '已扫码',
role_ready: '待确认角色',
confirmed: '已确认',
failed: '失败',
expired: '已过期',
}
const BINDING_FLOW_LABELS: Record<string, string> = {
binding_query_required: '待查询绑定',
initial_bind_required: '待首次绑定',
first_bind_qr_pending: '首次绑定待扫码',
first_bind_role_ready: '首次绑定待确认',
first_bind_role_mismatch: '首次绑定角色不一致',
first_bind_failed: '首次绑定失败',
current_role_confirmable: '当前角色待确认',
rebind_required: '需要换绑',
rebind_qr_pending: '换绑待扫码',
rebind_role_ready: '换绑待确认',
rebind_effect_pending: '换绑生效中',
rebind_blocked_account: '账号换绑冷却',
rebind_blocked_target_role: '目标角色冷却',
rebind_rejected: '虎牙拒绝换绑',
rebind_effect_failed: '换绑未生效',
confirmed: '绑定已确认',
manual_review: '绑定需人工核实',
expired: '绑定已过期',
}
type CompleteFormValues = {
note?: string
externalOrderNo?: string
costYuan?: number
}
const INJECTION_FOLLOW_UP_TIMEOUT_MS = 30_000
type PendingInjection = {
taskId: number
platform: SemiAutoTask['platform']
popup: Window | null
timeoutId: number
}
export default function AdminSemiAutoTasksPage() {
const { message, modal } = App.useApp()
const queryClient = useQueryClient()
const [keyword, setKeyword] = useState('')
const [platform, setPlatform] = useState('')
const [status, setStatus] = useState('')
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>()
const pendingInjectionRef = useRef<PendingInjection | null>(null)
const params = useMemo(
() => ({
page,
pageSize,
keyword: keyword.trim() || undefined,
platform: platform || undefined,
status: status || undefined,
}),
[keyword, page, pageSize, platform, status],
)
const listQuery = useQuery({
queryKey: ['admin-semi-auto-tasks', params],
queryFn: () => fetchAdminSemiAutoTasks(params),
})
const detailQuery = useQuery({
queryKey: ['admin-semi-auto-task', detailTaskId],
queryFn: () => fetchAdminSemiAutoTask(Number(detailTaskId)),
enabled: Boolean(detailTaskId),
})
const list = listQuery.data?.data?.items || []
const pagination = listQuery.data?.data?.pagination
const detail = detailQuery.data?.data
useEffect(() => {
if (detailTaskId && listQuery.data && !list.some((item) => item.id === detailTaskId)) {
setDetailTaskId(null)
}
}, [detailTaskId, list, listQuery.data])
useEffect(() => {
const handleResult = (event: Event) => {
const detail = (event as CustomEvent<string>).detail
if (typeof detail !== 'string') return
let result: { ok?: boolean; written?: number; error?: string }
try {
result = JSON.parse(detail) as { ok?: boolean; written?: number; error?: string }
} catch {
return
}
if (!result || typeof result !== 'object') return
const pending = pendingInjectionRef.current
if (result.ok) {
message.success(`浏览器登录态已注入(${Number(result.written || 0)} 个 Cookie)`)
if (!pending) return
window.clearTimeout(pending.timeoutId)
pendingInjectionRef.current = null
const targetUrl = resolvePostInjectionUrl(pending.platform)
const popup = pending.popup
if (!targetUrl) {
if (popup && !popup.closed) popup.close()
return
}
if (popup && !popup.closed) {
try {
popup.location.href = targetUrl
popup.focus()
return
} catch {
// 占位页已被关闭或无法导航:先关掉残留标签,再用 window.open 兜底。
try {
popup.close()
} catch {
// 关闭失败不影响继续打开目标页。
}
}
}
const opened = window.open(targetUrl, '_blank')
if (opened) {
opened.focus()
return
}
modal.info({
title: '注入成功',
content: (
<span>
浏览器拦截了自动打开的新标签页,请
<a href={targetUrl} target="_blank" rel="noreferrer">
点击这里打开平台页面
</a>
。
</span>
),
})
return
}
message.error(result.error || '浏览器登录态注入失败')
if (!pending) return
window.clearTimeout(pending.timeoutId)
pendingInjectionRef.current = null
if (pending.popup && !pending.popup.closed) pending.popup.close()
}
window.addEventListener('huya-exchange-result', handleResult)
return () => window.removeEventListener('huya-exchange-result', handleResult)
}, [message, modal])
// 页面卸载时清理未完成的占位页,避免留下空白标签。
useEffect(() => {
return () => {
const pending = pendingInjectionRef.current
if (!pending) return
window.clearTimeout(pending.timeoutId)
if (pending.popup && !pending.popup.closed) pending.popup.close()
pendingInjectionRef.current = null
}
}, [])
const syncMutation = useMutation({
mutationFn: (taskId: number) => syncAdminSemiAutoTask(taskId),
onSuccess: () => {
message.success('状态已刷新')
void refreshAll()
},
onError: (error) => message.error(error instanceof Error ? error.message : '刷新失败'),
})
const claimMutation = useMutation({
mutationFn: (taskId: number) => claimAdminSemiAutoTask(taskId),
onSuccess: () => {
message.success('任务已领取')
void refreshAll()
},
onError: (error) => message.error(error instanceof Error ? error.message : '领取失败'),
})
function cancelPendingInjection() {
const pending = pendingInjectionRef.current
if (!pending) return
window.clearTimeout(pending.timeoutId)
if (pending.popup && !pending.popup.closed) pending.popup.close()
pendingInjectionRef.current = null
}
function openInjectionPlaceholder() {
const popup = window.open('about:blank', '_blank')
if (!popup) return null
try {
popup.document.title = '正在注入浏览器登录态'
popup.document.body.textContent = '正在注入浏览器登录态,完成后将自动打开平台页面…'
} catch {
// 占位内容写入失败不影响后续跳转。
}
return popup
}
const injectionMutation = useMutation({
mutationFn: (task: SemiAutoTask) =>
createAdminSemiAutoBrowserSession(task.id, firstTargetUrl(task)),
onSuccess: (response) => {
const ticket = String(response.data?.ticket || '').trim()
if (!ticket) {
cancelPendingInjection()
message.error('注入票据生成失败')
return
}
window.postMessage({ type: 'ORDER_SITE_SEMI_AUTO_INJECT', ticket }, window.location.origin)
message.info('正在注入浏览器登录态,请稍候')
void refreshAll()
},
onError: (error) => {
cancelPendingInjection()
message.error(error instanceof Error ? error.message : '打开浏览器登录态失败')
},
})
function startInjection(task: SemiAutoTask) {
if (pendingInjectionRef.current) {
message.warning('上一次注入尚未完成,请稍候')
return
}
// 扩展内容脚本会在白名单页面打标记;没有标记时直接提示,避免空等 30 秒。
if (document.documentElement.dataset.huyaExchangeHelper !== '1') {
message.warning('未检测到浏览器扩展,请启用「虎牙兑换助手」后刷新本页')
return
}
const popup = openInjectionPlaceholder()
const timeoutId = window.setTimeout(() => {
const pending = pendingInjectionRef.current
if (!pending) return
pendingInjectionRef.current = null
if (pending.popup && !pending.popup.closed) pending.popup.close()
message.warning('未检测到注入完成,请确认浏览器扩展已启用后重试')
}, INJECTION_FOLLOW_UP_TIMEOUT_MS)
pendingInjectionRef.current = {
taskId: task.id,
platform: task.platform,
popup,
timeoutId,
}
injectionMutation.mutate(task)
}
const credentialExportMutation = useMutation({
mutationFn: (taskId: number) => exportAdminSemiAutoCredential(taskId),
onSuccess: (response) => {
const text =
String(response.data?.cookieHeader || '').trim() ||
(response.data?.cookies || []).map((cookie) => `${cookie.name}=${cookie.value}`).join('; ')
if (!text) {
message.error('当前任务没有可复制的 CK')
return
}
void navigator.clipboard
.writeText(text)
.then(() => message.success('最终 CK 已复制'))
.catch(() => message.error('复制失败,请检查浏览器剪贴板权限'))
},
onError: (error) => message.error(error instanceof Error ? error.message : '复制账号 CK 失败'),
})
const reauthMutation = useMutation({
mutationFn: (task: SemiAutoTask) => requestAdminSemiAutoCustomerReauth(task.id),
onSuccess: async (response, task) => {
const copied = await copyCustomerLink(response.data?.task || task, '')
message.success(
copied ? '已重新发起授权,客户链接已复制' : '已重新发起授权,请手动复制客户链接',
)
await refreshAll()
},
onError: (error) =>
message.error(error instanceof Error ? error.message : '重新发起客户授权失败'),
})
const completeMutation = useMutation({
mutationFn: async (values: CompleteFormValues) => {
if (!completeTask) throw new Error('任务不存在')
const costFen =
values.costYuan !== undefined && values.costYuan !== null
? Math.round(Number(values.costYuan) * 100)
: undefined
return completeAdminSemiAutoTask(completeTask.id, {
note: values.note || '',
externalOrderNo: values.externalOrderNo || '',
...(costFen !== undefined ? { costFen } : {}),
screenshots: completeFiles.map((file) => ({ ...file })),
})
},
onSuccess: () => {
message.success('半自动履约已完成')
setCompleteTask(null)
setCompleteFiles([])
completeForm.resetFields()
void refreshAll()
},
onError: (error) => message.error(error instanceof Error ? error.message : '完成履约失败'),
})
const cancelMutation = useMutation({
mutationFn: ({ taskId, reason }: { taskId: number; reason: string }) =>
cancelAdminSemiAutoTask(taskId, reason),
onSuccess: () => {
message.success('任务已取消')
void refreshAll()
},
onError: (error) => message.error(error instanceof Error ? error.message : '取消失败'),
})
async function refreshAll() {
await Promise.all([
queryClient.invalidateQueries({ queryKey: ['admin-semi-auto-tasks'] }),
detailTaskId
? queryClient.invalidateQueries({ queryKey: ['admin-semi-auto-task', detailTaskId] })
: Promise.resolve(),
])
}
async function copyCustomerLink(task: SemiAutoTask, successMessage = '客户授权链接已复制') {
const path = buildCustomerFulfillmentPath(task.orderNo, task.platform)
if (!path) {
message.error('订单号为空,无法生成客户链接')
return false
}
const url = `${window.location.origin}${path}`
try {
await navigator.clipboard.writeText(url)
if (successMessage) message.success(successMessage)
return true
} catch {
message.error('复制失败,请手动复制客户链接')
return false
}
}
function confirmReauth(task: SemiAutoTask) {
modal.confirm({
title: '重新发送客户授权',
content: '当前登录状态会失效,客户需要打开新的授权链接重新登录。原授权记录会保留。',
okText: '重新发送并复制链接',
cancelText: '取消',
onOk: () => reauthMutation.mutateAsync(task),
})
}
function confirmCopyCredential(task: SemiAutoTask) {
modal.confirm({
title: '复制最终 CK',
content: 'CK 等同于平台登录态。复制后请勿发给无关人员,也不要保存到聊天记录或工单备注。',
okText: '确认复制',
okButtonProps: { danger: true },
cancelText: '取消',
onOk: () => credentialExportMutation.mutateAsync(task.id),
})
}
function openComplete(task: SemiAutoTask) {
setCompleteTask(task)
setCompleteFiles([])
completeForm.resetFields()
}
function confirmCancel(task: SemiAutoTask) {
let reason = ''
modal.confirm({
title: '取消半自动履约任务',
content: (
<Input.TextArea
rows={3}
placeholder="请填写取消原因(可选)"
onChange={(event) => {
reason = event.target.value
}}
/>
),
okText: '确认取消',
okButtonProps: { danger: true },
cancelText: '返回',
onOk: () => cancelMutation.mutateAsync({ taskId: task.id, reason }),
})
}
const columns: TableColumnsType<SemiAutoTask> = [
{
title: '订单 / 商品',
key: 'order',
width: 260,
render: (_, task) => (
<Space direction="vertical" size={2}>
<Text strong>{task.orderNo}</Text>
<Text>{task.productName || task.skuName || task.skuCode}</Text>
<Text type="secondary">SKU:{task.skuCode || '-'}</Text>
</Space>
),
},
{
title: '平台',
dataIndex: 'platform',
width: 120,
render: (value: string, task) => (
<Space direction="vertical" size={4}>
<Tag color="purple">{PLATFORM_LABELS[value] || value}</Tag>
<Tag color={task.connectorMode === 'mock' ? 'orange' : 'green'}>
{task.connectorMode === 'mock' ? 'Mock' : '真实'}
</Tag>
</Space>
),
},
{
title: '客户登录',
key: 'login',
width: 180,
render: (_, task) => (
<Space direction="vertical" size={2}>
<Tag>{task.displayStatus.label}</Tag>
<Text type="secondary">{task.displayStatus.nextAction}</Text>
<Text type="secondary">{task.huyaUid ? `UID ${task.huyaUid}` : '未获取 UID'}</Text>
<Text type="secondary">
{`绑定:${
BINDING_FLOW_LABELS[task.bindingFlowState] ||
BINDING_STATUS_LABELS[task.bindingStatus] ||
task.bindingStatus
}`}
</Text>
{task.bindGameRole || task.bindGameRoleToken ? (
<Text type="secondary">
{`当前角色:${task.bindGameRole || '-'}${
task.bindGameRoleToken ? '(平台加密标识已识别)' : ''
}`}
</Text>
) : null}
{task.pendingBindGameRole ? (
<Text type="secondary">{`待确认角色:${task.pendingBindGameRole}`}</Text>
) : null}
<Text type="secondary">
CK:
{task.credentialStatus === 'valid'
? '有效'
: task.credentialStatus === 'invalid'
? '失效'
: task.credentialStatus === 'error'
? '检测异常'
: '未保存'}
</Text>
</Space>
),
},
{
title: '账号凭证',
key: 'credential',
width: 190,
render: (_, task) => (
<Space direction="vertical" size={2}>
<Text strong>{task.platformNickname || task.huyaUid || '未获取账号'}</Text>
<Text type="secondary">
{task.credentialSource
? `${task.credentialSource} · ${formatAdminDateTime(task.credentialUpdatedAt)}`
: '尚无 CK'}
</Text>
</Space>
),
},
{
title: '客服',
dataIndex: 'assignedAdminName',
width: 110,
render: (value: string) => value || '未领取',
},
{
title: '更新时间',
dataIndex: 'updatedAt',
width: 155,
render: (value: string) => formatAdminDateTime(value),
},
{
title: '操作',
key: 'actions',
width: 520,
render: (_, task) => (
<Space direction="vertical" size={6} style={{ width: '100%' }}>
<Space wrap>
<Button size="small" onClick={() => setDetailTaskId(task.id)}>
详情
</Button>
<Button
size="small"
icon={<HistoryOutlined />}
onClick={() => setHistoryTaskId(task.id)}
>
历史
</Button>
{taskNeedsCustomerReauth(task) ? (
<Button
size="small"
type="primary"
icon={<SendOutlined />}
loading={reauthMutation.isPending}
onClick={() => confirmReauth(task)}
>
重发授权
</Button>
) : null}
<Button
size="small"
icon={<KeyOutlined />}
disabled={!task.credentialReady}
loading={credentialExportMutation.isPending}
onClick={() => confirmCopyCredential(task)}
>
复制 CK
</Button>
<Button
size="small"
icon={<ChromeOutlined />}
disabled={!canInjectSemiAutoBrowser(task)}
loading={injectionMutation.isPending}
onClick={() => startInjection(task)}
>
注入浏览器
</Button>
</Space>
<Space wrap>
<Button
size="small"
icon={<CopyOutlined />}
onClick={() => void copyCustomerLink(task)}
>
客户链接
</Button>
<Button
size="small"
icon={<ReloadOutlined />}
loading={syncMutation.isPending}
onClick={() => syncMutation.mutate(task.id)}
>
刷新
</Button>
{!task.assignedAdminUserId ? (
<Button
size="small"
icon={<UserSwitchOutlined />}
loading={claimMutation.isPending}
onClick={() => claimMutation.mutate(task.id)}
>
领取
</Button>
) : null}
{task.executionStatus !== 'completed' &&
task.executionStatus !== 'cancelled' &&
!taskNeedsCustomerReauth(task) ? (
<Button
size="small"
type="primary"
icon={<CheckCircleOutlined />}
disabled={!canCompleteSemiAutoTask(task)}
onClick={() => openComplete(task)}
>
完成
</Button>
) : null}
{task.executionStatus !== 'completed' && task.executionStatus !== 'cancelled' ? (
<Button size="small" danger onClick={() => confirmCancel(task)}>
取消
</Button>
) : null}
</Space>
</Space>
),
},
]
return (
<section className="page-stack">
<PageHeader
title="半自动履约"
description="人工客服渠道下的平台账号授权、扫码绑定和浏览器辅助履约。"
/>
<Card size="small">
<Space wrap style={{ marginBottom: 16 }}>
<Input.Search
allowClear
placeholder="订单号 / 商品 / UID / 角色"
value={keyword}
onChange={(event) => {
setKeyword(event.target.value)
setPage(1)
}}
style={{ width: 280 }}
/>
<Select
allowClear
placeholder="全部平台"
value={platform || undefined}
onChange={(value) => {
setPlatform(value || '')
setPage(1)
}}
options={[
{ value: 'huya', label: '虎牙' },
{ value: 'weibo', label: '微博' },
]}
style={{ width: 130 }}
/>
<Select
allowClear
placeholder="全部状态"
value={status || undefined}
onChange={(value) => {
setStatus(value || '')
setPage(1)
}}
options={[
{ value: 'waiting_customer', label: '等待客户' },
{ value: 'waiting_operator', label: '等待客服' },
{ value: 'processing', label: '处理中' },
{ value: 'completed', label: '已完成' },
{ value: 'failed', label: '失败' },
{ value: 'cancelled', label: '已取消' },
]}
style={{ width: 130 }}
/>
<Button icon={<ReloadOutlined />} onClick={() => void listQuery.refetch()}>
刷新
</Button>
</Space>
<PercentTable<SemiAutoTask>
rowKey="id"
loading={listQuery.isLoading}
columns={columns}
dataSource={list}
scroll={{ x: 1400 }}
pagination={{
current: pagination?.page || page,
pageSize: pagination?.pageSize || pageSize,
total: pagination?.total || 0,
showSizeChanger: true,
onChange: (nextPage, nextPageSize) => {
setPage(nextPage)
setPageSize(nextPageSize)
},
}}
/>
</Card>
<Drawer
open={Boolean(detailTaskId)}
width={720}
title={detail?.task ? `半自动履约 · ${detail.task.orderNo}` : '半自动履约详情'}
onClose={() => setDetailTaskId(null)}
>
{detailQuery.isLoading ? (
<Text type="secondary">加载中...</Text>
) : detail?.task ? (
<Space direction="vertical" size={16} style={{ width: '100%' }}>
<Descriptions bordered size="small" column={2}>
<Descriptions.Item label="商品" span={2}>
{detail.task.productName}
</Descriptions.Item>
<Descriptions.Item label="平台">
{PLATFORM_LABELS[detail.task.platform] || detail.task.platform}
</Descriptions.Item>
<Descriptions.Item label="Connector">
<Tag color={detail.task.connectorMode === 'mock' ? 'orange' : 'green'}>
{detail.task.connectorMode === 'mock'
? '内置 Mock'
: detail.task.connectorMode === 'external'
? '远程真实'
: '内置真实'}
</Tag>
</Descriptions.Item>
<Descriptions.Item label="当前状态">
<Tag color={STATUS_COLORS[detail.task.displayStatus.key] || 'default'}>
{detail.task.displayStatus.label}
</Tag>
</Descriptions.Item>
<Descriptions.Item label={detail.task.platform === 'weibo' ? '微博 UID' : '虎牙 UID'}>
{detail.task.huyaUid || '-'}
</Descriptions.Item>
<Descriptions.Item label="平台昵称">
{detail.task.platformNickname || '-'}
</Descriptions.Item>
<Descriptions.Item label="账号 CK">
<Space size={6}>
<Tag
color={
detail.task.credentialStatus === 'valid'
? 'green'
: detail.task.credentialStatus === 'invalid'
? 'red'
: 'default'
}
>
{detail.task.credentialStatus === 'valid'
? '有效'
: detail.task.credentialStatus === 'invalid'
? '失效'
: detail.task.credentialStatus === 'error'
? '检测异常'
: '未保存'}
</Tag>
<Text type="secondary">
{detail.task.credentialSource
? `${detail.task.credentialSource} · ${formatAdminDateTime(detail.task.credentialUpdatedAt)}`
: '-'}
</Text>
</Space>
</Descriptions.Item>
<Descriptions.Item label="平台昵称">
{detail.task.platformNickname || '-'}
</Descriptions.Item>
<Descriptions.Item label="登录状态">
{detail.task.loginStatus === 'authenticated' ? 'CK 已获取' : '等待客户登录'}
</Descriptions.Item>
<Descriptions.Item label="绑定状态">
{BINDING_FLOW_LABELS[detail.task.bindingFlowState] ||
BINDING_STATUS_LABELS[detail.task.bindingStatus] ||
detail.task.bindingStatus}
</Descriptions.Item>
<Descriptions.Item label="平台当前角色">
{detail.task.bindGameRole || '-'}
</Descriptions.Item>
<Descriptions.Item label="待确认角色">
{detail.task.pendingBindGameRole || '-'}
</Descriptions.Item>
<Descriptions.Item label="平台角色标识">
{detail.task.platformGameRoleUid
? `游戏角色 UID ${detail.task.platformGameRoleUid}`
: detail.task.bindGameRoleToken || detail.task.pendingBindGameRoleToken
? '已识别的虎牙加密角色标识'
: '-'}
</Descriptions.Item>
<Descriptions.Item label="平台绑定渠道">
{[
detail.task.bindGameChannel,
detail.comparison?.boundZone ? `识别区服 ${detail.comparison.boundZone}` : '',
]
.filter(Boolean)
.join(' · ') || '-'}
</Descriptions.Item>
<Descriptions.Item label="客户填写角色">
{detail.task.customerGameRoleName || '-'}
</Descriptions.Item>
<Descriptions.Item label="客户游戏角色 UID">
{detail.task.customerGameRoleId || '-'}
</Descriptions.Item>
<Descriptions.Item label="客户区服">
{detail.task.customerServerZone || '-'}
</Descriptions.Item>
<Descriptions.Item label="角色比对" span={2}>
<Space direction="vertical" size={2}>
<Tag
color={
detail.comparison?.verdict === 'match'
? 'green'
: detail.comparison?.verdict === 'mismatch'
? 'red'
: 'orange'
}
>
{detail.comparison?.verdict === 'match'
? '三项一致,可提交平台绑定'
: detail.comparison?.verdict === 'mismatch'
? '资料与平台角色不一致'
: '信息不完整,需人工核实'}
</Tag>
<Text type="secondary">{detail.comparison?.message || '-'}</Text>
</Space>
</Descriptions.Item>
<Descriptions.Item label="绑定判定" span={2}>
<Space direction="vertical" size={2}>
<Text strong>{BINDING_FLOW_LABELS[detail.task.bindingFlowState] || '-'}</Text>
<Text type="secondary">{detail.task.bindingDecision?.message || '-'}</Text>
{detail.task.bindingDecision?.rebindBlockScope ? (
<Text type="warning">
阻塞作用域:
{detail.task.bindingDecision.rebindBlockScope === 'account'
? '虎牙账号'
: detail.task.bindingDecision.rebindBlockScope === 'target_role'
? '目标游戏角色'
: '平台其他原因'}
</Text>
) : null}
</Space>
</Descriptions.Item>
<Descriptions.Item label="客服">
{detail.task.assignedAdminName || '未领取'}
</Descriptions.Item>
<Descriptions.Item label="更新时间">
{formatAdminDateTime(detail.task.updatedAt)}
</Descriptions.Item>
</Descriptions>
{taskNeedsCustomerReauth(detail.task) ? (
<Alert
type="warning"
showIcon
message="客户登录状态需要更新"
description="平台 CK 已失效或任务登录失败。重新发送后,客户需要重新打开链接完成登录。"
/>
) : null}
{detail.task.lastError ? (
<Card size="small" title="最近错误">
<Text type="danger">{detail.task.lastError}</Text>
</Card>
) : null}
<Card size="small" title="操作">
<Space wrap>
{taskNeedsCustomerReauth(detail.task) ? (
<Button
type="primary"
icon={<SendOutlined />}
loading={reauthMutation.isPending}
onClick={() => confirmReauth(detail.task)}
>
重新发送授权
</Button>
) : null}
<Button icon={<CopyOutlined />} onClick={() => void copyCustomerLink(detail.task)}>
复制客户链接
</Button>
<Button
icon={<ReloadOutlined />}
loading={syncMutation.isPending}
onClick={() => syncMutation.mutate(detail.task.id)}
>
刷新客户状态
</Button>
<Button
icon={<KeyOutlined />}
disabled={!detail.task.credentialReady}
loading={credentialExportMutation.isPending}
onClick={() => confirmCopyCredential(detail.task)}
>
复制 CK
</Button>
<Button
icon={<ChromeOutlined />}
disabled={!canInjectSemiAutoBrowser(detail.task)}
loading={injectionMutation.isPending}
onClick={() => startInjection(detail.task)}
>
注入浏览器
</Button>
</Space>
</Card>
<Card size="small" title="时间线">
<Timeline
items={(detail.events || []).map((event) => ({
color: event.eventType.includes('failed') ? 'red' : 'blue',
children: (
<Space direction="vertical" size={2}>
<Text strong>{event.eventType}</Text>
<Text type="secondary">
{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>
),
}))}
/>
</Card>
</Space>
) : (
<Text type="secondary">暂无任务详情</Text>
)}
</Drawer>
<SemiAutoTaskHistoryDrawer
open={Boolean(historyTaskId)}
taskId={historyTaskId}
onClose={() => setHistoryTaskId(null)}
/>
<Modal
open={Boolean(completeTask)}
title="确认完成半自动履约"
okText="确认完成"
cancelText="取消"
confirmLoading={completeMutation.isPending}
onCancel={() => {
setCompleteTask(null)
setCompleteFiles([])
completeForm.resetFields()
}}
onOk={() => {
void completeForm.validateFields().then((values) => completeMutation.mutate(values))
}}
>
<Form<CompleteFormValues> form={completeForm} layout="vertical">
<Form.Item name="externalOrderNo" label="外部订单号 / 流水号(可选)">
<Input maxLength={200} />
</Form.Item>
<Form.Item name="note" label="备注(可选)">
<Input.TextArea rows={3} maxLength={1000} showCount />
</Form.Item>
<Form.Item
name="costYuan"
label="本次实际成本(元,可选)"
extra="成本不固定的 SKU 可在这里填写;固定成本不需要填写。"
>
<InputNumber min={0} precision={2} style={{ width: '100%' }} />
</Form.Item>
<Form.Item label="完成截图(可选)">
<ImageUpload
value={completeFiles}
onChange={setCompleteFiles}
scene="semi-auto-evidence"
scope="admin"
maxCount={6}
showPasteHint
captureGlobalPaste
/>
</Form.Item>
</Form>
</Modal>
</section>
)
}
function firstTargetUrl(task: SemiAutoTask) {
const targets = Array.isArray(task.semiAutoConfig?.browserTargets)
? task.semiAutoConfig.browserTargets
: []
return String(targets.find((item) => item?.url)?.url || '')
}
function taskNeedsCustomerReauth(task: SemiAutoTask) {
if (task.executionStatus === 'completed' || task.executionStatus === 'cancelled') return false
return (
task.credentialStatus === 'invalid' ||
task.credentialStatus === 'error' ||
task.executionStatus === 'failed' ||
task.loginStatus === 'failed' ||
task.loginStatus === 'expired'
)
}