重构(半自动履约): 统一虎牙/微博状态写入、CK 直取与履约分类(迁移190)

迁移 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 中指向不存在文件的失效链接。
This commit is contained in:
yml
2026-11-30 23:23:07 +08:00
parent 133705e986
commit eaf6296430
48 changed files with 3522 additions and 1482 deletions
@@ -21,6 +21,7 @@ import {
Modal,
Select,
Space,
Tabs,
Tag,
Timeline,
Typography,
@@ -28,6 +29,7 @@ import {
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'
@@ -37,19 +39,38 @@ import {
cancelAdminSemiAutoTask,
claimAdminSemiAutoTask,
completeAdminSemiAutoTask,
createAdminSemiAutoBrowserSession,
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 { resolvePostInjectionUrl } from '@/utils/semi-auto-injection'
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
@@ -118,20 +139,21 @@ type CompleteFormValues = {
costYuan?: number
}
const INJECTION_FOLLOW_UP_TIMEOUT_MS = 30_000
const INJECTION_RESULT_TIMEOUT_MS = 30_000
/** 一次在途注入:只接受 request_id 与它匹配的扩展回执。 */
type PendingInjection = {
requestId: string
taskId: number
platform: SemiAutoTask['platform']
popup: Window | null
timeoutId: number
}
export default function AdminSemiAutoTasksPage() {
const { message, modal } = App.useApp()
const queryClient = useQueryClient()
const [searchParams, setSearchParams] = useSearchParams()
const [keyword, setKeyword] = useState('')
const [platform, setPlatform] = useState('')
const [categoryFilter, setCategoryFilter] = useState<SemiAutoCategoryFilter>('all')
const [status, setStatus] = useState('')
const [page, setPage] = useState(1)
const [pageSize, setPageSize] = useState(20)
@@ -142,15 +164,12 @@ export default function AdminSemiAutoTasksPage() {
const [completeForm] = Form.useForm<CompleteFormValues>()
const pendingInjectionRef = useRef<PendingInjection | null>(null)
// tab 即平台:URL 上没有 tab 或值非法时落到虎牙,刷新/分享链接后仍是同一个列表。
const tab = resolveSemiAutoPlatformTab(searchParams.get('tab'))
const params = useMemo(
() => ({
page,
pageSize,
keyword: keyword.trim() || undefined,
platform: platform || undefined,
status: status || undefined,
}),
[keyword, page, pageSize, platform, status],
() => buildSemiAutoTaskListParams({ tab, categoryFilter, keyword, status, page, pageSize }),
[tab, categoryFilter, keyword, status, page, pageSize],
)
const listQuery = useQuery({
@@ -174,77 +193,39 @@ export default function AdminSemiAutoTasksPage() {
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
// 扩展回执是页面级广播:只消费 request_id 与本次注入匹配的那一条。
const result = matchSemiAutoInjectionResult(
(event as CustomEvent<unknown>).detail,
pending.requestId,
)
if (!result) return
window.clearTimeout(pending.timeoutId)
pendingInjectionRef.current = null
if (pending.popup && !pending.popup.closed) pending.popup.close()
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('huya-exchange-result', handleResult)
return () => window.removeEventListener('huya-exchange-result', handleResult)
}, [message, modal])
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)
if (pending.popup && !pending.popup.closed) pending.popup.close()
pendingInjectionRef.current = null
}
}, [])
@@ -271,69 +252,9 @@ export default function AdminSemiAutoTasksPage() {
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) => {
@@ -352,6 +273,64 @@ export default function AdminSemiAutoTasksPage() {
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) => {
@@ -408,6 +387,18 @@ export default function AdminSemiAutoTasksPage() {
])
}
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) {
@@ -498,6 +489,14 @@ export default function AdminSemiAutoTasksPage() {
</Space>
),
},
{
title: '分类',
dataIndex: 'semiAutoCategory',
width: 100,
render: (value: string) => (
<Tag color={value ? 'blue' : 'default'}>{semiAutoCategoryLabel(value)}</Tag>
),
},
{
title: '客户登录',
key: 'login',
@@ -657,12 +656,8 @@ export default function AdminSemiAutoTasksPage() {
},
]
return (
<section className="page-stack">
<PageHeader
title="半自动履约"
description="人工客服渠道下的平台账号授权、扫码绑定和浏览器辅助履约。"
/>
function renderTaskPanel() {
return (
<Card size="small">
<Space wrap style={{ marginBottom: 16 }}>
<Input.Search
@@ -676,16 +671,17 @@ export default function AdminSemiAutoTasksPage() {
style={{ width: 280 }}
/>
<Select
allowClear
placeholder="全部平台"
value={platform || undefined}
value={categoryFilter}
onChange={(value) => {
setPlatform(value || '')
setCategoryFilter(value)
setPage(1)
}}
options={[
{ value: 'huya', label: '虎牙' },
{ value: 'weibo', label: '微博' },
{ value: 'all', label: '全部分类' },
...SEMI_AUTO_CATEGORY_KEYS.map((key) => ({
value: key,
label: SEMI_AUTO_CATEGORY_LABELS[key],
})),
]}
style={{ width: 130 }}
/>
@@ -716,7 +712,7 @@ export default function AdminSemiAutoTasksPage() {
loading={listQuery.isLoading}
columns={columns}
dataSource={list}
scroll={{ x: 1400 }}
scroll={{ x: 1500 }}
pagination={{
current: pagination?.page || page,
pageSize: pagination?.pageSize || pageSize,
@@ -729,6 +725,25 @@ export default function AdminSemiAutoTasksPage() {
}}
/>
</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)}
@@ -747,6 +762,11 @@ export default function AdminSemiAutoTasksPage() {
<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'
@@ -1033,11 +1053,14 @@ export default function AdminSemiAutoTasksPage() {
)
}
function firstTargetUrl(task: SemiAutoTask) {
function resolveInjectionTargetUrl(task: SemiAutoTask) {
// 优先用人工 SKU 里配的 browserTargets,再用平台默认目标页;
// 这个 URL 只是 `target_url`,写入 Cookie 后由扩展负责打开。
const targets = Array.isArray(task.semiAutoConfig?.browserTargets)
? task.semiAutoConfig.browserTargets
: []
return String(targets.find((item) => item?.url)?.url || '')
const configured = String(targets.find((item) => item?.url)?.url || '')
return configured || resolvePostInjectionUrl(task.platform)
}
function taskNeedsCustomerReauth(task: SemiAutoTask) {