Files
live-hub-py/web/frontend/src/pages/PlatformFulfillmentPage.tsx
T

645 lines
21 KiB
TypeScript

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 type { ColumnsType } from 'antd/es/table';
import { douyuApi, platformFulfillmentApi } from '../api/modules';
import type {
DouyuGoodsItem,
PlatformFulfillmentDetail,
PlatformFulfillmentMapping,
PlatformFulfillmentTask,
} from '../api/modules';
import { getErrorMessage } from '../utils/error';
import { message } from '../utils/antdMessage';
import { formatTime } from '../utils/time';
import { getUser } from '../store/auth';
import { usePermissions } from '../hooks/usePermissions';
const { Text, Title } = Typography;
const STATUS_OPTIONS = [
{ value: '', label: '全部' },
{ value: 'pending_mapping', label: '待映射' },
{ value: 'ready', label: '待分配' },
{ value: 'allocated', label: '已分配' },
{ value: 'waiting_bind', label: '待扫码' },
{ value: 'role_ready', label: '待确认绑定' },
{ value: 'binding_confirming', label: '确认绑定中' },
{ value: 'bound', label: '待兑换' },
{ value: 'manual_required', label: '待人工' },
{ value: 'completed', label: '已完成' },
{ value: 'cancelled', label: '已取消' },
];
const STATUS_COLORS: Record<string, string> = {
pending_mapping: 'orange',
ready: 'blue',
allocated: 'cyan',
waiting_bind: 'gold',
role_ready: 'purple',
binding_confirming: 'processing',
bound: 'green',
manual_required: 'red',
completed: 'success',
cancelled: 'default',
};
function statusLabel(value: string) {
return STATUS_OPTIONS.find((item) => item.value === value)?.label || value;
}
function money(fen: number) {
return `¥${(Number(fen || 0) / 100).toFixed(2)}`;
}
export default function PlatformFulfillmentPage() {
const user = getUser();
const { can } = usePermissions(user);
const [status, setStatus] = useState('');
const [keyword, setKeyword] = useState('');
const [page, setPage] = useState(1);
const [pageSize, setPageSize] = useState(20);
const [rows, setRows] = useState<PlatformFulfillmentTask[]>([]);
const [total, setTotal] = useState(0);
const [loading, setLoading] = useState(false);
const [syncing, setSyncing] = useState(false);
const [selectedId, setSelectedId] = useState<number | null>(null);
const [detail, setDetail] = useState<PlatformFulfillmentDetail | null>(null);
const [detailLoading, setDetailLoading] = useState(false);
const [qrOpen, setQrOpen] = useState(false);
const [mappingOpen, setMappingOpen] = useState(false);
const [mappingSku, setMappingSku] = useState('');
const [mappingGoodsId, setMappingGoodsId] = useState('');
const [mappingPoints, setMappingPoints] = useState<number | null>(null);
const [mappingEnabled, setMappingEnabled] = useState(true);
const [goods, setGoods] = useState<DouyuGoodsItem[]>([]);
const [mappings, setMappings] = useState<PlatformFulfillmentMapping[]>([]);
const loadTasks = useCallback(async () => {
setLoading(true);
try {
const result = await platformFulfillmentApi.listTasks({
status: status || undefined,
keyword: keyword.trim() || undefined,
page,
page_size: pageSize,
});
setRows(result.items);
setTotal(result.pagination.total);
} catch (error) {
message.error(getErrorMessage(error));
} finally {
setLoading(false);
}
}, [keyword, page, pageSize, status]);
const loadDetail = useCallback(async (taskId: number) => {
setDetailLoading(true);
try {
const result = await platformFulfillmentApi.getTask(taskId);
setDetail(result);
} catch (error) {
message.error(getErrorMessage(error));
} finally {
setDetailLoading(false);
}
}, []);
useEffect(() => {
void loadTasks();
}, [loadTasks]);
useEffect(() => {
if (selectedId) void loadDetail(selectedId);
}, [loadDetail, selectedId]);
const selected = detail?.task || null;
const qrValue = selected?.bindTask?.qrUrl || '';
useEffect(() => {
if (qrValue) setQrOpen(true);
}, [qrValue]);
const sync = async () => {
setSyncing(true);
try {
const result = await platformFulfillmentApi.sync(200);
message.success(`同步完成:新增 ${result.created},更新 ${result.updated}`);
await loadTasks();
} catch (error) {
message.error(getErrorMessage(error));
} finally {
setSyncing(false);
}
};
const runTaskAction = async (action: () => Promise<PlatformFulfillmentDetail>) => {
try {
const result = await action();
setDetail(result);
setSelectedId(result.task.id);
await loadTasks();
message.success('操作已完成');
} catch (error) {
message.error(getErrorMessage(error));
}
};
const openMapping = async (task?: PlatformFulfillmentTask) => {
setMappingSku(task?.internalSkuKey || '');
setMappingGoodsId(task?.commodityId || '');
setMappingPoints(task?.requiredPoints ?? null);
setMappingEnabled(true);
setMappingOpen(true);
try {
const [goodsRows, mappingRows] = await Promise.all([
douyuApi.listGoods(),
platformFulfillmentApi.listMappings(task?.internalSkuKey || ''),
]);
setGoods(goodsRows);
setMappings(mappingRows);
} catch (error) {
message.error(getErrorMessage(error));
}
};
const selectGoods = (commodityId: string) => {
const item = goods.find((row) => row.commodity_id === commodityId);
setMappingGoodsId(commodityId);
if (item?.score != null) setMappingPoints(Number(item.score));
};
const saveMapping = async () => {
if (!mappingSku.trim() || !mappingGoodsId) {
message.warning('请填写内部 SKU 并选择斗鱼商品');
return;
}
const item = goods.find((row) => row.commodity_id === mappingGoodsId);
try {
await platformFulfillmentApi.upsertMapping({
internal_sku_key: mappingSku.trim(),
commodity_id: mappingGoodsId,
goods_name: item?.name || '',
required_points: mappingPoints,
enabled: mappingEnabled,
});
message.success('商品映射已保存');
setMappings(await platformFulfillmentApi.listMappings(mappingSku.trim()));
await loadTasks();
} catch (error) {
message.error(getErrorMessage(error));
}
};
const columns: ColumnsType<PlatformFulfillmentTask> = [
{
title: '订单 / 商品',
key: 'order',
width: 280,
render: (_, task) => (
<Space direction="vertical" size={2}>
<Text strong>{task.platformOrderId || `#${task.sourceOrderId}`}</Text>
<Text>{task.skuName || task.internalSkuKey || '-'}</Text>
<Text type="secondary">
{task.provider || '-'} / {task.shopName || task.shopId || '-'}
</Text>
</Space>
),
},
{
title: '商品映射',
key: 'mapping',
width: 230,
render: (_, task) => (
<Space direction="vertical" size={2}>
<Text>{task.commodityId || '未映射'}</Text>
<Text type="secondary">
{task.requiredPoints != null ? `${task.requiredPoints} 积分` : '价格未知'}
</Text>
</Space>
),
},
{
title: '订单金额',
dataIndex: 'orderAmountFen',
width: 110,
render: (value: number) => money(value),
},
{
title: '账号',
key: 'account',
width: 190,
render: (_, task) =>
task.account ? (
<Space direction="vertical" size={2}>
<Text>{task.account.nickname || task.account.username}</Text>
<Text type="secondary">
积分 {task.account.points ?? '-'} · 鱼翅 {task.account.goldBalance ?? '-'}
</Text>
<Text type="secondary">
租约 {task.lease?.status || '-'} · {formatTime(task.lease?.expiresAt)}
</Text>
</Space>
) : (
<Text type="secondary">未分配</Text>
),
},
{
title: '绑定',
key: 'binding',
width: 180,
render: (_, task) => (
<Space direction="vertical" size={2}>
<Tag>{task.bindingStatus}</Tag>
<Text>{task.bindTask?.roleName || task.bindTask?.bindPhase || '-'}</Text>
</Space>
),
},
{
title: '状态',
key: 'status',
width: 150,
render: (_, task) => (
<Space direction="vertical" size={4}>
<Tag color={STATUS_COLORS[task.executionStatus] || 'default'}>
{statusLabel(task.executionStatus)}
</Tag>
<Text type="secondary">兑换:{task.exchangeStatus}</Text>
</Space>
),
},
{
title: '更新时间',
dataIndex: 'updatedAt',
width: 160,
render: (value: string) => formatTime(value),
},
{
title: '操作',
key: 'actions',
width: 330,
render: (_, task) => (
<Space wrap>
<Button size="small" onClick={() => setSelectedId(task.id)}>
详情
</Button>
{task.executionStatus === 'pending_mapping' ? (
<Button
size="small"
type="primary"
icon={<LinkOutlined />}
disabled={!can('platform_fulfillment:admin')}
onClick={() => void openMapping(task)}
>
配置映射
</Button>
) : null}
{task.executionStatus === 'ready' ? (
<Button
size="small"
type="primary"
icon={<UserSwitchOutlined />}
onClick={() =>
void runTaskAction(() => platformFulfillmentApi.allocate(task.id))
}
>
自动选号
</Button>
) : null}
{task.executionStatus === 'allocated' ? (
<Button
size="small"
type="primary"
icon={<QrcodeOutlined />}
onClick={() =>
void runTaskAction(() => platformFulfillmentApi.startBinding(task.id))
}
>
生成二维码
</Button>
) : null}
{['waiting_bind', 'binding_confirming'].includes(task.executionStatus) ? (
<Button
size="small"
icon={<ReloadOutlined />}
onClick={() =>
void runTaskAction(() => platformFulfillmentApi.refreshBinding(task.id))
}
>
刷新绑定
</Button>
) : null}
{task.executionStatus === 'role_ready' ? (
<Button
size="small"
type="primary"
icon={<CheckCircleOutlined />}
onClick={() =>
void runTaskAction(() => platformFulfillmentApi.confirmBinding(task.id))
}
>
确认绑定
</Button>
) : null}
{task.executionStatus === 'bound' ? (
<>
<Button
size="small"
icon={<SyncOutlined />}
onClick={() =>
void runTaskAction(() =>
platformFulfillmentApi.refreshEligibility(task.id),
)
}
>
刷新兑换资格
</Button>
<Button
size="small"
type="primary"
disabled={task.exchangeStatus !== 'eligible'}
onClick={() =>
void runTaskAction(() =>
platformFulfillmentApi.complete(task.id, '人工兑换完成'),
)
}
>
完成
</Button>
</>
) : null}
</Space>
),
},
];
const actionButtons = selected ? (
<Space wrap>
{selected.bindTask?.qrUrl ? (
<Button icon={<QrcodeOutlined />} onClick={() => setQrOpen(true)}>
查看二维码
</Button>
) : null}
{selected.account ? (
<Button
onClick={() =>
void runTaskAction(() => platformFulfillmentApi.release(selected.id))
}
>
释放账号
</Button>
) : null}
{selected.executionStatus !== 'completed' &&
selected.executionStatus !== 'cancelled' ? (
<Button
danger
onClick={() =>
void runTaskAction(() =>
platformFulfillmentApi.cancel(selected.id, '运营取消'),
)
}
>
取消
</Button>
) : null}
</Space>
) : null;
return (
<Space direction="vertical" size={16} style={{ width: '100%' }}>
<Card size="small">
<Space align="start" style={{ width: '100%', justifyContent: 'space-between' }} wrap>
<div>
<Title level={4} style={{ margin: 0 }}>
直播账号履约工作台
</Title>
<Text type="secondary">
读取 order_site 人工订单,客户扫码绑定游戏角色,运营使用斗鱼账号人工兑换。
</Text>
</div>
<Space wrap>
<Button icon={<LinkOutlined />} disabled={!can('platform_fulfillment:admin')} onClick={() => void openMapping()}>
商品映射
</Button>
<Button type="primary" loading={syncing} icon={<SyncOutlined />} onClick={() => void sync()}>
同步待履约订单
</Button>
</Space>
</Space>
</Card>
<Card size="small">
<Space wrap style={{ marginBottom: 16 }}>
<Input.Search
allowClear
placeholder="订单号 / SKU / 商品 ID"
value={keyword}
onChange={(event) => {
setKeyword(event.target.value);
setPage(1);
}}
style={{ width: 300 }}
/>
<Select
value={status}
options={STATUS_OPTIONS}
onChange={(value) => {
setStatus(value);
setPage(1);
}}
style={{ width: 150 }}
/>
<Button icon={<ReloadOutlined />} onClick={() => void loadTasks()}>
刷新
</Button>
</Space>
<Table<PlatformFulfillmentTask>
rowKey="id"
loading={loading}
columns={columns}
dataSource={rows}
scroll={{ x: 1500 }}
pagination={{
current: page,
pageSize,
total,
showSizeChanger: true,
onChange: (nextPage, nextSize) => {
setPage(nextPage);
setPageSize(nextSize);
},
}}
locale={{ emptyText: <Empty description="暂无直播账号履约任务" /> }}
/>
</Card>
<Drawer
open={Boolean(selectedId)}
width={760}
title={selected ? `履约详情 · ${selected.platformOrderId}` : '履约详情'}
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>
<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>
</Space>
)}
</Drawer>
<Modal
open={qrOpen && Boolean(qrValue)}
title="客户扫码绑定游戏角色"
footer={null}
onCancel={() => setQrOpen(false)}
>
<Space direction="vertical" align="center" style={{ width: '100%' }}>
{qrValue ? <QRCode value={qrValue} size={260} /> : null}
<Text type="secondary">
请客户使用对应游戏平台扫码。二维码只用于当前履约作业。
</Text>
<Button
icon={<CopyOutlined />}
onClick={() => {
void navigator.clipboard.writeText(qrValue).then(
() => message.success('二维码链接已复制'),
() => message.error('复制失败'),
);
}}
>
复制二维码链接
</Button>
</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)}
/>
<Select
showSearch
optionFilterProp="label"
placeholder="选择斗鱼精英宝典商品"
value={mappingGoodsId || undefined}
onChange={selectGoods}
options={goods.map((item) => ({
value: item.commodity_id,
label: `${item.name || item.commodity_id} · ${item.score ?? '-'} 积分`,
}))}
style={{ width: '100%' }}
/>
<Space>
<Text>所需积分</Text>
<InputNumber min={0} value={mappingPoints} onChange={(value) => setMappingPoints(value)} />
<Text>启用</Text>
<Switch checked={mappingEnabled} onChange={setMappingEnabled} />
</Space>
<Tabs
items={[
{
key: 'current',
label: '当前映射',
children: (
<Table<PlatformFulfillmentMapping>
rowKey="id"
size="small"
pagination={false}
dataSource={mappings}
columns={[
{ title: '内部 SKU', dataIndex: 'internalSkuKey' },
{ title: '商品', dataIndex: 'goodsName' },
{ title: '商品 ID', dataIndex: 'commodityId' },
{ title: '积分', dataIndex: 'requiredPoints' },
{
title: '状态',
dataIndex: 'enabled',
render: (value: boolean) => (
<Tag color={value ? 'green' : 'default'}>
{value ? '启用' : '停用'}
</Tag>
),
},
]}
/>
),
},
]}
/>
</Space>
</Modal>
</Space>
);
}