feat(semi-auto): 客户链接按平台严格绑定,注入后统一由前端打开指定页

This commit is contained in:
2026-11-17 17:27:19 +08:00
parent 7bd5b8bade
commit 77e1c69a2b
13 changed files with 459 additions and 56 deletions
@@ -503,7 +503,7 @@ export async function createSemiAutoMock(
skuKey, skuKey,
connectorMode, connectorMode,
connectorConfigured, connectorConfigured,
customerPath: `/c/${encodeURIComponent(orderNo)}`, customerPath: buildMockCustomerPath(platform, orderNo),
adminPath: `/admin/semi-auto-tasks?keyword=${encodeURIComponent(orderNo)}`, adminPath: `/admin/semi-auto-tasks?keyword=${encodeURIComponent(orderNo)}`,
tips: tips:
platform === 'weibo' platform === 'weibo'
@@ -781,7 +781,7 @@ export async function createSemiAutoIntegrationMock(
connectorMode, connectorMode,
connectorConfigured, connectorConfigured,
mappingId, mappingId,
customerPath: `/c/${encodeURIComponent(orderNo)}`, customerPath: buildMockCustomerPath(platform, orderNo),
adminPath: `/admin/semi-auto-tasks?keyword=${encodeURIComponent(orderNo)}`, adminPath: `/admin/semi-auto-tasks?keyword=${encodeURIComponent(orderNo)}`,
tips: [ tips: [
'订单通过正式 upsertOrderFromSource 入库。', '订单通过正式 upsertOrderFromSource 入库。',
@@ -802,6 +802,10 @@ function normalizeMockSemiAutoPlatform(value: unknown): 'huya' | 'weibo' {
: 'huya' : 'huya'
} }
function buildMockCustomerPath(platform: 'huya' | 'weibo', orderNo: string): string {
return `/${platform === 'weibo' ? 'd' : 'c'}/${encodeURIComponent(orderNo)}`
}
function normalizeMockSemiAutoConnectorMode(value: unknown): SemiAutoConnectorMode { function normalizeMockSemiAutoConnectorMode(value: unknown): SemiAutoConnectorMode {
const mode = String(value || '') const mode = String(value || '')
.trim() .trim()
@@ -0,0 +1,34 @@
import assert from 'node:assert/strict'
import { describe, it } from 'node:test'
import { buildExtensionInjectionPayload } from './semi-auto-task-service.js'
const payload = {
platform: 'weibo' as const,
targetUrl: 'https://weibo.com/',
expiresAt: '2026-11-17T00:00:00.000Z',
cookies: [
{
name: 'SUB',
value: 'weibo-sub',
domain: '.weibo.com',
path: '/',
secure: true,
},
],
}
describe('下发给扩展的注入载荷', () => {
it('清空 targetUrl,避免扩展额外打开目标页', () => {
const result = buildExtensionInjectionPayload(payload)
assert.equal(result.targetUrl, '')
assert.equal(result.platform, 'weibo')
assert.equal(result.expiresAt, payload.expiresAt)
assert.deepEqual(result.cookies, payload.cookies)
})
it('不修改票据内的原始载荷(Cookie 序列化仍依赖原 targetUrl)', () => {
buildExtensionInjectionPayload(payload)
assert.equal(payload.targetUrl, 'https://weibo.com/')
})
})
@@ -32,6 +32,7 @@ import {
consumeHuyaBrowserTicket, consumeHuyaBrowserTicket,
verifyHuyaSmsChallenge, verifyHuyaSmsChallenge,
type ConnectorBindingSession, type ConnectorBindingSession,
type ConnectorInjectionPayload,
type SemiAutoConnectorMode, type SemiAutoConnectorMode,
type ConnectorLoginSession, type ConnectorLoginSession,
} from './huya-connector-client.js' } from './huya-connector-client.js'
@@ -412,7 +413,7 @@ function assertHuyaTask(task: TaskRow) {
} }
/** /**
* 半自动订单没有工单,资料页 /c/<订单号> 是唯一入口。 * 半自动订单没有工单,资料页 /c/<订单号>(虎牙)或 /d/<订单号>(微博)是唯一入口。
* 未提交区服 / 游戏编号 / 角色名时,不允许开始登录,避免后续无法比对角色。 * 未提交区服 / 游戏编号 / 角色名时,不允许开始登录,避免后续无法比对角色。
*/ */
function assertCustomerProfileReady(task: TaskRow) { function assertCustomerProfileReady(task: TaskRow) {
@@ -713,7 +714,7 @@ export async function ensureSemiAutoTasksForOrderItems(input: unknown[]) {
/** /**
* 后台列表读取前的幂等回填。 * 后台列表读取前的幂等回填。
* *
* 客户不先打开 `/c/订单号` 时,任务也必须进入客服工作台;后备查询只插入缺失任务, * 客户不先打开 `/c/订单号` 或 `/d/订单号` 时,任务也必须进入客服工作台;后备查询只插入缺失任务,
* 不修改已有任务状态,也不会重复写事件。 * 不修改已有任务状态,也不会重复写事件。
*/ */
export async function backfillSemiAutoTasks() { export async function backfillSemiAutoTasks() {
@@ -794,7 +795,7 @@ export function normalizeCustomerProfile(input: CustomerProfileInput = {}) {
} }
/** /**
* 半自动订单没有 work_orders,客户资料只能在授权页 /c/<订单号> 收集。 * 半自动订单没有 work_orders,客户资料只能在授权页 /c/<订单号>(虎牙)或 /d/<订单号>(微博)收集。
* 保存后立即参与“客户填写角色 vs 平台识别角色”的比对。 * 保存后立即参与“客户填写角色 vs 平台识别角色”的比对。
*/ */
export async function savePublicTaskProfile( export async function savePublicTaskProfile(
@@ -2200,6 +2201,17 @@ export async function createAdminBrowserSession(
return ticket return ticket
} }
/**
* 票据内的 targetUrl 只服务于创建阶段的 Cookie 序列化与审计;
* 下发给扩展时清空,指定平台页统一由前端占位页在注入成功后打开,
* 这样扩展只写 Cookie,不会再额外打开一个目标页标签。
*/
export function buildExtensionInjectionPayload(
payload: ConnectorInjectionPayload,
): ConnectorInjectionPayload {
return { ...payload, targetUrl: '' }
}
export async function consumeSemiAutoInjectionTicket(ticketInput: unknown) { export async function consumeSemiAutoInjectionTicket(ticketInput: unknown) {
const ticket = String(ticketInput || '').trim() const ticket = String(ticketInput || '').trim()
if (!ticket) { if (!ticket) {
@@ -2208,10 +2220,10 @@ export async function consumeSemiAutoInjectionTicket(ticketInput: unknown) {
errorCode: 'semi_auto_injection_ticket_invalid', errorCode: 'semi_auto_injection_ticket_invalid',
}) })
} }
if (ticket.startsWith(WEIBO_TICKET_PREFIX)) { const payload = ticket.startsWith(WEIBO_TICKET_PREFIX)
return consumeWeiboBrowserTicket(ticket) ? await consumeWeiboBrowserTicket(ticket)
} : await consumeHuyaBrowserTicket(ticket)
return consumeHuyaBrowserTicket(ticket) return buildExtensionInjectionPayload(payload)
} }
async function resolveCompletionEvidence( async function resolveCompletionEvidence(
@@ -91,7 +91,7 @@ test(
[fulfillmentId, configId], [fulfillmentId, configId],
) )
// 客服工作台先打开时也必须看到任务,不能依赖客户先访问 `/c/订单号`。 // 客服工作台先打开时也必须看到任务,不能依赖客户先访问 `/c/订单号` 或 `/d/订单号`。
const adminList = await listAdminSemiAutoTasks({ keyword: orderNo }) const adminList = await listAdminSemiAutoTasks({ keyword: orderNo })
assert.equal(adminList.pagination.total, 1) assert.equal(adminList.pagination.total, 1)
assert.equal(adminList.items[0]?.orderNo, orderNo) assert.equal(adminList.items[0]?.orderNo, orderNo)
+12 -2
View File
@@ -169,12 +169,22 @@ function OrderServiceApplication() {
function CustomerFulfillmentApplication() { function CustomerFulfillmentApplication() {
useClearStrayHash() useClearStrayHash()
// 非标准子路径也按首段路径绑定平台,避免 /c/.../extra 这类地址绕过严格绑定。
const prefix = window.location.pathname.split('/').filter(Boolean)[0]
const wildcardPlatform = prefix === 'c' ? 'huya' : prefix === 'd' ? 'weibo' : undefined
return ( return (
<BrowserRouter> <BrowserRouter>
<Suspense fallback={<RouteLoading />}> <Suspense fallback={<RouteLoading />}>
<Routes> <Routes>
<Route path="/c/:orderNo" element={<CustomerFulfillmentPage />} /> <Route path="/c/:orderNo" element={<CustomerFulfillmentPage expectedPlatform="huya" />} />
<Route path="*" element={<CustomerFulfillmentPage />} /> <Route
path="/d/:orderNo"
element={<CustomerFulfillmentPage expectedPlatform="weibo" />}
/>
<Route
path="*"
element={<CustomerFulfillmentPage expectedPlatform={wildcardPlatform} />}
/>
</Routes> </Routes>
</Suspense> </Suspense>
</BrowserRouter> </BrowserRouter>
@@ -33,6 +33,7 @@ import {
type DevMockSemiAutoResult, type DevMockSemiAutoResult,
type DevSemiAutoIntegrationResult, type DevSemiAutoIntegrationResult,
} from '@/services/admin' } from '@/services/admin'
import { buildCustomerFulfillmentPath } from '@/utils/customer-fulfillment-link'
export default function AdminDevMockPage() { export default function AdminDevMockPage() {
const { message } = App.useApp() const { message } = App.useApp()
@@ -109,6 +110,14 @@ export default function AdminDevMockPage() {
}) })
const defaultOrderNo = useMemo(() => lastCreate?.orderNo || '', [lastCreate?.orderNo]) const defaultOrderNo = useMemo(() => lastCreate?.orderNo || '', [lastCreate?.orderNo])
// 页面展示按平台重新生成规范路径,避免历史 Mock 响应里的 customerPath 仍是 /c。
const semiAutoCustomerPath = lastSemiAuto
? buildCustomerFulfillmentPath(lastSemiAuto.orderNo, lastSemiAuto.semiAutoPlatform) ||
lastSemiAuto.customerPath
: ''
const semiAutoCustomerUrl = semiAutoCustomerPath
? `${window.location.origin}${semiAutoCustomerPath}`
: ''
if (statusQuery.isLoading) { if (statusQuery.isLoading) {
return ( return (
@@ -347,32 +356,22 @@ export default function AdminDevMockPage() {
<Col span={24}> <Col span={24}>
<Typography.Text type="secondary">客户履约入口</Typography.Text> <Typography.Text type="secondary">客户履约入口</Typography.Text>
<div> <div>
<Typography.Link <Typography.Link href={semiAutoCustomerUrl} target="_blank" rel="noreferrer">
href={`${window.location.origin}${lastSemiAuto.customerPath}`}
target="_blank"
rel="noreferrer"
>
<LinkOutlined /> {window.location.origin} <LinkOutlined /> {window.location.origin}
{lastSemiAuto.customerPath} {semiAutoCustomerPath}
</Typography.Link> </Typography.Link>
</div> </div>
<Space style={{ marginTop: 8 }} wrap> <Space style={{ marginTop: 8 }} wrap>
<Button <Button
icon={<CopyOutlined />} icon={<CopyOutlined />}
onClick={async () => { onClick={async () => {
await navigator.clipboard.writeText( await navigator.clipboard.writeText(semiAutoCustomerUrl)
`${window.location.origin}${lastSemiAuto.customerPath}`,
)
message.success('已复制客户履约链接') message.success('已复制客户履约链接')
}} }}
> >
复制客户链接 复制客户链接
</Button> </Button>
<Button <Button type="primary" href={semiAutoCustomerUrl} target="_blank">
type="primary"
href={`${window.location.origin}${lastSemiAuto.customerPath}`}
target="_blank"
>
打开客户页 打开客户页
</Button> </Button>
</Space> </Space>
@@ -27,7 +27,7 @@ import {
} from 'antd' } from 'antd'
import type { TableColumnsType } from 'antd' import type { TableColumnsType } from 'antd'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useEffect, useMemo, useState } from 'react' import { useEffect, useMemo, useRef, useState } from 'react'
import ImageUpload from '@/components/files/ImageUpload' import ImageUpload from '@/components/files/ImageUpload'
import PageHeader from '@/components/admin/PageHeader' import PageHeader from '@/components/admin/PageHeader'
@@ -47,6 +47,8 @@ import {
import type { SemiAutoTask } from '@/types/admin/semi-auto' import type { SemiAutoTask } from '@/types/admin/semi-auto'
import type { UploadedFile } from '@/types/worker-platform' import type { UploadedFile } from '@/types/worker-platform'
import { formatAdminDateTime } from '@/utils/admin-time' import { formatAdminDateTime } from '@/utils/admin-time'
import { buildCustomerFulfillmentPath } from '@/utils/customer-fulfillment-link'
import { resolvePostInjectionUrl } from '@/utils/semi-auto-injection'
const { Text } = Typography const { Text } = Typography
@@ -87,6 +89,15 @@ type CompleteFormValues = {
costYuan?: number 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() { export default function AdminSemiAutoTasksPage() {
const { message, modal } = App.useApp() const { message, modal } = App.useApp()
const queryClient = useQueryClient() const queryClient = useQueryClient()
@@ -100,6 +111,7 @@ export default function AdminSemiAutoTasksPage() {
const [completeTask, setCompleteTask] = useState<SemiAutoTask | null>(null) const [completeTask, setCompleteTask] = useState<SemiAutoTask | null>(null)
const [completeFiles, setCompleteFiles] = useState<UploadedFile[]>([]) const [completeFiles, setCompleteFiles] = useState<UploadedFile[]>([])
const [completeForm] = Form.useForm<CompleteFormValues>() const [completeForm] = Form.useForm<CompleteFormValues>()
const pendingInjectionRef = useRef<PendingInjection | null>(null)
const params = useMemo( const params = useMemo(
() => ({ () => ({
@@ -137,25 +149,78 @@ export default function AdminSemiAutoTasksPage() {
const handleResult = (event: Event) => { const handleResult = (event: Event) => {
const detail = (event as CustomEvent<string>).detail const detail = (event as CustomEvent<string>).detail
if (typeof detail !== 'string') return if (typeof detail !== 'string') return
let result: { ok?: boolean; written?: number; error?: string }
try { try {
const result = JSON.parse(detail) as { result = JSON.parse(detail) as { ok?: boolean; written?: number; error?: string }
ok?: boolean } catch {
written?: number return
error?: string
} }
if (!result || typeof result !== 'object') return if (!result || typeof result !== 'object') return
const pending = pendingInjectionRef.current
if (result.ok) { if (result.ok) {
message.success(`浏览器登录态已注入(${Number(result.written || 0)} 个 Cookie)`) message.success(`浏览器登录态已注入(${Number(result.written || 0)} 个 Cookie)`)
} else { if (!pending) return
message.error(result.error || '浏览器登录态注入失败') 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 { } 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) window.addEventListener('huya-exchange-result', handleResult)
return () => window.removeEventListener('huya-exchange-result', handleResult) return () => window.removeEventListener('huya-exchange-result', handleResult)
}, [message]) }, [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({ const syncMutation = useMutation({
mutationFn: (taskId: number) => syncAdminSemiAutoTask(taskId), mutationFn: (taskId: number) => syncAdminSemiAutoTask(taskId),
@@ -175,12 +240,33 @@ export default function AdminSemiAutoTasksPage() {
onError: (error) => message.error(error instanceof Error ? error.message : '领取失败'), 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({ const injectionMutation = useMutation({
mutationFn: (task: SemiAutoTask) => mutationFn: (task: SemiAutoTask) =>
createAdminSemiAutoBrowserSession(task.id, firstTargetUrl(task)), createAdminSemiAutoBrowserSession(task.id, firstTargetUrl(task)),
onSuccess: (response) => { onSuccess: (response) => {
const ticket = String(response.data?.ticket || '').trim() const ticket = String(response.data?.ticket || '').trim()
if (!ticket) { if (!ticket) {
cancelPendingInjection()
message.error('注入票据生成失败') message.error('注入票据生成失败')
return return
} }
@@ -188,10 +274,39 @@ export default function AdminSemiAutoTasksPage() {
message.info('正在注入浏览器登录态,请稍候') message.info('正在注入浏览器登录态,请稍候')
void refreshAll() void refreshAll()
}, },
onError: (error) => onError: (error) => {
message.error(error instanceof Error ? error.message : '打开浏览器登录态失败'), 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({ const credentialExportMutation = useMutation({
mutationFn: (taskId: number) => exportAdminSemiAutoCredential(taskId), mutationFn: (taskId: number) => exportAdminSemiAutoCredential(taskId),
onSuccess: (response) => { onSuccess: (response) => {
@@ -267,7 +382,12 @@ export default function AdminSemiAutoTasksPage() {
} }
async function copyCustomerLink(task: SemiAutoTask, successMessage = '客户授权链接已复制') { async function copyCustomerLink(task: SemiAutoTask, successMessage = '客户授权链接已复制') {
const url = `${window.location.origin}/c/${encodeURIComponent(task.orderNo)}` const path = buildCustomerFulfillmentPath(task.orderNo, task.platform)
if (!path) {
message.error('订单号为空,无法生成客户链接')
return false
}
const url = `${window.location.origin}${path}`
try { try {
await navigator.clipboard.writeText(url) await navigator.clipboard.writeText(url)
if (successMessage) message.success(successMessage) if (successMessage) message.success(successMessage)
@@ -451,7 +571,7 @@ export default function AdminSemiAutoTasksPage() {
icon={<ChromeOutlined />} icon={<ChromeOutlined />}
disabled={!taskCanUseCredential(task)} disabled={!taskCanUseCredential(task)}
loading={injectionMutation.isPending} loading={injectionMutation.isPending}
onClick={() => injectionMutation.mutate(task)} onClick={() => startInjection(task)}
> >
注入浏览器 注入浏览器
</Button> </Button>
@@ -720,7 +840,7 @@ export default function AdminSemiAutoTasksPage() {
icon={<ChromeOutlined />} icon={<ChromeOutlined />}
disabled={!taskCanUseCredential(detail.task)} disabled={!taskCanUseCredential(detail.task)}
loading={injectionMutation.isPending} loading={injectionMutation.isPending}
onClick={() => injectionMutation.mutate(detail.task)} onClick={() => startInjection(detail.task)}
> >
注入浏览器 注入浏览器
</Button> </Button>
@@ -658,7 +658,7 @@ export function ManualSkuConfigPanel() {
name="semiAutoEnabled" name="semiAutoEnabled"
label="启用半自动履约" label="启用半自动履约"
valuePropName="checked" valuePropName="checked"
extra="订单进入人工渠道后,客户可通过 /c/订单号 登录平台并完成绑定。" extra="订单进入人工渠道后,客户可通过专属链接登录平台并完成绑定(虎牙 /c/订单号,微博 /d/订单号)。"
> >
<Switch /> <Switch />
</Form.Item> </Form.Item>
@@ -8,7 +8,7 @@ import {
import { App, Alert, Button, Image, Input, Modal, Select, Space, Spin } from 'antd' import { App, Alert, Button, Image, Input, Modal, Select, Space, Spin } from 'antd'
import QRCode from 'qrcode' import QRCode from 'qrcode'
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react' import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
import { useParams } from 'react-router' import { useLocation, useNavigate, useParams } from 'react-router'
import { import {
confirmCustomerBinding, confirmCustomerBinding,
@@ -36,6 +36,11 @@ import type {
CustomerSemiAutoTask, CustomerSemiAutoTask,
} from '@/types/customer-fulfillment' } from '@/types/customer-fulfillment'
import { formatAdminDateTime } from '@/utils/admin-time' import { formatAdminDateTime } from '@/utils/admin-time'
import {
buildCustomerFulfillmentPath,
resolveCustomerPlatformRedirect,
type CustomerFulfillmentPlatform,
} from '@/utils/customer-fulfillment-link'
import { runWeiboYidunChallenge } from '@/utils/weibo-yidun' import { runWeiboYidunChallenge } from '@/utils/weibo-yidun'
import HuyaChallengeModal from './HuyaChallengeModal' import HuyaChallengeModal from './HuyaChallengeModal'
@@ -46,9 +51,15 @@ const SERVER_ZONE_OPTIONS = ['苹果Q区', '苹果V区', '安卓Q区', '安卓V
/** antd v6 语义化 classNames:让区服下拉弹层用页面深色样式 */ /** antd v6 语义化 classNames:让区服下拉弹层用页面深色样式 */
const SERVER_ZONE_SELECT_CLASS_NAMES = { popup: { root: 'customer-collect-dropdown' } } const SERVER_ZONE_SELECT_CLASS_NAMES = { popup: { root: 'customer-collect-dropdown' } }
export default function CustomerFulfillmentPage() { export default function CustomerFulfillmentPage({
expectedPlatform,
}: {
expectedPlatform?: CustomerFulfillmentPlatform
}) {
const { message, modal } = App.useApp() const { message, modal } = App.useApp()
const { orderNo: routeOrderNo } = useParams<{ orderNo?: string }>() const { orderNo: routeOrderNo } = useParams<{ orderNo?: string }>()
const navigate = useNavigate()
const { search, hash } = useLocation()
const orderNo = String(routeOrderNo || '').trim() const orderNo = String(routeOrderNo || '').trim()
const [loading, setLoading] = useState(true) const [loading, setLoading] = useState(true)
const [loadError, setLoadError] = useState('') const [loadError, setLoadError] = useState('')
@@ -79,6 +90,7 @@ export default function CustomerFulfillmentPage() {
const startingBindingRef = useRef(false) const startingBindingRef = useRef(false)
const hydratingBindingRef = useRef(false) const hydratingBindingRef = useRef(false)
const autoOpenedRoleRef = useRef('') const autoOpenedRoleRef = useRef('')
const redirectingRef = useRef(false)
// Connector 重启或会话被回收后,绑定/确认接口会返回 huya_native_session_not_found。 // Connector 重启或会话被回收后,绑定/确认接口会返回 huya_native_session_not_found。
const [bindingSessionExpired, setBindingSessionExpired] = useState(false) const [bindingSessionExpired, setBindingSessionExpired] = useState(false)
const [bindingLoadError, setBindingLoadError] = useState('') const [bindingLoadError, setBindingLoadError] = useState('')
@@ -100,11 +112,28 @@ export default function CustomerFulfillmentPage() {
try { try {
const response = await fetchCustomerFulfillment(orderNo) const response = await fetchCustomerFulfillment(orderNo)
const nextTasks = response.data || [] const nextTasks = response.data || []
setTasks(nextTasks) const redirectPlatform = resolveCustomerPlatformRedirect(expectedPlatform, nextTasks)
if (redirectPlatform) {
const targetPath = buildCustomerFulfillmentPath(orderNo, redirectPlatform)
if (targetPath && !redirectingRef.current) {
redirectingRef.current = true
void navigate(`${targetPath}${search}${hash}`, { replace: true })
}
return
}
const visibleTasks = expectedPlatform
? nextTasks.filter((task) => task.platform === expectedPlatform)
: nextTasks
if (expectedPlatform && nextTasks.length > 0 && visibleTasks.length === 0) {
setTasks([])
setLoadError('当前链接与订单平台不匹配,请使用对应平台的客户链接')
return
}
setTasks(visibleTasks)
setLoadError('') setLoadError('')
setSelectedTaskId((current) => { setSelectedTaskId((current) => {
if (nextTasks.some((task) => task.id === current)) return current if (visibleTasks.some((task) => task.id === current)) return current
return nextTasks[0]?.id || 0 return visibleTasks[0]?.id || 0
}) })
} catch (error) { } catch (error) {
if (!silent) { if (!silent) {
@@ -115,9 +144,14 @@ export default function CustomerFulfillmentPage() {
if (!silent) setLoading(false) if (!silent) setLoading(false)
} }
}, },
[orderNo], [expectedPlatform, hash, navigate, orderNo, search],
) )
// 订单号或平台路由变化后允许重新判定跳转,避免复用组件时上一次的标记卡住。
useEffect(() => {
redirectingRef.current = false
}, [expectedPlatform, orderNo])
useEffect(() => { useEffect(() => {
void load() void load()
}, [load]) }, [load])
@@ -1,6 +1,58 @@
/** 客户半自动履约入口:/c/:orderNo。 */ export type CustomerFulfillmentPlatform = 'huya' | 'weibo'
/** 客户半自动履约入口:虎牙 /c/:orderNo,微博 /d/:orderNo。 */
export function buildCustomerFulfillmentPath(orderNo: unknown, platform: unknown): string {
const normalizedOrderNo = String(orderNo || '').trim()
if (!normalizedOrderNo) return ''
const prefix =
String(platform || '')
.trim()
.toLowerCase() === 'weibo'
? 'd'
: 'c'
return `/${prefix}/${encodeURIComponent(normalizedOrderNo)}`
}
export function isCustomerFulfillmentPath(pathname: unknown): boolean { export function isCustomerFulfillmentPath(pathname: unknown): boolean {
const normalized = String(pathname || '').trim() const normalized = String(pathname || '').trim()
if (!normalized.startsWith('/')) return false if (!normalized.startsWith('/')) return false
return normalized.split(/[?#]/)[0].replace(/\/+$/, '').split('/').filter(Boolean)[0] === 'c' const first = normalized.split(/[?#]/)[0].replace(/\/+$/, '').split('/').filter(Boolean)[0]
return first === 'c' || first === 'd'
}
/**
* 严格绑定下的自动归一化:当前路径对应平台没有任务、但订单只有另一个平台任务时,
* 返回应跳转的平台;双平台订单返回 null(各路径只展示自己的任务),
* 无任务或平台未知也返回 null。
*/
export function resolveCustomerPlatformRedirect(
expectedPlatform: CustomerFulfillmentPlatform | null | undefined,
tasks: Array<{ platform?: string | null }>,
): CustomerFulfillmentPlatform | null {
if (expectedPlatform !== 'huya' && expectedPlatform !== 'weibo') return null
if (!Array.isArray(tasks) || tasks.length === 0) return null
if (
tasks.some(
(task) =>
String(task.platform || '')
.trim()
.toLowerCase() === expectedPlatform,
)
) {
return null
}
const platforms = new Set(
tasks
.map((task) =>
String(task.platform || '')
.trim()
.toLowerCase(),
)
.filter(
(platform): platform is CustomerFulfillmentPlatform =>
platform === 'huya' || platform === 'weibo',
),
)
if (platforms.size !== 1) return null
return [...platforms][0]
} }
@@ -0,0 +1,15 @@
import type { SemiAutoPlatform } from '@/types/admin/semi-auto'
/**
* 注入浏览器成功后自动打开的平台页面。
* 只在客户页/后台侧使用;扩展只负责写入 Cookie,指定平台页由前端占位页打开。
*/
export const POST_INJECTION_URLS: Record<SemiAutoPlatform, string> = {
huya: 'https://m-shop.huya.com/points.html?pagecode=heping_baodian_credit_center_page&sourceId=yellowcarlist&pid=1199650619883&anchorUid=1199650619883&roomid=30596253',
weibo: 'https://vipclub.e.weibo.com/game/homepage?F=bowen_tjg',
}
export function resolvePostInjectionUrl(platform: string | null | undefined): string {
if (platform === 'huya' || platform === 'weibo') return POST_INJECTION_URLS[platform]
return ''
}
@@ -1,17 +1,93 @@
import assert from 'node:assert/strict' import assert from 'node:assert/strict'
import { readFile } from 'node:fs/promises'
import test from 'node:test' import test from 'node:test'
import { isCustomerFulfillmentPath } from '../src/utils/customer-fulfillment-link.ts' import {
buildCustomerFulfillmentPath,
isCustomerFulfillmentPath,
resolveCustomerPlatformRedirect,
} from '../src/utils/customer-fulfillment-link.ts'
test('客户半自动履约入口:/c 命名空间整段命中', () => { test('客户半自动履约入口:/c 与 /d 命名空间整段命中', () => {
assert.equal(isCustomerFulfillmentPath('/c/263123'), true) assert.equal(isCustomerFulfillmentPath('/c/263123'), true)
assert.equal(isCustomerFulfillmentPath('/c'), true) assert.equal(isCustomerFulfillmentPath('/c'), true)
assert.equal(isCustomerFulfillmentPath('/c/a/b'), true) assert.equal(isCustomerFulfillmentPath('/c/a/b'), true)
assert.equal(isCustomerFulfillmentPath('/d/263123'), true)
assert.equal(isCustomerFulfillmentPath('/d'), true)
assert.equal(isCustomerFulfillmentPath('/d/a/b'), true)
assert.equal(isCustomerFulfillmentPath('/d/263123?from=chat'), true)
assert.equal(isCustomerFulfillmentPath('/d/263123#section'), true)
}) })
test('客户半自动履约入口不误伤相似前缀和其他路径', () => { test('客户半自动履约入口不误伤相似前缀和其他路径', () => {
assert.equal(isCustomerFulfillmentPath('/claim/x'), false) assert.equal(isCustomerFulfillmentPath('/claim/x'), false)
assert.equal(isCustomerFulfillmentPath('/customer/x'), false) assert.equal(isCustomerFulfillmentPath('/customer/x'), false)
assert.equal(isCustomerFulfillmentPath('/admin/c/1'), false) assert.equal(isCustomerFulfillmentPath('/admin/c/1'), false)
assert.equal(isCustomerFulfillmentPath('/admin/d/1'), false)
assert.equal(isCustomerFulfillmentPath('/dd/1'), false)
assert.equal(isCustomerFulfillmentPath('c/1'), false) assert.equal(isCustomerFulfillmentPath('c/1'), false)
assert.equal(isCustomerFulfillmentPath('d/1'), false)
})
test('按平台生成客户链接:虎牙 /c、微博 /d', () => {
assert.equal(
buildCustomerFulfillmentPath('INTSA1794902905684_360848', 'huya'),
'/c/INTSA1794902905684_360848',
)
assert.equal(
buildCustomerFulfillmentPath('INTSA1794902905684_360848', 'weibo'),
'/d/INTSA1794902905684_360848',
)
assert.equal(buildCustomerFulfillmentPath(' INTWB1 ', 'WEIBO'), '/d/INTWB1')
assert.equal(buildCustomerFulfillmentPath('a/b', 'weibo'), '/d/a%2Fb')
assert.equal(buildCustomerFulfillmentPath('', 'weibo'), '')
assert.equal(buildCustomerFulfillmentPath('x', 'unknown'), '/c/x')
})
test('严格绑定:路径平台不匹配时返回应跳转的平台', () => {
assert.equal(resolveCustomerPlatformRedirect('huya', [{ platform: 'weibo' }]), 'weibo')
assert.equal(resolveCustomerPlatformRedirect('weibo', [{ platform: 'huya' }]), 'huya')
assert.equal(resolveCustomerPlatformRedirect('huya', [{ platform: 'huya' }]), null)
assert.equal(resolveCustomerPlatformRedirect('weibo', [{ platform: 'weibo' }]), null)
assert.equal(
resolveCustomerPlatformRedirect('huya', [{ platform: 'huya' }, { platform: 'weibo' }]),
null,
)
assert.equal(
resolveCustomerPlatformRedirect('weibo', [{ platform: 'huya' }, { platform: 'weibo' }]),
null,
)
assert.equal(resolveCustomerPlatformRedirect('huya', []), null)
assert.equal(resolveCustomerPlatformRedirect(undefined, [{ platform: 'weibo' }]), null)
assert.equal(resolveCustomerPlatformRedirect('huya', [{ platform: 'unknown' }]), null)
assert.equal(
resolveCustomerPlatformRedirect('huya', [{ platform: 'weibo' }, { platform: 'unknown' }]),
'weibo',
)
})
test('客户页路由与严格绑定接线', async () => {
const app = await readFile(new URL('../src/App.tsx', import.meta.url), 'utf8')
const page = await readFile(
new URL('../src/pages/customer-fulfillment/CustomerFulfillmentPage.tsx', import.meta.url),
'utf8',
)
assert.match(app, /path="\/c\/:orderNo"/)
assert.match(app, /expectedPlatform="huya"/)
assert.match(app, /path="\/d\/:orderNo"/)
assert.match(app, /expectedPlatform="weibo"/)
assert.match(page, /resolveCustomerPlatformRedirect/)
assert.match(page, /buildCustomerFulfillmentPath/)
assert.match(page, /task\.platform === expectedPlatform/)
})
test('开发 Mock 页按平台重新生成客户路径', async () => {
const page = await readFile(
new URL('../src/pages/admin/AdminDevMockPage.tsx', import.meta.url),
'utf8',
)
assert.match(page, /buildCustomerFulfillmentPath/)
assert.match(page, /semiAutoCustomerPath/)
assert.match(page, /semiAutoCustomerUrl/)
}) })
@@ -0,0 +1,47 @@
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'
import { POST_INJECTION_URLS, resolvePostInjectionUrl } from '../src/utils/semi-auto-injection.ts'
const source = readFileSync(
join(dirname(fileURLToPath(import.meta.url)), '../src/pages/admin/AdminSemiAutoTasksPage.tsx'),
'utf8',
)
test('注入完成后打开对应平台页面', () => {
assert.equal(resolvePostInjectionUrl('huya'), POST_INJECTION_URLS.huya)
assert.equal(resolvePostInjectionUrl('weibo'), POST_INJECTION_URLS.weibo)
assert.match(POST_INJECTION_URLS.huya, /^https:\/\/m-shop\.huya\.com\/points\.html\?/)
assert.match(
POST_INJECTION_URLS.weibo,
/^https:\/\/vipclub\.e\.weibo\.com\/game\/homepage\?F=bowen_tjg$/,
)
assert.equal(resolvePostInjectionUrl('other'), '')
assert.equal(resolvePostInjectionUrl(null), '')
})
test('注入按钮预开新标签页,完成后跳转,失败/超时关闭', () => {
assert.ok(source.includes("window.open('about:blank', '_blank')"))
assert.ok(source.includes('function startInjection('))
assert.ok(source.includes('onClick={() => startInjection(task)}'))
assert.ok(source.includes('onClick={() => startInjection(detail.task)}'))
assert.ok(source.includes('huya-exchange-result'))
assert.ok(source.includes('resolvePostInjectionUrl(pending.platform)'))
assert.ok(source.includes('popup.location.href = targetUrl'))
assert.ok(source.includes('popup.focus()'))
assert.ok(source.includes("const opened = window.open(targetUrl, '_blank')"))
// 占位页无法导航时,先关闭残留标签再走 window.open 兜底,避免留下空白页。
const jumpIndex = source.indexOf('popup.location.href = targetUrl')
const fallbackIndex = source.indexOf("const opened = window.open(targetUrl, '_blank')")
assert.ok(jumpIndex >= 0 && fallbackIndex > jumpIndex)
assert.ok(source.slice(jumpIndex, fallbackIndex).includes('popup.close()'))
assert.ok(source.includes('pending.popup.close()'))
assert.ok(source.includes('INJECTION_FOLLOW_UP_TIMEOUT_MS'))
assert.ok(source.includes('未检测到注入完成'))
assert.ok(source.includes('上一次注入尚未完成'))
assert.ok(source.includes("dataset.huyaExchangeHelper !== '1'"))
assert.ok(source.includes('未检测到浏览器扩展'))
})