From 77e1c69a2b6d4e60ca2ea1ea61abbb269bf9a26e Mon Sep 17 00:00:00 2001 From: zhaoxing <2558691827@qq.com> Date: Tue, 17 Nov 2026 17:27:19 +0800 Subject: [PATCH] =?UTF-8?q?feat(semi-auto):=20=E5=AE=A2=E6=88=B7=E9=93=BE?= =?UTF-8?q?=E6=8E=A5=E6=8C=89=E5=B9=B3=E5=8F=B0=E4=B8=A5=E6=A0=BC=E7=BB=91?= =?UTF-8?q?=E5=AE=9A=EF=BC=8C=E6=B3=A8=E5=85=A5=E5=90=8E=E7=BB=9F=E4=B8=80?= =?UTF-8?q?=E7=94=B1=E5=89=8D=E7=AB=AF=E6=89=93=E5=BC=80=E6=8C=87=E5=AE=9A?= =?UTF-8?q?=E9=A1=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/services/dev-mock/dev-mock-service.ts | 8 +- .../semi-auto-injection-payload.test.ts | 34 ++++ .../semi-auto/semi-auto-task-service.ts | 26 ++- .../semi-auto-task.integration.test.ts | 2 +- apps/frontend/src/App.tsx | 14 +- .../src/pages/admin/AdminDevMockPage.tsx | 27 ++- .../pages/admin/AdminSemiAutoTasksPage.tsx | 158 +++++++++++++++--- .../cost-center/ManualSkuConfigPanel.tsx | 2 +- .../CustomerFulfillmentPage.tsx | 46 ++++- .../src/utils/customer-fulfillment-link.ts | 56 ++++++- .../frontend/src/utils/semi-auto-injection.ts | 15 ++ .../tests/customer-fulfillment-link.test.ts | 80 ++++++++- .../tests/semi-auto-injection.test.ts | 47 ++++++ 13 files changed, 459 insertions(+), 56 deletions(-) create mode 100644 apps/backend/src/services/semi-auto/semi-auto-injection-payload.test.ts create mode 100644 apps/frontend/src/utils/semi-auto-injection.ts create mode 100644 apps/frontend/tests/semi-auto-injection.test.ts diff --git a/apps/backend/src/services/dev-mock/dev-mock-service.ts b/apps/backend/src/services/dev-mock/dev-mock-service.ts index d6f1ebcd..ca4abe0c 100644 --- a/apps/backend/src/services/dev-mock/dev-mock-service.ts +++ b/apps/backend/src/services/dev-mock/dev-mock-service.ts @@ -503,7 +503,7 @@ export async function createSemiAutoMock( skuKey, connectorMode, connectorConfigured, - customerPath: `/c/${encodeURIComponent(orderNo)}`, + customerPath: buildMockCustomerPath(platform, orderNo), adminPath: `/admin/semi-auto-tasks?keyword=${encodeURIComponent(orderNo)}`, tips: platform === 'weibo' @@ -781,7 +781,7 @@ export async function createSemiAutoIntegrationMock( connectorMode, connectorConfigured, mappingId, - customerPath: `/c/${encodeURIComponent(orderNo)}`, + customerPath: buildMockCustomerPath(platform, orderNo), adminPath: `/admin/semi-auto-tasks?keyword=${encodeURIComponent(orderNo)}`, tips: [ '订单通过正式 upsertOrderFromSource 入库。', @@ -802,6 +802,10 @@ function normalizeMockSemiAutoPlatform(value: unknown): 'huya' | 'weibo' { : 'huya' } +function buildMockCustomerPath(platform: 'huya' | 'weibo', orderNo: string): string { + return `/${platform === 'weibo' ? 'd' : 'c'}/${encodeURIComponent(orderNo)}` +} + function normalizeMockSemiAutoConnectorMode(value: unknown): SemiAutoConnectorMode { const mode = String(value || '') .trim() diff --git a/apps/backend/src/services/semi-auto/semi-auto-injection-payload.test.ts b/apps/backend/src/services/semi-auto/semi-auto-injection-payload.test.ts new file mode 100644 index 00000000..6ef135d8 --- /dev/null +++ b/apps/backend/src/services/semi-auto/semi-auto-injection-payload.test.ts @@ -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/') + }) +}) diff --git a/apps/backend/src/services/semi-auto/semi-auto-task-service.ts b/apps/backend/src/services/semi-auto/semi-auto-task-service.ts index 709c1c9c..1048e7de 100644 --- a/apps/backend/src/services/semi-auto/semi-auto-task-service.ts +++ b/apps/backend/src/services/semi-auto/semi-auto-task-service.ts @@ -32,6 +32,7 @@ import { consumeHuyaBrowserTicket, verifyHuyaSmsChallenge, type ConnectorBindingSession, + type ConnectorInjectionPayload, type SemiAutoConnectorMode, type ConnectorLoginSession, } from './huya-connector-client.js' @@ -412,7 +413,7 @@ function assertHuyaTask(task: TaskRow) { } /** - * 半自动订单没有工单,资料页 /c/<订单号> 是唯一入口。 + * 半自动订单没有工单,资料页 /c/<订单号>(虎牙)或 /d/<订单号>(微博)是唯一入口。 * 未提交区服 / 游戏编号 / 角色名时,不允许开始登录,避免后续无法比对角色。 */ function assertCustomerProfileReady(task: TaskRow) { @@ -713,7 +714,7 @@ export async function ensureSemiAutoTasksForOrderItems(input: unknown[]) { /** * 后台列表读取前的幂等回填。 * - * 客户不先打开 `/c/订单号` 时,任务也必须进入客服工作台;后备查询只插入缺失任务, + * 客户不先打开 `/c/订单号` 或 `/d/订单号` 时,任务也必须进入客服工作台;后备查询只插入缺失任务, * 不修改已有任务状态,也不会重复写事件。 */ export async function backfillSemiAutoTasks() { @@ -794,7 +795,7 @@ export function normalizeCustomerProfile(input: CustomerProfileInput = {}) { } /** - * 半自动订单没有 work_orders,客户资料只能在授权页 /c/<订单号> 收集。 + * 半自动订单没有 work_orders,客户资料只能在授权页 /c/<订单号>(虎牙)或 /d/<订单号>(微博)收集。 * 保存后立即参与“客户填写角色 vs 平台识别角色”的比对。 */ export async function savePublicTaskProfile( @@ -2200,6 +2201,17 @@ export async function createAdminBrowserSession( return ticket } +/** + * 票据内的 targetUrl 只服务于创建阶段的 Cookie 序列化与审计; + * 下发给扩展时清空,指定平台页统一由前端占位页在注入成功后打开, + * 这样扩展只写 Cookie,不会再额外打开一个目标页标签。 + */ +export function buildExtensionInjectionPayload( + payload: ConnectorInjectionPayload, +): ConnectorInjectionPayload { + return { ...payload, targetUrl: '' } +} + export async function consumeSemiAutoInjectionTicket(ticketInput: unknown) { const ticket = String(ticketInput || '').trim() if (!ticket) { @@ -2208,10 +2220,10 @@ export async function consumeSemiAutoInjectionTicket(ticketInput: unknown) { errorCode: 'semi_auto_injection_ticket_invalid', }) } - if (ticket.startsWith(WEIBO_TICKET_PREFIX)) { - return consumeWeiboBrowserTicket(ticket) - } - return consumeHuyaBrowserTicket(ticket) + const payload = ticket.startsWith(WEIBO_TICKET_PREFIX) + ? await consumeWeiboBrowserTicket(ticket) + : await consumeHuyaBrowserTicket(ticket) + return buildExtensionInjectionPayload(payload) } async function resolveCompletionEvidence( diff --git a/apps/backend/src/services/semi-auto/semi-auto-task.integration.test.ts b/apps/backend/src/services/semi-auto/semi-auto-task.integration.test.ts index b3fd1cc8..28dc20aa 100644 --- a/apps/backend/src/services/semi-auto/semi-auto-task.integration.test.ts +++ b/apps/backend/src/services/semi-auto/semi-auto-task.integration.test.ts @@ -91,7 +91,7 @@ test( [fulfillmentId, configId], ) - // 客服工作台先打开时也必须看到任务,不能依赖客户先访问 `/c/订单号`。 + // 客服工作台先打开时也必须看到任务,不能依赖客户先访问 `/c/订单号` 或 `/d/订单号`。 const adminList = await listAdminSemiAutoTasks({ keyword: orderNo }) assert.equal(adminList.pagination.total, 1) assert.equal(adminList.items[0]?.orderNo, orderNo) diff --git a/apps/frontend/src/App.tsx b/apps/frontend/src/App.tsx index 877b1dda..8af034c3 100644 --- a/apps/frontend/src/App.tsx +++ b/apps/frontend/src/App.tsx @@ -169,12 +169,22 @@ function OrderServiceApplication() { function CustomerFulfillmentApplication() { useClearStrayHash() + // 非标准子路径也按首段路径绑定平台,避免 /c/.../extra 这类地址绕过严格绑定。 + const prefix = window.location.pathname.split('/').filter(Boolean)[0] + const wildcardPlatform = prefix === 'c' ? 'huya' : prefix === 'd' ? 'weibo' : undefined return ( }> - } /> - } /> + } /> + } + /> + } + /> diff --git a/apps/frontend/src/pages/admin/AdminDevMockPage.tsx b/apps/frontend/src/pages/admin/AdminDevMockPage.tsx index 0be2209d..c558022c 100644 --- a/apps/frontend/src/pages/admin/AdminDevMockPage.tsx +++ b/apps/frontend/src/pages/admin/AdminDevMockPage.tsx @@ -33,6 +33,7 @@ import { type DevMockSemiAutoResult, type DevSemiAutoIntegrationResult, } from '@/services/admin' +import { buildCustomerFulfillmentPath } from '@/utils/customer-fulfillment-link' export default function AdminDevMockPage() { const { message } = App.useApp() @@ -109,6 +110,14 @@ export default function AdminDevMockPage() { }) 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) { return ( @@ -347,32 +356,22 @@ export default function AdminDevMockPage() { 客户履约入口
- + {window.location.origin} - {lastSemiAuto.customerPath} + {semiAutoCustomerPath}
- diff --git a/apps/frontend/src/pages/admin/AdminSemiAutoTasksPage.tsx b/apps/frontend/src/pages/admin/AdminSemiAutoTasksPage.tsx index 91365073..42bbdc42 100644 --- a/apps/frontend/src/pages/admin/AdminSemiAutoTasksPage.tsx +++ b/apps/frontend/src/pages/admin/AdminSemiAutoTasksPage.tsx @@ -27,7 +27,7 @@ import { } from 'antd' import type { TableColumnsType } from 'antd' 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 PageHeader from '@/components/admin/PageHeader' @@ -47,6 +47,8 @@ import { 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' const { Text } = Typography @@ -87,6 +89,15 @@ type CompleteFormValues = { 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() @@ -100,6 +111,7 @@ export default function AdminSemiAutoTasksPage() { const [completeTask, setCompleteTask] = useState(null) const [completeFiles, setCompleteFiles] = useState([]) const [completeForm] = Form.useForm() + const pendingInjectionRef = useRef(null) const params = useMemo( () => ({ @@ -137,25 +149,78 @@ export default function AdminSemiAutoTasksPage() { const handleResult = (event: Event) => { const detail = (event as CustomEvent).detail if (typeof detail !== 'string') return + let result: { ok?: boolean; written?: number; error?: string } try { - const result = JSON.parse(detail) as { - ok?: boolean - written?: number - error?: string - } - if (!result || typeof result !== 'object') return - if (result.ok) { - message.success(`浏览器登录态已注入(${Number(result.written || 0)} 个 Cookie)`) - } else { - message.error(result.error || '浏览器登录态注入失败') - } + 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: ( + + 浏览器拦截了自动打开的新标签页,请 + + 点击这里打开平台页面 + + 。 + + ), + }) + 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]) + }, [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), @@ -175,12 +240,33 @@ export default function AdminSemiAutoTasksPage() { 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 } @@ -188,10 +274,39 @@ export default function AdminSemiAutoTasksPage() { message.info('正在注入浏览器登录态,请稍候') void refreshAll() }, - onError: (error) => - message.error(error instanceof Error ? error.message : '打开浏览器登录态失败'), + 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) => { @@ -267,7 +382,12 @@ export default function AdminSemiAutoTasksPage() { } 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 { await navigator.clipboard.writeText(url) if (successMessage) message.success(successMessage) @@ -451,7 +571,7 @@ export default function AdminSemiAutoTasksPage() { icon={} disabled={!taskCanUseCredential(task)} loading={injectionMutation.isPending} - onClick={() => injectionMutation.mutate(task)} + onClick={() => startInjection(task)} > 注入浏览器 @@ -720,7 +840,7 @@ export default function AdminSemiAutoTasksPage() { icon={} disabled={!taskCanUseCredential(detail.task)} loading={injectionMutation.isPending} - onClick={() => injectionMutation.mutate(detail.task)} + onClick={() => startInjection(detail.task)} > 注入浏览器 diff --git a/apps/frontend/src/pages/admin/cost-center/ManualSkuConfigPanel.tsx b/apps/frontend/src/pages/admin/cost-center/ManualSkuConfigPanel.tsx index ac033557..86e9d8bc 100644 --- a/apps/frontend/src/pages/admin/cost-center/ManualSkuConfigPanel.tsx +++ b/apps/frontend/src/pages/admin/cost-center/ManualSkuConfigPanel.tsx @@ -658,7 +658,7 @@ export function ManualSkuConfigPanel() { name="semiAutoEnabled" label="启用半自动履约" valuePropName="checked" - extra="订单进入人工渠道后,客户可通过 /c/订单号 登录平台并完成绑定。" + extra="订单进入人工渠道后,客户可通过专属链接登录平台并完成绑定(虎牙 /c/订单号,微博 /d/订单号)。" > diff --git a/apps/frontend/src/pages/customer-fulfillment/CustomerFulfillmentPage.tsx b/apps/frontend/src/pages/customer-fulfillment/CustomerFulfillmentPage.tsx index 969b1c1e..04ea4d4f 100644 --- a/apps/frontend/src/pages/customer-fulfillment/CustomerFulfillmentPage.tsx +++ b/apps/frontend/src/pages/customer-fulfillment/CustomerFulfillmentPage.tsx @@ -8,7 +8,7 @@ import { import { App, Alert, Button, Image, Input, Modal, Select, Space, Spin } from 'antd' import QRCode from 'qrcode' import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react' -import { useParams } from 'react-router' +import { useLocation, useNavigate, useParams } from 'react-router' import { confirmCustomerBinding, @@ -36,6 +36,11 @@ import type { CustomerSemiAutoTask, } from '@/types/customer-fulfillment' import { formatAdminDateTime } from '@/utils/admin-time' +import { + buildCustomerFulfillmentPath, + resolveCustomerPlatformRedirect, + type CustomerFulfillmentPlatform, +} from '@/utils/customer-fulfillment-link' import { runWeiboYidunChallenge } from '@/utils/weibo-yidun' import HuyaChallengeModal from './HuyaChallengeModal' @@ -46,9 +51,15 @@ const SERVER_ZONE_OPTIONS = ['苹果Q区', '苹果V区', '安卓Q区', '安卓V /** antd v6 语义化 classNames:让区服下拉弹层用页面深色样式 */ 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 { orderNo: routeOrderNo } = useParams<{ orderNo?: string }>() + const navigate = useNavigate() + const { search, hash } = useLocation() const orderNo = String(routeOrderNo || '').trim() const [loading, setLoading] = useState(true) const [loadError, setLoadError] = useState('') @@ -79,6 +90,7 @@ export default function CustomerFulfillmentPage() { const startingBindingRef = useRef(false) const hydratingBindingRef = useRef(false) const autoOpenedRoleRef = useRef('') + const redirectingRef = useRef(false) // Connector 重启或会话被回收后,绑定/确认接口会返回 huya_native_session_not_found。 const [bindingSessionExpired, setBindingSessionExpired] = useState(false) const [bindingLoadError, setBindingLoadError] = useState('') @@ -100,11 +112,28 @@ export default function CustomerFulfillmentPage() { try { const response = await fetchCustomerFulfillment(orderNo) 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('') setSelectedTaskId((current) => { - if (nextTasks.some((task) => task.id === current)) return current - return nextTasks[0]?.id || 0 + if (visibleTasks.some((task) => task.id === current)) return current + return visibleTasks[0]?.id || 0 }) } catch (error) { if (!silent) { @@ -115,9 +144,14 @@ export default function CustomerFulfillmentPage() { if (!silent) setLoading(false) } }, - [orderNo], + [expectedPlatform, hash, navigate, orderNo, search], ) + // 订单号或平台路由变化后允许重新判定跳转,避免复用组件时上一次的标记卡住。 + useEffect(() => { + redirectingRef.current = false + }, [expectedPlatform, orderNo]) + useEffect(() => { void load() }, [load]) diff --git a/apps/frontend/src/utils/customer-fulfillment-link.ts b/apps/frontend/src/utils/customer-fulfillment-link.ts index 5fc0777b..295a3c91 100644 --- a/apps/frontend/src/utils/customer-fulfillment-link.ts +++ b/apps/frontend/src/utils/customer-fulfillment-link.ts @@ -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 { const normalized = String(pathname || '').trim() 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] } diff --git a/apps/frontend/src/utils/semi-auto-injection.ts b/apps/frontend/src/utils/semi-auto-injection.ts new file mode 100644 index 00000000..f4fe2730 --- /dev/null +++ b/apps/frontend/src/utils/semi-auto-injection.ts @@ -0,0 +1,15 @@ +import type { SemiAutoPlatform } from '@/types/admin/semi-auto' + +/** + * 注入浏览器成功后自动打开的平台页面。 + * 只在客户页/后台侧使用;扩展只负责写入 Cookie,指定平台页由前端占位页打开。 + */ +export const POST_INJECTION_URLS: Record = { + 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 '' +} diff --git a/apps/frontend/tests/customer-fulfillment-link.test.ts b/apps/frontend/tests/customer-fulfillment-link.test.ts index ea553831..4b724053 100644 --- a/apps/frontend/tests/customer-fulfillment-link.test.ts +++ b/apps/frontend/tests/customer-fulfillment-link.test.ts @@ -1,17 +1,93 @@ import assert from 'node:assert/strict' +import { readFile } from 'node:fs/promises' 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'), 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('客户半自动履约入口不误伤相似前缀和其他路径', () => { assert.equal(isCustomerFulfillmentPath('/claim/x'), false) assert.equal(isCustomerFulfillmentPath('/customer/x'), 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('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/) }) diff --git a/apps/frontend/tests/semi-auto-injection.test.ts b/apps/frontend/tests/semi-auto-injection.test.ts new file mode 100644 index 00000000..84518ac2 --- /dev/null +++ b/apps/frontend/tests/semi-auto-injection.test.ts @@ -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('未检测到浏览器扩展')) +})