迁移 190 - 新增 SKU 级履约分类:manual_fulfillment_configs.semi_auto_category 为唯一真源 (''/direct_exchange/presale + CHECK),semi_auto_tasks.semi_auto_category 为物化快照, 配置改动不回写历史任务;补 (platform, semi_auto_category, created_at, id) 列表索引, 并按配置真源回填一次存量空快照。 状态写入收敛 - 26 处 UPDATE semi_auto_tasks 统一到唯一写入口 convergeSemiAutoTaskState: 行锁 + 状态转换规则 + 单条 UPDATE + 事件,事件只写本次真正变更的状态组。 - 新增 task-state-rules 纯函数与单测;终态 completed/cancelled 不再被业务状态改写。 - 热路径默认不回读带 join 的完整行,避免 2 秒轮询重复重读。 CK 生命周期 - 删除一次性注入票据与票据 TTL:移除 /semi-auto/injections 路由、两个 Connector 与 Mock 的票据实现;browser-session 改为后台鉴权后直接下发账号级 CK, 并补平台一致性与账号 UID 一致性校验。 - 登录成功但 CK 导出失败不再谎报已授权:落 failed + 原因,保留会话可重试; 微博短信登录与扫码路径行为对齐。 - 凭证 invalid 不再是永久黑名单:恢复前实时验证、成功回写 valid、失效重试按 60 秒节流; 微博恢复补任务级 UID 比对。 扩展与前端 - live-hub 的 huya-exchange-helper 迁入 apps/extensions/semi-auto-exchange-helper: 支持虎牙与微博域、CustomEvent 注入协议、--env-file 读取后台域名构建、 平台原始过期时间优先、只做 Cookie 注入与打开目标页(兑换人工完成)。 - 半自动履约页改为虎牙/微博 Tab + 分类筛选;人工 SKU 配置新增「履约分类」; 注入链路改为真实回执,扩展缺失时明确提示并支持复制 CK 兜底。 文档 - 权威文档同步:票据与 TTL 删除、CK 直取下发、扩展单一归属、分类真源与快照、 唯一写入口、迁移 190 记录。 - 新增《虎牙微博半自动履约现状-2026-11-30》现状盘点(重构前基线); 删除 docs/README.md 中指向不存在文件的失效链接。
1076 lines
39 KiB
TypeScript
1076 lines
39 KiB
TypeScript
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,
|
||
Tabs,
|
||
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 { useSearchParams } from 'react-router'
|
||
|
||
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,
|
||
createSemiAutoBrowserSession,
|
||
exportAdminSemiAutoCredential,
|
||
fetchAdminSemiAutoTask,
|
||
fetchAdminSemiAutoTasks,
|
||
requestAdminSemiAutoCustomerReauth,
|
||
syncAdminSemiAutoTask,
|
||
} from '@/services/admin/semi-auto'
|
||
import {
|
||
SEMI_AUTO_CATEGORY_KEYS,
|
||
SEMI_AUTO_CATEGORY_LABELS,
|
||
semiAutoCategoryLabel,
|
||
} from '@/types/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 { formatHuyaBindingDecisionMessage } from '@/utils/semi-auto-binding-decision'
|
||
import {
|
||
buildSemiAutoInjectionKit,
|
||
dispatchSemiAutoInjection,
|
||
isSemiAutoExchangeHelperReady,
|
||
matchSemiAutoInjectionResult,
|
||
resolvePostInjectionUrl,
|
||
SEMI_AUTO_RESULT_EVENT,
|
||
} from '@/utils/semi-auto-injection'
|
||
import {
|
||
buildSemiAutoTaskListParams,
|
||
isSemiAutoPlatformTab,
|
||
resolveSemiAutoPlatformTab,
|
||
SEMI_AUTO_PLATFORM_TABS,
|
||
type SemiAutoCategoryFilter,
|
||
} from '@/utils/semi-auto-task-filters'
|
||
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_RESULT_TIMEOUT_MS = 30_000
|
||
|
||
/** 一次在途注入:只接受 request_id 与它匹配的扩展回执。 */
|
||
type PendingInjection = {
|
||
requestId: string
|
||
taskId: number
|
||
timeoutId: number
|
||
}
|
||
|
||
export default function AdminSemiAutoTasksPage() {
|
||
const { message, modal } = App.useApp()
|
||
const queryClient = useQueryClient()
|
||
const [searchParams, setSearchParams] = useSearchParams()
|
||
const [keyword, setKeyword] = useState('')
|
||
const [categoryFilter, setCategoryFilter] = useState<SemiAutoCategoryFilter>('all')
|
||
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)
|
||
|
||
// tab 即平台:URL 上没有 tab 或值非法时落到虎牙,刷新/分享链接后仍是同一个列表。
|
||
const tab = resolveSemiAutoPlatformTab(searchParams.get('tab'))
|
||
|
||
const params = useMemo(
|
||
() => buildSemiAutoTaskListParams({ tab, categoryFilter, keyword, status, page, pageSize }),
|
||
[tab, categoryFilter, keyword, status, page, pageSize],
|
||
)
|
||
|
||
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 pending = pendingInjectionRef.current
|
||
if (!pending) return
|
||
// 扩展回执是页面级广播:只消费 request_id 与本次注入匹配的那一条。
|
||
const result = matchSemiAutoInjectionResult(
|
||
(event as CustomEvent<unknown>).detail,
|
||
pending.requestId,
|
||
)
|
||
if (!result) return
|
||
window.clearTimeout(pending.timeoutId)
|
||
pendingInjectionRef.current = null
|
||
if (result.ok) {
|
||
message.success(`已写入 ${result.written} 个 Cookie(扩展已打开平台页面)`)
|
||
} else {
|
||
message.error(
|
||
result.error ||
|
||
(result.written > 0
|
||
? `只写入 ${result.written} 个 Cookie,${result.failed} 个失败,请重新注入`
|
||
: '浏览器登录态写入失败,请确认「半自动兑换助手」可用后重试'),
|
||
)
|
||
}
|
||
void queryClient.invalidateQueries({ queryKey: ['admin-semi-auto-tasks'] })
|
||
void queryClient.invalidateQueries({ queryKey: ['admin-semi-auto-task'] })
|
||
}
|
||
window.addEventListener(SEMI_AUTO_RESULT_EVENT, handleResult)
|
||
return () => window.removeEventListener(SEMI_AUTO_RESULT_EVENT, handleResult)
|
||
}, [message, queryClient])
|
||
|
||
// 页面卸载时清掉在途注入的定时器,避免已卸载页面继续弹提示。
|
||
useEffect(() => {
|
||
return () => {
|
||
const pending = pendingInjectionRef.current
|
||
if (!pending) return
|
||
window.clearTimeout(pending.timeoutId)
|
||
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)
|
||
pendingInjectionRef.current = null
|
||
}
|
||
|
||
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 失败'),
|
||
})
|
||
|
||
/**
|
||
* 注入流程:取 CK → 组装材料包 → 派发 CustomEvent → 等扩展回执。
|
||
* 前端不再签发/消费票据,也不自己开关标签页(写入 Cookie 并打开目标页都是扩展的职责)。
|
||
*/
|
||
const injectionMutation = useMutation({
|
||
mutationFn: (task: SemiAutoTask) =>
|
||
createSemiAutoBrowserSession(task.id, resolveInjectionTargetUrl(task)),
|
||
onSuccess: (response, task) => {
|
||
const session = response.data
|
||
const cookieCount = Array.isArray(session?.cookies) ? session.cookies.length : 0
|
||
if (!session || cookieCount === 0) {
|
||
cancelPendingInjection()
|
||
message.error('账号 CK 不可用,请客户重新登录后再注入浏览器')
|
||
return
|
||
}
|
||
cancelPendingInjection()
|
||
const kit = buildSemiAutoInjectionKit(session)
|
||
const timeoutId = window.setTimeout(() => {
|
||
const pending = pendingInjectionRef.current
|
||
if (!pending || pending.requestId !== kit.request_id) return
|
||
pendingInjectionRef.current = null
|
||
message.warning('未收到「半自动兑换助手」回执,请确认扩展已启用后重试')
|
||
}, INJECTION_RESULT_TIMEOUT_MS)
|
||
pendingInjectionRef.current = { requestId: kit.request_id, taskId: task.id, timeoutId }
|
||
if (!dispatchSemiAutoInjection(kit)) {
|
||
cancelPendingInjection()
|
||
message.error('注入材料派发失败,请刷新页面后重试')
|
||
return
|
||
}
|
||
message.info(`正在向浏览器写入 ${cookieCount} 个 Cookie,请稍候`)
|
||
void refreshAll()
|
||
},
|
||
onError: (error) => {
|
||
cancelPendingInjection()
|
||
message.error(error instanceof Error ? error.message : '获取浏览器登录态失败')
|
||
},
|
||
})
|
||
|
||
function startInjection(task: SemiAutoTask) {
|
||
if (pendingInjectionRef.current) {
|
||
message.warning('上一次注入尚未完成,请稍候')
|
||
return
|
||
}
|
||
// 扩展内容脚本会在白名单页面打标记;没有标记时直接提示 + 提供复制 CK 兜底,不静默失败。
|
||
if (!isSemiAutoExchangeHelperReady(document.documentElement?.dataset)) {
|
||
modal.warning({
|
||
title: '未检测到「半自动兑换助手」扩展',
|
||
content:
|
||
'请先在 Chrome / Edge 安装并启用「半自动兑换助手」,然后刷新本页再注入;也可以直接复制账号 CK 手工兑换。',
|
||
okText: '复制 CK',
|
||
cancelText: '我知道了',
|
||
onOk: () => credentialExportMutation.mutateAsync(task.id),
|
||
})
|
||
return
|
||
}
|
||
injectionMutation.mutate(task)
|
||
}
|
||
|
||
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(),
|
||
])
|
||
}
|
||
|
||
function changeTab(nextTab: string) {
|
||
if (!isSemiAutoPlatformTab(nextTab) || nextTab === tab) return
|
||
setPage(1)
|
||
setSearchParams(
|
||
(current) => {
|
||
current.set('tab', nextTab)
|
||
return current
|
||
},
|
||
{ replace: true },
|
||
)
|
||
}
|
||
|
||
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: '分类',
|
||
dataIndex: 'semiAutoCategory',
|
||
width: 100,
|
||
render: (value: string) => (
|
||
<Tag color={value ? 'blue' : 'default'}>{semiAutoCategoryLabel(value)}</Tag>
|
||
),
|
||
},
|
||
{
|
||
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 ? (
|
||
<Text type="secondary">{`当前角色:${task.bindGameRole}`}</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>
|
||
),
|
||
},
|
||
]
|
||
|
||
function renderTaskPanel() {
|
||
return (
|
||
<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
|
||
value={categoryFilter}
|
||
onChange={(value) => {
|
||
setCategoryFilter(value)
|
||
setPage(1)
|
||
}}
|
||
options={[
|
||
{ value: 'all', label: '全部分类' },
|
||
...SEMI_AUTO_CATEGORY_KEYS.map((key) => ({
|
||
value: key,
|
||
label: SEMI_AUTO_CATEGORY_LABELS[key],
|
||
})),
|
||
]}
|
||
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: 1500 }}
|
||
pagination={{
|
||
current: pagination?.page || page,
|
||
pageSize: pagination?.pageSize || pageSize,
|
||
total: pagination?.total || 0,
|
||
showSizeChanger: true,
|
||
onChange: (nextPage, nextPageSize) => {
|
||
setPage(nextPage)
|
||
setPageSize(nextPageSize)
|
||
},
|
||
}}
|
||
/>
|
||
</Card>
|
||
)
|
||
}
|
||
|
||
return (
|
||
<section className="page-stack">
|
||
<PageHeader
|
||
title="半自动履约"
|
||
description="人工客服渠道下的平台账号授权、扫码绑定和浏览器辅助履约。"
|
||
/>
|
||
<Tabs
|
||
activeKey={tab}
|
||
onChange={changeTab}
|
||
items={SEMI_AUTO_PLATFORM_TABS.map((platformKey) => ({
|
||
key: platformKey,
|
||
label: PLATFORM_LABELS[platformKey] || platformKey,
|
||
// 只渲染当前 tab:两个平台同时挂在 DOM 上会重复拉一次列表。
|
||
children: tab === platformKey ? renderTaskPanel() : null,
|
||
}))}
|
||
/>
|
||
|
||
<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="履约分类">
|
||
<Tag color={detail.task.semiAutoCategory ? 'blue' : 'default'}>
|
||
{semiAutoCategoryLabel(detail.task.semiAutoCategory)}
|
||
</Tag>
|
||
</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>
|
||
{detail.task.platformGameRoleUid ? (
|
||
<Descriptions.Item label="平台角色 UID">
|
||
{detail.task.platformGameRoleUid}
|
||
</Descriptions.Item>
|
||
) : null}
|
||
{detail.task.pendingPlatformGameRoleUid ? (
|
||
<Descriptions.Item label="待确认角色 UID">
|
||
{detail.task.pendingPlatformGameRoleUid}
|
||
</Descriptions.Item>
|
||
) : null}
|
||
<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">
|
||
{formatHuyaBindingDecisionMessage(detail.task.bindingDecision) || '-'}
|
||
</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 resolveInjectionTargetUrl(task: SemiAutoTask) {
|
||
// 优先用人工 SKU 里配的 browserTargets,再用平台默认目标页;
|
||
// 这个 URL 只是 `target_url`,写入 Cookie 后由扩展负责打开。
|
||
const targets = Array.isArray(task.semiAutoConfig?.browserTargets)
|
||
? task.semiAutoConfig.browserTargets
|
||
: []
|
||
const configured = String(targets.find((item) => item?.url)?.url || '')
|
||
return configured || resolvePostInjectionUrl(task.platform)
|
||
}
|
||
|
||
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'
|
||
)
|
||
}
|