feat(fulfillment): 实时刷新斗鱼账号并支持租约时长设置

This commit is contained in:
yml
2026-11-18 10:59:20 +08:00
parent 0220ef995f
commit 9958e4ab7d
21 changed files with 1546 additions and 120 deletions
@@ -3,9 +3,19 @@ import type {
PlatformFulfillmentDetail,
PlatformFulfillmentListResponse,
PlatformFulfillmentMapping,
PlatformFulfillmentSettings,
} from './types';
export const platformFulfillmentApi = {
getSettings: () =>
api.get<PlatformFulfillmentSettings, PlatformFulfillmentSettings>(
'/platform-fulfillment/settings',
),
updateSettings: (leaseDurationMinutes: number | null) =>
api.put<PlatformFulfillmentSettings, PlatformFulfillmentSettings>(
'/platform-fulfillment/settings',
{ lease_duration_minutes: leaseDurationMinutes },
),
listTasks: (params: {
status?: string;
keyword?: string;
+6 -1
View File
@@ -2118,6 +2118,11 @@ export interface PlatformFulfillmentAccount {
roleChangeAvailableAt: string | null;
}
export interface PlatformFulfillmentSettings {
leaseDurationMinutes: number | null;
updatedAt: string | null;
}
export interface PlatformFulfillmentBindTask {
id: number;
taskType: string;
@@ -2162,7 +2167,7 @@ export interface PlatformFulfillmentTask {
createdAt: string;
updatedAt: string;
account: PlatformFulfillmentAccount | null;
lease: { id: number; status: string; expiresAt: string } | null;
lease: { id: number; status: string; expiresAt: string | null } | null;
bindTask: PlatformFulfillmentBindTask | null;
}
@@ -1,9 +1,9 @@
import { useCallback, useEffect, useState } from 'react';
import { Alert, Button, Card, Descriptions, Drawer, Empty, Input, InputNumber, Modal, QRCode, Select, Space, Switch, Table, Tabs, Tag, Timeline, Typography } from 'antd';
import { CheckCircleOutlined, CopyOutlined, LinkOutlined, QrcodeOutlined, ReloadOutlined, SyncOutlined, UserSwitchOutlined } from '@ant-design/icons';
import { Alert, Button, Card, Descriptions, Drawer, Empty, Input, InputNumber, Modal, QRCode, Segmented, Select, Space, Switch, Table, Tabs, Tag, Timeline, Typography } from 'antd';
import { CheckCircleOutlined, CopyOutlined, LinkOutlined, QrcodeOutlined, ReloadOutlined, SettingOutlined, SyncOutlined, UserSwitchOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { douyuApi, platformFulfillmentApi } from '../api/modules';
import type { DouyuGoodsItem, PlatformFulfillmentDetail, PlatformFulfillmentMapping, PlatformFulfillmentTask } from '../api/modules';
import type { DouyuGoodsItem, PlatformFulfillmentDetail, PlatformFulfillmentMapping, PlatformFulfillmentSettings, PlatformFulfillmentTask } from '../api/modules';
import { getErrorMessage } from '../utils/error';
import { message } from '../utils/antdMessage';
import { formatTime } from '../utils/time';
@@ -39,14 +39,180 @@ const STATUS_COLORS: Record<string, string> = {
cancelled: 'default',
};
const BINDING_STATUS_LABELS: Record<string, string> = {
not_started: '未开始',
preparing: '准备中',
qr_pending: '待扫码',
role_ready: '待确认角色',
bound: '已绑定',
failed: '绑定失败',
};
const EXCHANGE_STATUS_LABELS: Record<string, string> = {
not_started: '未开始',
eligible: '可兑换',
points_short: '积分不足',
not_opened: '精英宝典未开通',
limited: '已达限兑上限',
check_failed: '资格查询失败',
manual_done: '人工兑换完成',
};
const ACTOR_TYPE_LABELS: Record<string, string> = {
system: '系统',
user: '运营',
customer: '客户',
connector: '连接器',
};
const EVENT_LABELS: Record<string, string> = {
task_created: '同步人工履约订单',
mapping_updated: '更新商品映射',
account_allocation_failed: '自动选号未找到可分配账号',
account_allocated: '账号分配成功',
account_released: '释放履约账号',
binding_started: '开始绑定游戏角色',
binding_confirm_started: '提交角色绑定确认',
eligibility_check_failed: '兑换资格查询失败',
exchange_eligibility_checked: '刷新兑换资格',
manual_exchange_completed: '人工兑换完成',
marked_manual_required: '转人工处理',
task_cancelled: '任务已取消',
};
const ISSUE_LABELS: Record<string, string> = {
mapping_missing: '商品映射缺失',
no_eligible_account: '没有可分配账号',
points_short: '积分不足',
elite_not_opened: '精英宝典未开通',
commodity_limit_reached: '商品已达限兑上限',
eligibility_check_failed: '资格查询失败',
binding_failed: '绑定失败',
lease_expired: '账号租约已过期',
manual_required: '需要人工处理',
};
function statusLabel(value: string) {
return STATUS_OPTIONS.find((item) => item.value === value)?.label || value;
}
function bindingStatusLabel(value: string) {
return BINDING_STATUS_LABELS[value] || '未知状态';
}
function exchangeStatusLabel(value: string) {
return EXCHANGE_STATUS_LABELS[value] || '未知状态';
}
function issueLabel(value: string) {
if (!value) return '-';
return ISSUE_LABELS[value] || '其他处理事项';
}
function exchangeStatusHint(status: string) {
if (status === 'points_short') return '当前积分不足,账号不会被淘汰。完成充值后点击“刷新兑换资格”即可继续。';
if (status === 'not_opened') return '账号尚未开通精英宝典,不会被淘汰。开通后点击“刷新兑换资格”即可继续。';
if (status === 'limited') return '当前账号已达到该商品限兑上限,可等待限制解除、人工处理或释放后换号。';
if (status === 'check_failed') return '实时查询失败,账号仍保留。请稍后重新刷新兑换资格。';
if (status === 'eligible') return '账号已满足当前商品兑换条件,可以继续人工兑换。';
return '';
}
function ckStatusLabel(status: string) {
if (status === 'valid') return '有效';
if (status === 'invalid') return '已失效';
if (status === 'error') return '查询异常';
return '未检测';
}
function eliteOpenedLabel(value: boolean | null) {
if (value === true) return '已开通';
if (value === false) return '未开通';
return '未知';
}
function bindStatusLabel(value: string) {
if (value === 'bound') return '已绑定';
if (value === 'unbound') return '未绑定';
if (value === 'pending') return '待确认';
return '未知';
}
function providerLabel(value: string) {
if (value === 'livehub_douyu_dev') return '斗鱼联调';
if (!value) return '-';
return /^[a-z0-9_-]+$/i.test(value) ? '外部订单' : value;
}
function eventLabel(value: string) {
return EVENT_LABELS[value] || '履约记录';
}
function eventColor(value: string) {
if (value.includes('failed') || value.includes('cancelled')) return 'red';
if (value.includes('manual_required')) return 'orange';
if (value.includes('completed') || value.includes('allocated')) return 'green';
return 'blue';
}
function eventDescription(event: { eventType: string; detail: Record<string, unknown> }) {
const detail = event.detail || {};
if (event.eventType === 'account_allocation_failed') {
const diagnostics = Array.isArray(detail.diagnostics) ? detail.diagnostics : [];
const lines = diagnostics.slice(0, 3).map((item) => {
const row = item && typeof item === 'object' ? (item as Record<string, unknown>) : {};
const name = String(row.accountName || `账号 ${row.accountId || '-'}`);
const reasons = Array.isArray(row.reasons) ? row.reasons.map(String) : [];
return `${name}:${reasons.join('、') || '未满足分配条件'}`;
});
return lines.join(';') || '本批账号均不满足当前分配条件';
}
if (event.eventType === 'account_allocated') {
const reasons = Array.isArray(detail.softReasons) ? detail.softReasons.map(String) : [];
const base = `账号 ${String(detail.accountName || '-')},实时积分 ${String(detail.points ?? '-')}`;
return reasons.length ? `${base};后续需要:${reasons.join('、')}` : `${base};可直接兑换`;
}
if (event.eventType === 'mapping_updated') {
return `斗鱼商品 ${String(detail.commodityId || '-')},映射${detail.enabled === false ? '已停用' : '已启用'}`;
}
if (event.eventType === 'exchange_eligibility_checked') {
return `兑换状态:${exchangeStatusLabel(String(detail.exchangeStatus || ''))};限兑商品 ${String(detail.limitedCount ?? 0)} 个`;
}
if (event.eventType === 'eligibility_check_failed') {
return '实时查询兑换资格失败,可稍后重试';
}
if (event.eventType === 'account_released') {
return `释放原因:${String(detail.reason || '人工释放')}`;
}
if (event.eventType === 'manual_exchange_completed') {
return String(detail.note || '运营已确认人工兑换完成');
}
if (event.eventType === 'marked_manual_required') {
return String(detail.reason || '已转人工处理');
}
if (event.eventType === 'task_cancelled') {
return `取消原因:${String(detail.reason || '人工取消')}`;
}
if (event.eventType === 'binding_started') return '已生成客户绑定二维码';
if (event.eventType === 'binding_confirm_started') return '已提交游戏角色绑定确认';
if (event.eventType === 'task_created') return '订单已进入直播账号履约工作台';
return '履约状态已更新';
}
function money(fen: number) {
return `¥${(Number(fen || 0) / 100).toFixed(2)}`;
}
function leaseDurationLabel(minutes: number | null | undefined) {
if (minutes == null) return '无限制';
if (minutes % 60 === 0) return `${minutes / 60} 小时`;
return `${minutes} 分钟`;
}
function leaseExpiresLabel(expiresAt: string | null | undefined) {
return expiresAt ? formatTime(expiresAt) : '无限制';
}
export default function PlatformFulfillmentPage() {
const user = getUser();
const { can } = usePermissions(user);
@@ -70,6 +236,11 @@ export default function PlatformFulfillmentPage() {
const [goods, setGoods] = useState<DouyuGoodsItem[]>([]);
const [mappingGoodsLoading, setMappingGoodsLoading] = useState(false);
const [mappings, setMappings] = useState<PlatformFulfillmentMapping[]>([]);
const [settings, setSettings] = useState<PlatformFulfillmentSettings | null>(null);
const [settingsOpen, setSettingsOpen] = useState(false);
const [leaseDurationMode, setLeaseDurationMode] = useState<'unlimited' | 'minutes' | 'hours'>('unlimited');
const [leaseDurationValue, setLeaseDurationValue] = useState<number | null>(60);
const [savingSettings, setSavingSettings] = useState(false);
const loadTasks = useCallback(async () => {
setLoading(true);
@@ -105,6 +276,13 @@ export default function PlatformFulfillmentPage() {
void loadTasks();
}, [loadTasks]);
useEffect(() => {
void platformFulfillmentApi
.getSettings()
.then(setSettings)
.catch((error) => message.error(getErrorMessage(error)));
}, []);
useEffect(() => {
if (selectedId) void loadDetail(selectedId);
}, [loadDetail, selectedId]);
@@ -207,6 +385,47 @@ export default function PlatformFulfillmentPage() {
}
};
const openLeaseSettings = () => {
const minutes = settings?.leaseDurationMinutes ?? null;
if (minutes == null) {
setLeaseDurationMode('unlimited');
setLeaseDurationValue(60);
} else if (minutes % 60 === 0) {
setLeaseDurationMode('hours');
setLeaseDurationValue(minutes / 60);
} else {
setLeaseDurationMode('minutes');
setLeaseDurationValue(minutes);
}
setSettingsOpen(true);
};
const saveLeaseSettings = async () => {
const minutes =
leaseDurationMode === 'unlimited'
? null
: leaseDurationMode === 'hours'
? Number(leaseDurationValue || 0) * 60
: Number(leaseDurationValue || 0);
if (minutes != null && minutes < 1) {
message.warning('租约时长至少为 1 分钟');
return;
}
setSavingSettings(true);
try {
const result = await platformFulfillmentApi.updateSettings(minutes);
setSettings(result);
setSettingsOpen(false);
message.success(`租约设置已更新为${leaseDurationLabel(result.leaseDurationMinutes)}`);
if (selectedId) await loadDetail(selectedId);
await loadTasks();
} catch (error) {
message.error(getErrorMessage(error));
} finally {
setSavingSettings(false);
}
};
const columns: ColumnsType<PlatformFulfillmentTask> = [
{
title: '订单 / 商品',
@@ -217,7 +436,7 @@ export default function PlatformFulfillmentPage() {
<Text strong>{task.platformOrderId || `#${task.sourceOrderId}`}</Text>
<Text>{task.skuName || task.internalSkuKey || '-'}</Text>
<Text type="secondary">
{task.provider || '-'} / {task.shopName || task.shopId || '-'}
{providerLabel(task.provider)} / {task.shopName || task.shopId || '-'}
</Text>
</Space>
),
@@ -251,7 +470,7 @@ export default function PlatformFulfillmentPage() {
积分 {task.account.points ?? '-'} · 鱼翅 {task.account.goldBalance ?? '-'}
</Text>
<Text type="secondary">
租约 {task.lease?.status || '-'} · {formatTime(task.lease?.expiresAt)}
租约 {task.lease ? '占用中' : '未占用'} · {task.lease ? leaseExpiresLabel(task.lease.expiresAt) : '-'}
</Text>
</Space>
) : (
@@ -264,8 +483,8 @@ export default function PlatformFulfillmentPage() {
width: 180,
render: (_, task) => (
<Space direction="vertical" size={2}>
<Tag>{task.bindingStatus}</Tag>
<Text>{task.bindTask?.roleName || task.bindTask?.bindPhase || '-'}</Text>
<Tag>{bindingStatusLabel(task.bindingStatus)}</Tag>
<Text>{task.bindTask?.roleName || (task.bindTask?.bindPhase === 'role_ready' ? '角色待确认' : '-')}</Text>
</Space>
),
},
@@ -276,7 +495,7 @@ export default function PlatformFulfillmentPage() {
render: (_, task) => (
<Space direction="vertical" size={4}>
<Tag color={STATUS_COLORS[task.executionStatus] || 'default'}>{statusLabel(task.executionStatus)}</Tag>
<Text type="secondary">兑换:{task.exchangeStatus}</Text>
<Text type="secondary">兑换:{exchangeStatusLabel(task.exchangeStatus)}</Text>
</Space>
),
},
@@ -362,6 +581,14 @@ export default function PlatformFulfillmentPage() {
<Text type="secondary">读取 order_site 人工订单,客户扫码绑定游戏角色,运营使用斗鱼账号人工兑换。</Text>
</div>
<Space wrap>
<Tag>账号租约:{leaseDurationLabel(settings?.leaseDurationMinutes)}</Tag>
<Button
icon={<SettingOutlined />}
disabled={!can('platform_fulfillment:admin')}
onClick={openLeaseSettings}
>
租约设置
</Button>
<Button icon={<LinkOutlined />} disabled={!can('platform_fulfillment:admin')} onClick={() => void openMapping()}>
商品映射
</Button>
@@ -417,43 +644,131 @@ export default function PlatformFulfillmentPage() {
/>
</Card>
<Drawer open={Boolean(selectedId)} width={760} title={selected ? `履约详情 · ${selected.platformOrderId}` : '履约详情'} onClose={() => setSelectedId(null)}>
<Drawer
open={Boolean(selectedId)}
width="min(1080px, 94vw)"
title={selected ? `履约详情 · ${selected.platformOrderId}` : '履约详情'}
extra={
selected ? (
<Space>
<Tag color={STATUS_COLORS[selected.executionStatus] || 'default'}>
{statusLabel(selected.executionStatus)}
</Tag>
<Tag>{exchangeStatusLabel(selected.exchangeStatus)}</Tag>
</Space>
) : null
}
onClose={() => setSelectedId(null)}
>
{detailLoading || !selected ? (
<Text type="secondary">加载中...</Text>
) : (
<Space direction="vertical" size={16} style={{ width: '100%' }}>
{selected.lastError ? <Alert type="warning" showIcon message={selected.lastError} /> : null}
<Descriptions bordered size="small" column={2}>
<Descriptions.Item label="商品" span={2}>
{selected.skuName}
</Descriptions.Item>
<Descriptions.Item label="内部 SKU">{selected.internalSkuKey || '-'}</Descriptions.Item>
<Descriptions.Item label="斗鱼商品">{selected.commodityId || '-'}</Descriptions.Item>
<Descriptions.Item label="订单金额">{money(selected.orderAmountFen)}</Descriptions.Item>
<Descriptions.Item label="所需积分">{selected.requiredPoints ?? '-'}</Descriptions.Item>
<Descriptions.Item label="执行状态">{statusLabel(selected.executionStatus)}</Descriptions.Item>
<Descriptions.Item label="绑定状态">{selected.bindingStatus}</Descriptions.Item>
<Descriptions.Item label="兑换状态">{selected.exchangeStatus}</Descriptions.Item>
<Descriptions.Item label="账号">{selected.account?.nickname || selected.account?.username || '-'}</Descriptions.Item>
</Descriptions>
{selected.issueCode || selected.lastError ? (
<Alert
type={selected.exchangeStatus === 'eligible' ? 'success' : 'warning'}
showIcon
message={selected.issueCode ? issueLabel(selected.issueCode) : '处理提示'}
description={selected.lastError || exchangeStatusHint(selected.exchangeStatus)}
/>
) : exchangeStatusHint(selected.exchangeStatus) ? (
<Alert
type={selected.exchangeStatus === 'eligible' ? 'success' : 'warning'}
showIcon
message={exchangeStatusLabel(selected.exchangeStatus)}
description={exchangeStatusHint(selected.exchangeStatus)}
/>
) : null}
<div
style={{
display: 'grid',
gridTemplateColumns: 'repeat(auto-fit, minmax(360px, 1fr))',
gap: 16,
}}
>
<Card size="small" title="订单与商品">
<Descriptions bordered size="small" column={2}>
<Descriptions.Item label="订单号" span={2}>
{selected.platformOrderId || '-'}
</Descriptions.Item>
<Descriptions.Item label="商品" span={2}>
{selected.skuName || selected.internalSkuKey || '-'}
</Descriptions.Item>
<Descriptions.Item label="内部 SKU" span={2}>
{selected.internalSkuKey || '-'}
</Descriptions.Item>
<Descriptions.Item label="斗鱼商品" span={2}>
{selected.commodityId || '未映射'}
</Descriptions.Item>
<Descriptions.Item label="订单金额">{money(selected.orderAmountFen)}</Descriptions.Item>
<Descriptions.Item label="所需积分">{selected.requiredPoints ?? '-'}</Descriptions.Item>
<Descriptions.Item label="执行状态">{statusLabel(selected.executionStatus)}</Descriptions.Item>
<Descriptions.Item label="绑定状态">{bindingStatusLabel(selected.bindingStatus)}</Descriptions.Item>
<Descriptions.Item label="兑换状态">{exchangeStatusLabel(selected.exchangeStatus)}</Descriptions.Item>
<Descriptions.Item label="处理提示">{issueLabel(selected.issueCode)}</Descriptions.Item>
</Descriptions>
</Card>
<Card size="small" title="账号实时状态">
{selected.account ? (
<Descriptions bordered size="small" column={2}>
<Descriptions.Item label="账号" span={2}>
{selected.account.nickname || selected.account.username}
</Descriptions.Item>
<Descriptions.Item label="CK 状态">
{ckStatusLabel(selected.account.ckCheckStatus)}
</Descriptions.Item>
<Descriptions.Item label="精英宝典">
{eliteOpenedLabel(selected.account.eliteOpened)}
</Descriptions.Item>
<Descriptions.Item label="当前积分">{selected.account.points ?? '-'}</Descriptions.Item>
<Descriptions.Item label="鱼翅余额">{selected.account.goldBalance ?? '-'}</Descriptions.Item>
<Descriptions.Item label="角色绑定">
{bindStatusLabel(selected.account.roleBindStatus)}
</Descriptions.Item>
<Descriptions.Item label="游戏角色">{selected.account.gameName || '-'}</Descriptions.Item>
<Descriptions.Item label="游戏渠道" span={2}>
{selected.account.gameChannel || '-'}
</Descriptions.Item>
<Descriptions.Item label="换绑可用时间" span={2}>
{formatTime(selected.account.roleChangeAvailableAt) || '无冷却'}
</Descriptions.Item>
<Descriptions.Item label="租约到期" span={2}>
{selected.lease ? leaseExpiresLabel(selected.lease.expiresAt) : '-'}
</Descriptions.Item>
</Descriptions>
) : (
<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="尚未分配账号" />
)}
</Card>
</div>
<Card size="small" title="当前操作">
{actionButtons}
</Card>
<Card size="small" title="事件时间线">
<Timeline
items={(detail?.events || []).map((event) => ({
color: event.eventType.includes('failed') ? 'red' : 'blue',
children: (
<Space direction="vertical" size={2}>
<Text strong>{event.eventType}</Text>
<Text type="secondary">
{formatTime(event.createdAt)} · {event.actorType}
{event.actorId ? ` ${event.actorId}` : ''}
</Text>
</Space>
),
}))}
/>
<Card size="small" title={`事件时间线(${detail?.events.length || 0})`}>
<div style={{ maxHeight: 440, overflowY: 'auto', paddingTop: 8 }}>
<Timeline
items={(detail?.events || [])
.slice()
.sort((left, right) => Date.parse(right.createdAt) - Date.parse(left.createdAt))
.slice(0, 50)
.map((event) => ({
color: eventColor(event.eventType),
children: (
<Space direction="vertical" size={3} style={{ maxWidth: 860 }}>
<Text strong>{eventLabel(event.eventType)}</Text>
<Text>{eventDescription(event)}</Text>
<Text type="secondary">
{formatTime(event.createdAt)} · {ACTOR_TYPE_LABELS[event.actorType] || '系统'}
{event.actorId ? ` · 操作人 ${event.actorId}` : ''}
</Text>
</Space>
),
}))}
/>
</div>
</Card>
</Space>
)}
@@ -477,6 +792,44 @@ export default function PlatformFulfillmentPage() {
</Space>
</Modal>
<Modal
open={settingsOpen}
title="账号租约设置"
okText="保存设置"
confirmLoading={savingSettings}
onOk={() => void saveLeaseSettings()}
onCancel={() => setSettingsOpen(false)}
>
<Space direction="vertical" size={16} style={{ width: '100%' }}>
<Segmented
block
value={leaseDurationMode}
onChange={(value) => setLeaseDurationMode(value as 'unlimited' | 'minutes' | 'hours')}
options={[
{ label: '无限制', value: 'unlimited' },
{ label: '按分钟', value: 'minutes' },
{ label: '按小时', value: 'hours' },
]}
/>
{leaseDurationMode !== 'unlimited' ? (
<InputNumber
min={1}
precision={0}
value={leaseDurationValue}
onChange={setLeaseDurationValue}
addonAfter={leaseDurationMode === 'hours' ? '小时' : '分钟'}
style={{ width: '100%' }}
/>
) : null}
<Alert
type="info"
showIcon
message={`当前设置:${leaseDurationLabel(settings?.leaseDurationMinutes)}`}
description="保存后会立即同步当前所有活跃租约。无限制模式不会自动回收,任务完成、释放或取消时仍会正常释放账号。"
/>
</Space>
</Modal>
<Modal open={mappingOpen} title="斗鱼商品映射" width={760} okText="保存映射" onOk={() => void saveMapping()} onCancel={() => setMappingOpen(false)}>
<Space direction="vertical" size={14} style={{ width: '100%' }}>
<Input placeholder="内部 SKU,例如 套装-兔兔白日梦" value={mappingSku} onChange={(event) => setMappingSku(event.target.value)} />