feat(douyu): 新增客户领取与角色绑定工作台

This commit is contained in:
yml
2026-11-18 11:00:28 +08:00
parent d0ec21ce16
commit 6de129d70a
29 changed files with 2119 additions and 5 deletions
+25 -1
View File
@@ -12,7 +12,10 @@ import {
import { getAdminRole, hasAdminSession } from '@/utils/admin-auth'
import { isClaimPath, isH5ClaimPath } from '@/utils/claim-path'
import { isCustomerFulfillmentPath } from '@/utils/customer-fulfillment-link'
import {
isCustomerFulfillmentPath,
isDouyuFulfillmentPath,
} from '@/utils/customer-fulfillment-link'
import {
isLegacySupplementPath,
isOrderServicePath,
@@ -44,6 +47,7 @@ const AdminPlatformShopsPage = lazy(() => import('@/pages/admin/platform/AdminPl
const AdminTaskDetailPage = lazy(() => import('@/pages/admin/AdminTaskDetailPage'))
const AdminTasksPage = lazy(() => import('@/pages/admin/AdminTasksPage'))
const AdminSemiAutoTasksPage = lazy(() => import('@/pages/admin/AdminSemiAutoTasksPage'))
const AdminDouyuFulfillmentPage = lazy(() => import('@/pages/admin/AdminDouyuFulfillmentPage'))
const AdminUsersPage = lazy(() => import('@/pages/admin/AdminUsersPage'))
const AdminDevMockPage = lazy(() => import('@/pages/admin/AdminDevMockPage'))
const AdminWorkerPlatformPage = lazy(() => import('@/pages/admin/AdminWorkerPlatformPage'))
@@ -53,6 +57,7 @@ const OrderServicePage = lazy(() => import('@/pages/public/OrderServicePage'))
const CustomerFulfillmentPage = lazy(
() => import('@/pages/customer-fulfillment/CustomerFulfillmentPage'),
)
const DouyuFulfillmentPage = lazy(() => import('@/pages/douyu-fulfillment/DouyuFulfillmentPage'))
const NotFoundPage = lazy(() => import('@/pages/NotFoundPage'))
const RedeemPage = lazy(() => import('@/pages/redeem/RedeemPage'))
const WorkerHallPage = lazy(() => import('@/pages/worker/WorkerHallPage'))
@@ -136,6 +141,10 @@ export default function App() {
return <OrderServiceApplication />
}
if (isDouyuFulfillmentPath(window.location.pathname)) {
return <DouyuFulfillmentApplication />
}
if (isCustomerFulfillmentPath(window.location.pathname)) {
return <CustomerFulfillmentApplication />
}
@@ -152,6 +161,20 @@ export default function App() {
return <AdminApplication />
}
function DouyuFulfillmentApplication() {
useClearStrayHash()
return (
<BrowserRouter>
<Suspense fallback={<RouteLoading />}>
<Routes>
<Route path="/coll/d/:orderNo" element={<DouyuFulfillmentPage />} />
<Route path="*" element={<DouyuFulfillmentPage />} />
</Routes>
</Suspense>
</BrowserRouter>
)
}
function OrderServiceApplication() {
useClearStrayHash()
return (
@@ -214,6 +237,7 @@ function AdminApplication() {
<Route path="tasks" element={<AdminTasksPage />} />
<Route path="tasks/:taskId" element={<AdminTaskDetailPage />} />
<Route path="semi-auto-tasks" element={<AdminSemiAutoTasksPage />} />
<Route path="douyu-fulfillment" element={<AdminDouyuFulfillmentPage />} />
</Route>
<Route element={<RequireRole roles={['admin', 'operator', 'support', 'finance']} />}>
<Route path="orders" element={<AdminOrdersPage />} />
+11
View File
@@ -17,6 +17,7 @@ import {
SettingOutlined,
SoundOutlined,
TeamOutlined,
ThunderboltOutlined,
TrophyOutlined,
UnorderedListOutlined,
UserOutlined,
@@ -252,6 +253,11 @@ export default function AdminLayout() {
icon: <RobotOutlined />,
label: '半自动履约',
},
{
key: '/admin/douyu-fulfillment',
icon: <ThunderboltOutlined />,
label: '斗鱼领取',
},
{ key: '/admin/worker-platform', icon: <TrophyOutlined />, label: '接单平台' },
{
key: '/admin/kuaishou-industry',
@@ -274,6 +280,11 @@ export default function AdminLayout() {
icon: <RobotOutlined />,
label: '半自动履约',
},
{
key: '/admin/douyu-fulfillment',
icon: <ThunderboltOutlined />,
label: '斗鱼领取',
},
{ key: '/admin/worker-platform', icon: <TrophyOutlined />, label: '接单平台' },
{
key: '/admin/kuaishou-industry',
@@ -551,6 +551,8 @@ function AffiliateDashResultCard({ result }: { result: DevMockCreateResult }) {
}
function DouyuFulfillmentResultCard({ result }: { result: DevDouyuFulfillmentMockResult }) {
const { message } = App.useApp()
const customerUrl = `${window.location.origin}${result.customerPath}`
return (
<Card size="small" title="最近结果" extra={<Link to={result.adminPath}>打开订单</Link>}>
<Row gutter={[12, 12]}>
@@ -576,6 +578,14 @@ function DouyuFulfillmentResultCard({ result }: { result: DevDouyuFulfillmentMoc
<Typography.Text type="secondary">履约单</Typography.Text>
<div>#{result.fulfillmentId}</div>
</Col>
<Col span={24}>
<Typography.Text type="secondary">客户领取链接</Typography.Text>
<Typography.Paragraph style={{ margin: '4px 0 0' }}>
<Typography.Link href={customerUrl} target="_blank" rel="noreferrer">
<LinkOutlined /> {customerUrl}
</Typography.Link>
</Typography.Paragraph>
</Col>
<Col span={24}>
<Alert
type="success"
@@ -590,6 +600,22 @@ function DouyuFulfillmentResultCard({ result }: { result: DevDouyuFulfillmentMoc
}
/>
</Col>
<Col span={24}>
<Space wrap>
<Button
icon={<CopyOutlined />}
onClick={async () => {
await navigator.clipboard.writeText(customerUrl)
message.success('斗鱼客户领取链接已复制')
}}
>
复制客户链接
</Button>
<Button type="primary" href={customerUrl} target="_blank">
打开客户领取页
</Button>
</Space>
</Col>
</Row>
</Card>
)
@@ -0,0 +1,390 @@
import {
CopyOutlined,
LinkOutlined,
ReloadOutlined,
SyncOutlined,
ThunderboltOutlined,
} from '@ant-design/icons'
import {
Alert,
App,
Button,
Card,
Descriptions,
Drawer,
Input,
Select,
Space,
Tag,
Timeline,
Typography,
} from 'antd'
import type { TableColumnsType } from 'antd'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useState } from 'react'
import PageHeader from '@/components/admin/PageHeader'
import PercentTable from '@/components/common/PercentTable'
import {
fetchAdminDouyuFulfillmentDetail,
fetchAdminDouyuFulfillmentTasks,
refreshAdminDouyuBinding,
restartAdminDouyuBinding,
syncAdminDouyuFulfillmentTasks,
} from '@/services/admin'
import type { DouyuFulfillmentTask } from '@/types/douyu-fulfillment'
import { formatAdminDateTime } from '@/utils/admin-time'
const { Text } = Typography
const STATUS_LABELS: Record<string, string> = {
waiting_profile: '待客户填资料',
preparing: '准备账号',
qr_pending: '待扫码',
role_ready: '待确认角色',
bound: '角色已绑定',
waiting_operator: '待运营处理',
processing: '处理中',
completed: '已完成',
failed: '失败',
manual_required: '人工处理',
cancelled: '已取消',
}
const STATUS_COLORS: Record<string, string> = {
waiting_profile: 'blue',
preparing: 'gold',
qr_pending: 'cyan',
role_ready: 'orange',
bound: 'green',
waiting_operator: 'volcano',
processing: 'processing',
completed: 'success',
failed: 'error',
manual_required: 'warning',
cancelled: 'default',
}
const PLATFORM_LABELS: Record<string, string> = {
wechat: '微信',
qq: 'QQ',
}
const SYSTEM_LABELS: Record<string, string> = {
ios: '苹果',
android: '安卓',
}
export default function AdminDouyuFulfillmentPage() {
const { message } = App.useApp()
const queryClient = useQueryClient()
const [keyword, setKeyword] = useState('')
const [status, setStatus] = useState('')
const [page, setPage] = useState(1)
const [pageSize, setPageSize] = useState(20)
const [detailOrderNo, setDetailOrderNo] = useState('')
const listQuery = useQuery({
queryKey: ['admin-douyu-fulfillment', keyword, status, page, pageSize],
queryFn: () =>
fetchAdminDouyuFulfillmentTasks({
keyword: keyword.trim() || undefined,
status: status || undefined,
page,
pageSize,
}),
refetchInterval: 5000,
})
const detailQuery = useQuery({
queryKey: ['admin-douyu-fulfillment-detail', detailOrderNo],
queryFn: () => fetchAdminDouyuFulfillmentDetail(detailOrderNo),
enabled: Boolean(detailOrderNo),
refetchInterval: detailOrderNo ? 3000 : false,
})
const list = listQuery.data?.data.items || []
const pagination = listQuery.data?.data.pagination
const detail = detailQuery.data?.data
async function refreshAll() {
await Promise.all([
queryClient.invalidateQueries({ queryKey: ['admin-douyu-fulfillment'] }),
detailOrderNo
? queryClient.invalidateQueries({
queryKey: ['admin-douyu-fulfillment-detail', detailOrderNo],
})
: Promise.resolve(),
])
}
const syncMutation = useMutation({
mutationFn: syncAdminDouyuFulfillmentTasks,
onSuccess: async (response) => {
message.success(`同步完成:新增 ${response.data.created},更新 ${response.data.updated}`)
await refreshAll()
},
onError: (error) => message.error(error instanceof Error ? error.message : '同步失败'),
})
const refreshMutation = useMutation({
mutationFn: refreshAdminDouyuBinding,
onSuccess: async () => {
message.success('绑定状态已刷新')
await refreshAll()
},
onError: (error) => message.error(error instanceof Error ? error.message : '刷新失败'),
})
const restartMutation = useMutation({
mutationFn: restartAdminDouyuBinding,
onSuccess: async () => {
message.success('已重新生成绑定二维码')
await refreshAll()
},
onError: (error) => message.error(error instanceof Error ? error.message : '重新生成失败'),
})
async function copyLink(task: DouyuFulfillmentTask) {
const url = `${window.location.origin}${task.linkPath}`
try {
await navigator.clipboard.writeText(url)
message.success('客户领取链接已复制')
} catch {
message.error('复制失败,请手动复制')
}
}
const columns: TableColumnsType<DouyuFulfillmentTask> = [
{
title: '订单 / 商品',
key: 'order',
width: 280,
render: (_, task) => (
<Space direction="vertical" size={2}>
<Text strong>{task.platform_order_id}</Text>
<Text>{task.product_name || task.sku_name || task.sku_code}</Text>
<Text type="secondary">订单项 #{task.order_item_id}</Text>
</Space>
),
},
{
title: '客户资料',
key: 'profile',
width: 220,
render: (_, task) =>
task.customer_role_name ? (
<Space direction="vertical" size={2}>
<Text strong>{task.customer_role_name}</Text>
<Text type="secondary">
{PLATFORM_LABELS[task.customer_platform] || '-'} ·{' '}
{SYSTEM_LABELS[task.customer_system] || '-'}
</Text>
</Space>
) : (
<Text type="secondary">待客户填写</Text>
),
},
{
title: '绑定角色',
key: 'boundRole',
width: 220,
render: (_, task) =>
task.bound_role_name ? (
<Space direction="vertical" size={2}>
<Text strong>{task.bound_role_name}</Text>
<Text type="secondary">
{[task.bound_area_name, task.bound_plat_name].filter(Boolean).join(' · ') || '-'}
</Text>
</Space>
) : (
<Text type="secondary">未识别</Text>
),
},
{
title: '状态',
dataIndex: 'status',
width: 140,
render: (value: string) => (
<Tag color={STATUS_COLORS[value] || 'default'}>{STATUS_LABELS[value] || value}</Tag>
),
},
{
title: '更新时间',
dataIndex: 'updated_at',
width: 165,
render: (value: string) => formatAdminDateTime(value),
},
{
title: '操作',
key: 'actions',
width: 360,
render: (_, task) => (
<Space wrap>
<Button size="small" onClick={() => setDetailOrderNo(task.platform_order_id)}>
详情
</Button>
<Button size="small" icon={<CopyOutlined />} onClick={() => void copyLink(task)}>
客户链接
</Button>
<Button
size="small"
icon={<ReloadOutlined />}
loading={refreshMutation.isPending}
onClick={() => refreshMutation.mutate(task.platform_order_id)}
>
刷新绑定
</Button>
</Space>
),
},
]
return (
<section className="page-stack">
<PageHeader
title="斗鱼领取工作台"
description="客户提交游戏资料并完成角色绑定;内部账号与兑换仍在直播账号履约工作台处理。"
/>
<Alert
type="info"
showIcon
message="客户领取链接格式"
description="域名/coll/d/订单号。客户资料和绑定状态会同步到 live-hub,但不会向客户展示 CK、积分或账号信息。"
/>
<Card size="small">
<Space wrap style={{ marginBottom: 16 }}>
<Input.Search
allowClear
placeholder="订单号 / 商品 / 角色名"
value={keyword}
onChange={(event) => {
setKeyword(event.target.value)
setPage(1)
}}
style={{ width: 300 }}
/>
<Select
allowClear
placeholder="全部状态"
value={status || undefined}
onChange={(value) => {
setStatus(value || '')
setPage(1)
}}
options={Object.entries(STATUS_LABELS).map(([value, label]) => ({
value,
label,
}))}
style={{ width: 160 }}
/>
<Button
type="primary"
icon={<SyncOutlined />}
loading={syncMutation.isPending}
onClick={() => syncMutation.mutate()}
>
同步斗鱼订单
</Button>
<Button icon={<ReloadOutlined />} onClick={() => void listQuery.refetch()}>
刷新
</Button>
</Space>
<PercentTable<DouyuFulfillmentTask>
rowKey="id"
loading={listQuery.isLoading}
columns={columns}
dataSource={list}
scroll={{ x: 1250 }}
pagination={{
current: pagination?.page || page,
pageSize: pagination?.pageSize || pageSize,
total: pagination?.total || 0,
showSizeChanger: true,
onChange: (nextPage, nextPageSize) => {
setPage(nextPage)
setPageSize(nextPageSize)
},
}}
/>
</Card>
<Drawer
open={Boolean(detailOrderNo)}
width="min(980px, 94vw)"
title={detail ? `斗鱼领取详情 · ${detail.task.platform_order_id}` : '斗鱼领取详情'}
onClose={() => setDetailOrderNo('')}
>
{detailQuery.isLoading || !detail ? (
<Text type="secondary">加载中...</Text>
) : (
<Space direction="vertical" size={16} style={{ width: '100%' }}>
<Alert
type={detail.comparison.matched ? 'success' : 'warning'}
showIcon
message={STATUS_LABELS[detail.task.status] || detail.task.status}
description={detail.comparison.message || detail.live.message}
/>
<Descriptions bordered size="small" column={2}>
<Descriptions.Item label="订单号" span={2}>
{detail.task.platform_order_id}
</Descriptions.Item>
<Descriptions.Item label="商品" span={2}>
{detail.task.product_name || detail.task.sku_name}
</Descriptions.Item>
<Descriptions.Item label="客户角色">
{detail.task.customer_role_name || '-'}
</Descriptions.Item>
<Descriptions.Item label="客户平台">
{PLATFORM_LABELS[detail.task.customer_platform] || '-'} ·{' '}
{SYSTEM_LABELS[detail.task.customer_system] || '-'}
</Descriptions.Item>
<Descriptions.Item label="平台角色">{detail.live.roleName || '-'}</Descriptions.Item>
<Descriptions.Item label="平台渠道">
{[detail.live.areaName, detail.live.platName].filter(Boolean).join(' · ') || '-'}
</Descriptions.Item>
<Descriptions.Item label="绑定阶段" span={2}>
{detail.task.binding_phase || '-'}
</Descriptions.Item>
</Descriptions>
<Space wrap>
<Button icon={<CopyOutlined />} onClick={() => void copyLink(detail.task)}>
复制客户链接
</Button>
<Button
icon={<ReloadOutlined />}
loading={refreshMutation.isPending}
onClick={() => refreshMutation.mutate(detail.task.platform_order_id)}
>
刷新绑定
</Button>
<Button
type="primary"
icon={<ThunderboltOutlined />}
loading={restartMutation.isPending}
onClick={() => restartMutation.mutate(detail.task.platform_order_id)}
>
重新生成二维码
</Button>
<Button icon={<LinkOutlined />} href={detail.linkPath} target="_blank">
打开客户页
</Button>
</Space>
<Card size="small" title="事件时间线">
<Timeline
items={detail.events.map((event) => ({
color: event.event_type.includes('failed') ? 'red' : 'blue',
children: (
<Space direction="vertical" size={2}>
<Text strong>{event.event_type}</Text>
<Text type="secondary">
{formatAdminDateTime(event.created_at)} · {event.actor_type}
</Text>
</Space>
),
}))}
/>
</Card>
</Space>
)}
</Drawer>
</section>
)
}
@@ -68,6 +68,7 @@ type ConfigFormValues = {
note?: string
semiAutoEnabled?: boolean
semiAutoPlatform?: '' | 'huya' | 'weibo'
douyuFulfillmentEnabled?: boolean
semiAutoConfig?: {
pageTitle?: string
pageDescription?: string
@@ -153,6 +154,7 @@ export function ManualSkuConfigPanel() {
semiAutoEnabled: values.semiAutoEnabled === true,
semiAutoPlatform: values.semiAutoEnabled ? values.semiAutoPlatform || '' : '',
semiAutoConfig: values.semiAutoConfig || {},
douyuFulfillmentEnabled: values.douyuFulfillmentEnabled === true,
}),
onSuccess: (response) => {
const summary = response.data.syncSummary
@@ -215,6 +217,7 @@ export function ManualSkuConfigPanel() {
semiAutoEnabled: item.config?.semiAutoEnabled === true,
semiAutoPlatform: item.config?.semiAutoPlatform || '',
semiAutoConfig: item.config?.semiAutoConfig || {},
douyuFulfillmentEnabled: item.config?.douyuFulfillmentEnabled === true,
})
setModalOpen(true)
}
@@ -229,6 +232,7 @@ export function ManualSkuConfigPanel() {
semiAutoEnabled: false,
semiAutoPlatform: '',
semiAutoConfig: {},
douyuFulfillmentEnabled: false,
})
setModalOpen(true)
}
@@ -697,6 +701,14 @@ export function ManualSkuConfigPanel() {
) : null
}
</Form.Item>
<Form.Item
name="douyuFulfillmentEnabled"
label="启用斗鱼精英宝典领取"
valuePropName="checked"
extra="客户通过 域名/coll/d/订单号 提交资料并扫码绑定角色;内部账号和兑换仍在直播账号履约工作台处理。"
>
<Switch />
</Form.Item>
</Card>
<Form.Item name="note" label="备注">
<Input.TextArea rows={2} maxLength={300} showCount />
@@ -0,0 +1,492 @@
import {
CheckCircleFilled,
ExclamationCircleOutlined,
LoadingOutlined,
QrcodeOutlined,
ReloadOutlined,
} from '@ant-design/icons'
import { Alert, App, Button, Image, Input, Progress, Segmented, Space, Spin } from 'antd'
import QRCode from 'qrcode'
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
import { useParams } from 'react-router'
import {
confirmDouyuBinding,
fetchDouyuFulfillment,
pollDouyuBinding,
saveDouyuProfile,
startDouyuBinding,
} from '@/services/douyu-fulfillment'
import type {
DouyuCustomerFulfillment,
DouyuCustomerPlatform,
DouyuCustomerSystem,
} from '@/types/douyu-fulfillment'
import { formatAdminDateTime } from '@/utils/admin-time'
const POLL_INTERVAL_MS = 3000
const STATUS_LABELS: Record<string, string> = {
waiting_profile: '等待填写资料',
preparing: '正在准备账号',
qr_pending: '等待扫码绑定',
role_ready: '请确认游戏角色',
bound: '角色已绑定',
waiting_operator: '等待运营处理',
processing: '正在兑换',
completed: '领取完成',
failed: '处理失败',
manual_required: '等待人工处理',
cancelled: '订单已取消',
}
function platformLabel(value: string) {
if (value === 'wechat') return '微信'
if (value === 'qq') return 'QQ'
return '未填写'
}
function systemLabel(value: string) {
if (value === 'ios') return '苹果'
if (value === 'android') return '安卓'
return '未填写'
}
export default function DouyuFulfillmentPage() {
const { message } = App.useApp()
const { orderNo = '' } = useParams<{ orderNo: string }>()
const [data, setData] = useState<DouyuCustomerFulfillment | null>(null)
const [loading, setLoading] = useState(true)
const [loadError, setLoadError] = useState('')
const [saving, setSaving] = useState(false)
const [bindingLoading, setBindingLoading] = useState(false)
const [roleName, setRoleName] = useState('')
const [platform, setPlatform] = useState<DouyuCustomerPlatform>('wechat')
const [system, setSystem] = useState<DouyuCustomerSystem>('android')
const [qrImage, setQrImage] = useState('')
const [nowMs, setNowMs] = useState(0)
const autoStartRef = useRef('')
const applyData = useCallback((next: DouyuCustomerFulfillment) => {
setData(next)
setRoleName((current) => current || next.task.customer_role_name || '')
if (next.task.customer_platform === 'qq' || next.task.customer_platform === 'wechat') {
setPlatform(next.task.customer_platform)
}
if (next.task.customer_system === 'ios' || next.task.customer_system === 'android') {
setSystem(next.task.customer_system)
}
}, [])
const load = useCallback(
async (silent = false) => {
if (!orderNo) {
setLoadError('订单号无效')
setLoading(false)
return
}
if (!silent) setLoading(true)
try {
const response = await fetchDouyuFulfillment(orderNo)
applyData(response.data)
setLoadError('')
} catch (error) {
if (!silent) {
setLoadError(error instanceof Error ? error.message : '读取订单失败')
}
} finally {
if (!silent) setLoading(false)
}
},
[applyData, orderNo],
)
useEffect(() => {
void load()
}, [load])
const task = data?.task
const live = data?.live
const needsProfile = Boolean(task && !task.customer_role_name)
const activeBinding = Boolean(
task &&
!needsProfile &&
!['completed', 'cancelled'].includes(task.status) &&
!live?.bindConfirmed,
)
useEffect(() => {
if (!activeBinding || !orderNo) return
const timer = window.setInterval(() => {
void pollDouyuBinding(orderNo)
.then((response) => applyData(response.data))
.catch(() => undefined)
}, POLL_INTERVAL_MS)
return () => window.clearInterval(timer)
}, [activeBinding, applyData, orderNo])
useEffect(() => {
const url = live?.qrUrl || ''
if (!url) {
setQrImage('')
return
}
void QRCode.toDataURL(url, {
width: 320,
margin: 2,
color: { dark: '#111827', light: '#ffffff' },
}).then(setQrImage)
}, [live?.qrUrl])
useEffect(() => {
const tick = () => setNowMs(Date.now())
tick()
const timer = window.setInterval(tick, 1000)
return () => window.clearInterval(timer)
}, [live?.qrExpiresAt])
useEffect(() => {
if (!task || !live || needsProfile || live.qrUrl || live.bindConfirmed) return
if (!live.accountReady) return
if (task.status !== 'preparing' && task.status !== 'waiting_profile') return
if (autoStartRef.current === orderNo) return
autoStartRef.current = orderNo
let cancelled = false
setBindingLoading(true)
void startDouyuBinding(orderNo)
.then((response) => {
if (!cancelled) applyData(response.data)
})
.catch(() => undefined)
.finally(() => {
if (!cancelled) setBindingLoading(false)
})
return () => {
cancelled = true
}
}, [applyData, live, needsProfile, orderNo, task])
const expiresInSeconds = useMemo(() => {
const raw = live?.qrExpiresAt || ''
const expiresAt = raw ? Date.parse(raw) : 0
if (!expiresAt || Number.isNaN(expiresAt)) return 0
return Math.max(0, Math.floor((expiresAt - nowMs) / 1000))
}, [live?.qrExpiresAt, nowMs])
async function submitProfile() {
if (!roleName.trim()) {
message.warning('请输入游戏角色名')
return
}
setSaving(true)
try {
const response = await saveDouyuProfile(orderNo, {
roleName: roleName.trim(),
platform,
system,
})
applyData(response.data)
message.success('资料已提交,正在准备绑定二维码')
} catch (error) {
message.error(error instanceof Error ? error.message : '提交资料失败')
} finally {
setSaving(false)
}
}
async function startBinding(forceRefresh = false) {
setBindingLoading(true)
try {
const response = await startDouyuBinding(orderNo, forceRefresh)
applyData(response.data)
message.success(forceRefresh ? '二维码已刷新' : '绑定流程已继续')
} catch (error) {
message.error(error instanceof Error ? error.message : '生成绑定二维码失败')
} finally {
setBindingLoading(false)
}
}
async function confirmBinding() {
setBindingLoading(true)
try {
const response = await confirmDouyuBinding(orderNo)
applyData(response.data)
message.success('角色绑定已确认,等待运营处理')
} catch (error) {
message.error(error instanceof Error ? error.message : '确认角色绑定失败')
} finally {
setBindingLoading(false)
}
}
if (loading) {
return (
<CustomerFrame title="斗鱼精英宝典领取">
<div className="customer-auth-loading">
<Spin indicator={<LoadingOutlined spin />} />
<span>正在读取订单...</span>
</div>
</CustomerFrame>
)
}
if (loadError || !data || !task) {
return (
<CustomerFrame title="斗鱼精英宝典领取">
<div className="customer-auth-state is-error">
<h2>暂时无法打开订单</h2>
<p>{loadError || '订单信息不存在'}</p>
</div>
</CustomerFrame>
)
}
if (task.status === 'completed') {
return (
<CustomerFrame title="斗鱼精英宝典领取">
<OrderCard data={data} />
<div className="customer-auth-state is-success">
<div className="customer-auth-state-icon">
<CheckCircleFilled />
</div>
<h2>领取已完成</h2>
<p>运营已完成本订单兑换,请到和平精英账号中确认。</p>
{task.completed_at ? (
<span className="customer-auth-state-time">
完成时间:{formatAdminDateTime(task.completed_at)}
</span>
) : null}
</div>
</CustomerFrame>
)
}
if (task.status === 'cancelled') {
return (
<CustomerFrame title="斗鱼精英宝典领取">
<OrderCard data={data} />
<Alert
type="warning"
showIcon
message="订单领取已关闭"
description="如订单发生退款或取消,请联系客服确认。"
/>
</CustomerFrame>
)
}
return (
<CustomerFrame title="斗鱼精英宝典领取">
<OrderCard data={data} />
{needsProfile ? (
<section className="customer-auth-section">
<div className="customer-auth-section-heading">
<div>
<h2>填写游戏角色</h2>
<p>资料用于核对扫码绑定的和平精英角色。</p>
</div>
</div>
<div className="customer-collect-body">
<label className="customer-collect-label">登录方式</label>
<Segmented
block
value={platform}
onChange={(value) => setPlatform(value as DouyuCustomerPlatform)}
options={[
{ label: '微信', value: 'wechat' },
{ label: 'QQ', value: 'qq' },
]}
/>
<label className="customer-collect-label">设备系统</label>
<Segmented
block
value={system}
onChange={(value) => setSystem(value as DouyuCustomerSystem)}
options={[
{ label: '安卓', value: 'android' },
{ label: '苹果', value: 'ios' },
]}
/>
<label className="customer-collect-label">游戏角色名</label>
<Input
className="customer-collect-input"
value={roleName}
onChange={(event) => setRoleName(event.target.value)}
placeholder="请输入和平精英角色名"
maxLength={100}
/>
<Button
block
size="large"
className="customer-collect-submit"
loading={saving}
onClick={() => void submitProfile()}
>
提交资料并继续
</Button>
</div>
</section>
) : (
<section className="customer-binding-stage">
<Alert
type={live?.bindConfirmed ? 'success' : 'info'}
showIcon
message={STATUS_LABELS[task.status] || '等待处理'}
description={
live?.message ||
'请使用微信扫描下方二维码,按提示选择和平精英角色。二维码仅用于本次订单。'
}
/>
{!live?.qrUrl && task.status !== 'completed' ? (
<div className="customer-binding-qr-card">
<h3>游戏角色绑定二维码</h3>
<div className="customer-auth-qr-placeholder">
<Spin />
<span>正在准备绑定二维码...</span>
</div>
<Button
block
size="large"
loading={bindingLoading}
onClick={() => void startBinding(false)}
>
继续准备
</Button>
</div>
) : null}
{live?.qrUrl && !live.bindConfirmed ? (
<div className="customer-binding-qr-card">
<h3>游戏角色绑定二维码</h3>
{qrImage ? (
<Image src={qrImage} alt="和平精英角色绑定二维码" width={260} preview={false} />
) : (
<div className="customer-auth-qr-placeholder">
<Spin />
<span>正在生成二维码图片...</span>
</div>
)}
<p className="customer-binding-qr-hint">
请使用微信扫码,并选择与资料一致的和平精英角色。
</p>
{expiresInSeconds > 0 ? (
<div className="customer-binding-qr-countdown">
二维码剩余 {Math.ceil(expiresInSeconds / 60)} 分钟
</div>
) : null}
<Progress percent={Math.min(100, (expiresInSeconds / 600) * 100)} showInfo={false} />
<div className="customer-binding-qr-actions">
<Button
icon={<ReloadOutlined />}
loading={bindingLoading}
onClick={() => void startBinding(true)}
>
刷新二维码
</Button>
<Button
icon={<QrcodeOutlined />}
loading={bindingLoading}
onClick={() =>
void pollDouyuBinding(orderNo).then((response) => applyData(response.data))
}
>
刷新状态
</Button>
</div>
</div>
) : null}
{live?.bindReadyForConfirm ? (
<div className="customer-binding-qr-card">
<h3>核对绑定角色</h3>
<p className="customer-binding-qr-hint">
平台识别角色:{live.roleName || '-'} · {live.areaName || '-'} ·{' '}
{live.platName || '-'}
</p>
<p className="customer-binding-qr-hint">
已填资料:{task.customer_role_name} · {platformLabel(task.customer_platform)} ·{' '}
{systemLabel(task.customer_system)}
</p>
<Alert
type={data.comparison.matched ? 'success' : 'warning'}
showIcon
message={data.comparison.matched ? '角色信息一致' : '角色信息不一致'}
description={data.comparison.message}
/>
<Space direction="vertical" size={10} style={{ width: '100%' }}>
<Button
block
size="large"
type="primary"
disabled={!data.comparison.matched}
loading={bindingLoading}
onClick={() => void confirmBinding()}
>
确认绑定角色
</Button>
<Button
block
danger
icon={<ExclamationCircleOutlined />}
onClick={() => {
setData({ ...data, task: { ...task, customer_role_name: '' } })
}}
>
修改资料
</Button>
</Space>
</div>
) : null}
</section>
)}
<div className="customer-auth-privacy">
资料仅用于本次订单履约。内部账号和登录凭证不会展示给客户。
</div>
</CustomerFrame>
)
}
function CustomerFrame({ title, children }: { title: string; children: ReactNode }) {
return (
<div className="customer-auth-page is-huya">
<div className="customer-auth-shell">
<header className="customer-auth-hero">
<div className="customer-auth-brand">
<div>
<h1>{title}</h1>
</div>
</div>
</header>
<main className="customer-auth-main">{children}</main>
</div>
</div>
)
}
function OrderCard({ data }: { data: DouyuCustomerFulfillment }) {
return (
<section className="customer-order-card">
<h3>订单信息</h3>
<div>
<span>订单号</span>
<strong>{data.task.platform_order_id}</strong>
</div>
<div>
<span>商品</span>
<strong>
{data.task.product_name || data.task.sku_name} × {data.task.quantity}
</strong>
</div>
<div>
<span>状态</span>
<strong className="customer-order-status">
{STATUS_LABELS[data.task.status] || data.task.status}
</strong>
</div>
</section>
)
}
@@ -365,6 +365,7 @@ export function saveAdminManualConfig(payload: {
semiAutoEnabled?: boolean
semiAutoPlatform?: '' | 'huya' | 'weibo'
semiAutoConfig?: Record<string, unknown>
douyuFulfillmentEnabled?: boolean
}) {
return apiPost<ManualFulfillmentConfig>('/api/v1/admin/cost-center/manual-configs', payload)
}
@@ -83,6 +83,7 @@ export type DevDouyuFulfillmentMockResult = {
configId: number
mappingId: number
skuKey: string
customerPath: string
adminPath: string
tips: string[]
}
@@ -0,0 +1,38 @@
import { apiGet, apiPost } from '@/lib/http'
import type { DouyuFulfillmentDetail, DouyuFulfillmentTask } from '@/types/douyu-fulfillment'
export function fetchAdminDouyuFulfillmentTasks(params: {
keyword?: string
status?: string
page?: number
pageSize?: number
}) {
return apiGet<{
items: DouyuFulfillmentTask[]
pagination: { page: number; pageSize: number; total: number }
}>('/api/v1/admin/douyu-fulfillment/tasks', { params })
}
export function syncAdminDouyuFulfillmentTasks() {
return apiPost<{ created: number; updated: number }>('/api/v1/admin/douyu-fulfillment/sync', {})
}
export function fetchAdminDouyuFulfillmentDetail(orderNo: string) {
return apiGet<DouyuFulfillmentDetail>(
`/api/v1/admin/douyu-fulfillment/tasks/${encodeURIComponent(orderNo)}`,
)
}
export function refreshAdminDouyuBinding(orderNo: string) {
return apiPost<DouyuFulfillmentDetail>(
`/api/v1/admin/douyu-fulfillment/tasks/${encodeURIComponent(orderNo)}/binding/refresh`,
{},
)
}
export function restartAdminDouyuBinding(orderNo: string) {
return apiPost<DouyuFulfillmentDetail>(
`/api/v1/admin/douyu-fulfillment/tasks/${encodeURIComponent(orderNo)}/binding/start`,
{ forceRefresh: true },
)
}
@@ -15,3 +15,4 @@ export * from './tasks'
export * from './dev-mock'
export * from './notifications'
export * from './worker-platform'
export * from './douyu-fulfillment'
@@ -0,0 +1,46 @@
import { apiGet, apiPost } from '@/lib/http'
import type {
DouyuCustomerFulfillment,
DouyuCustomerPlatform,
DouyuCustomerSystem,
} from '@/types/douyu-fulfillment'
export function fetchDouyuFulfillment(orderNo: string) {
return apiGet<DouyuCustomerFulfillment>(
`/api/v1/douyu-fulfillment/${encodeURIComponent(orderNo)}`,
)
}
export function saveDouyuProfile(
orderNo: string,
input: {
roleName: string
platform: DouyuCustomerPlatform
system: DouyuCustomerSystem
},
) {
return apiPost<DouyuCustomerFulfillment>(
`/api/v1/douyu-fulfillment/${encodeURIComponent(orderNo)}/profile`,
input,
)
}
export function startDouyuBinding(orderNo: string, forceRefresh = false) {
return apiPost<DouyuCustomerFulfillment>(
`/api/v1/douyu-fulfillment/${encodeURIComponent(orderNo)}/binding/start`,
{ forceRefresh },
)
}
export function pollDouyuBinding(orderNo: string) {
return apiGet<DouyuCustomerFulfillment>(
`/api/v1/douyu-fulfillment/${encodeURIComponent(orderNo)}/binding/status`,
)
}
export function confirmDouyuBinding(orderNo: string) {
return apiPost<DouyuCustomerFulfillment>(
`/api/v1/douyu-fulfillment/${encodeURIComponent(orderNo)}/binding/confirm`,
{},
)
}
@@ -432,6 +432,7 @@ export interface ManualFulfillmentConfig {
enabled: boolean
semiAutoEnabled: boolean
semiAutoPlatform: '' | 'huya' | 'weibo'
douyuFulfillmentEnabled: boolean
semiAutoConfig: {
pageTitle?: string
pageDescription?: string
@@ -0,0 +1,89 @@
export type DouyuCustomerPlatform = 'wechat' | 'qq'
export type DouyuCustomerSystem = 'ios' | 'android'
export type DouyuFulfillmentTask = {
id: number
order_id: number
order_item_id: number
fulfillment_id: number | null
live_session_id: number | null
status: string
customer_role_name: string
customer_platform: string
customer_system: string
binding_phase: string
live_execution_status: string
live_binding_status: string
issue_code: string
last_error: string
bound_role_name: string
bound_area_name: string
bound_plat_name: string
customer_link_opened_at: string | null
binding_started_at: string | null
bound_at: string | null
completed_at: string | null
last_synced_at: string | null
created_at: string
updated_at: string
platform_order_id: string
sku_code: string
sku_name: string
quantity: number
product_name: string
fulfillment_status: string
linkPath: string
}
export type DouyuLiveBindingState = {
sessionId: number
platformOrderId: string
sourceOrderItemId: string
productName: string
quantity: number
executionStatus: string
bindingStatus: string
exchangeStatus: string
issueCode: string
message: string
accountReady: boolean
bindTaskId: number | null
bindTaskStatus: string
bindPhase: string
qrUrl: string
qrGeneratedAt: string
qrExpiresAt: string
roleName: string
areaName: string
platName: string
bindReadyForConfirm: boolean
bindConfirmed: boolean
completedAt: string | null
updatedAt: string
}
export type DouyuRoleComparison = {
matched: boolean
roleMatched: boolean
channelMatched: boolean
message: string
}
export type DouyuCustomerFulfillment = {
task: DouyuFulfillmentTask
live: DouyuLiveBindingState
comparison: DouyuRoleComparison
linkPath: string
}
export type DouyuFulfillmentEvent = {
id: number
event_type: string
actor_type: string
detail_json: Record<string, unknown>
created_at: string
}
export type DouyuFulfillmentDetail = DouyuCustomerFulfillment & {
events: DouyuFulfillmentEvent[]
}
@@ -20,6 +20,21 @@ export function isCustomerFulfillmentPath(pathname: unknown): boolean {
return first === 'c' || first === 'd'
}
/** 斗鱼客户领取入口:/coll/d/:orderNo。 */
export function buildDouyuFulfillmentPath(orderNo: unknown): string {
const normalizedOrderNo = String(orderNo || '').trim()
return normalizedOrderNo ? `/coll/d/${encodeURIComponent(normalizedOrderNo)}` : ''
}
export function isDouyuFulfillmentPath(pathname: unknown): boolean {
const parts = String(pathname || '')
.trim()
.split(/[?#]/)[0]
.split('/')
.filter(Boolean)
return parts[0] === 'coll' && parts[1] === 'd'
}
/**
* 严格绑定下的自动归一化:当前路径对应平台没有任务、但订单只有另一个平台任务时,
* 返回应跳转的平台;双平台订单返回 null(各路径只展示自己的任务),