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

2150 lines
83 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { useCallback, useEffect, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import dayjs from 'dayjs';
import type { Dayjs } from 'dayjs';
import { Alert, Button, Card, Col, DatePicker, Descriptions, Drawer, Empty, Input, InputNumber, Modal, QRCode, Row, Segmented, Select, Space, Switch, Table, Tabs, Tag, Timeline, Typography } from 'antd';
import { CheckCircleOutlined, CopyOutlined, CreditCardOutlined, DownloadOutlined, GiftOutlined, LinkOutlined, QrcodeOutlined, ReloadOutlined, SettingOutlined, ShoppingOutlined, SyncOutlined, UndoOutlined, UserSwitchOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { douyuApi, platformFulfillmentApi } from '../api/modules';
import type { DouyuGoodsItem, DouyuTaskItem, PlatformFulfillmentDetail, PlatformFulfillmentMapping, PlatformFulfillmentSettings, PlatformFulfillmentTask } from '../api/modules';
import ExchangeResultImage from '../components/ExchangeResultImage';
import { copyImageToClipboard, fetchExchangeImageBlob, getExchangeImage, isExchangeTask } from '../utils/exchangeImage';
import { TASK_STATUS_COLORS, TASK_STATUS_LABELS, taskQrUrl } from './douyu-tasks/config';
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',
};
const COLLAB_STATUS_LABELS: Record<string, string> = {
incomplete: '待补资料',
to_recharge: '待充值',
recharged: '已充值',
scripted: '已上脚本',
done: '抢购成功',
points_error: '积分异常',
role_error: '账号角色异常',
failed: '抢购失败',
void: '已作废',
};
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: '已达限兑上限',
not_available: '商品当前不可兑换',
check_failed: '资格查询失败',
manual_done: '人工兑换完成',
};
const SALE_MODE_LABELS: Record<string, string> = {
presale: '预售',
direct: '直接兑换',
manual: '人工',
unknown: '未分类',
};
const AVAILABILITY_LABELS: Record<string, string> = {
waiting_release: '待开放',
available: '可兑换',
sold_out: '已售罄',
ended: '已结束',
unknown: '未知',
};
const MANUAL_REASON_LABELS: Record<string, string> = {
points_short: '积分不足',
elite_not_opened: '宝典未开通',
limit_reached: '已达限兑',
binding_failed: '绑定异常',
account_cooldown: '账号冷却',
other_manual: '其他人工',
};
const QUEUE_BUCKET_OPTIONS = [
{ value: 'current', label: '当前待办' },
{ value: 'presale_waiting', label: '预售待开放' },
{ value: 'ready_for_fulfillment', label: '可履约' },
{ value: 'needs_action', label: '需要人工' },
{ value: 'completed', label: '已完成' },
{ value: 'cancelled', label: '已取消' },
];
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: '提交角色绑定确认',
binding_failed: '游戏角色绑定失败',
binding_reset: '重置角色资料和绑定记录',
binding_stale_role_ignored: '忽略账号旧角色',
eligibility_check_failed: '兑换资格查询失败',
exchange_eligibility_checked: '刷新兑换资格',
manual_exchange_completed: '人工兑换完成',
marked_manual_required: '转人工处理',
released_to_manual: '释放账号并转人工',
douyu_operation_started: '斗鱼操作已提交',
douyu_operation_succeeded: '斗鱼操作成功',
douyu_operation_failed: '斗鱼操作失败',
douyu_operation_stopped: '斗鱼操作已停止',
task_cancelled: '任务已取消',
task_restored: '恢复已取消任务',
};
const ISSUE_LABELS: Record<string, string> = {
mapping_missing: '商品映射缺失',
no_eligible_account: '没有可分配账号',
points_short: '积分不足',
elite_not_opened: '精英宝典未开通',
commodity_limit_reached: '商品已达限兑上限',
commodity_not_open: '商品限时兑换未开始',
commodity_expired: '商品限时兑换已结束',
commodity_no_stock: '商品当前无库存',
commodity_not_offered: '商品当前未上架',
commodity_status_unknown: '商品资格状态未知',
commodity_not_exchangeable: '商品当前不可兑换',
eligibility_check_failed: '资格查询失败',
binding_failed: '绑定失败',
account_role_cooldown: '斗鱼账号仍在换绑冷却期',
customer_role_cooldown: '游戏角色仍在换绑冷却期',
lease_expired: '账号租约已过期',
manual_required: '需要人工处理',
source_cancelled: '来源订单已取消',
};
const DOUYU_ACTION_LABELS: Record<string, string> = {
query_elite_status: '查询精英宝典',
create_elite_qr: '开通精英宝典',
create_gold_qr: '充值鱼翅',
donate_elite_gift: '赠送精英令',
exchange_goods: '兑换订单皮肤',
};
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 collabStatusLabel(value: string) {
return COLLAB_STATUS_LABELS[value] || 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 === 'not_available') 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') || value.includes('released_to_manual')) return 'orange';
if (
value.includes('completed') ||
value.includes('allocated') ||
value.includes('restored') ||
value.includes('succeeded')
) {
return 'green';
}
if (value.includes('douyu_operation_failed') || value.includes('douyu_operation_stopped')) {
return value.includes('stopped') ? 'orange' : 'red';
}
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.goodsName || 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 === 'released_to_manual') {
return `转人工原因:${String(detail.reason || '以外部单协作人工处理为准')}`;
}
if (event.eventType === 'task_cancelled') {
return `取消原因:${String(detail.reason || '人工取消')}`;
}
if (event.eventType === 'task_restored') {
const status = String(detail.restoredExecutionStatus || '');
return `恢复原因:${String(detail.reason || '误取消恢复')};恢复后状态:${statusLabel(status)}`;
}
if (event.eventType === 'douyu_operation_started') {
return `${String(detail.taskLabel || detail.taskType || '斗鱼操作')};批次 ${String(detail.batchId || '-')}`;
}
if (
event.eventType === 'douyu_operation_succeeded' ||
event.eventType === 'douyu_operation_failed' ||
event.eventType === 'douyu_operation_stopped'
) {
return `${String(detail.taskLabel || detail.taskType || '斗鱼操作')}:${String(detail.message || detail.status || '-')}`;
}
if (event.eventType === 'binding_started') return '已生成客户绑定二维码';
if (event.eventType === 'binding_confirm_started') return '已提交游戏角色绑定确认';
if (event.eventType === 'binding_failed') {
return String(detail.rawError || issueLabel(String(detail.issueCode || 'binding_failed')));
}
if (event.eventType === 'binding_reset') {
return `${String(detail.reason || '客服重置角色绑定')};客户需重新填写角色资料`;
}
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) : '无限制';
}
function canResetBinding(task: PlatformFulfillmentTask) {
if (task.executionStatus === 'completed' || task.executionStatus === 'cancelled') {
return false;
}
return task.bindingStatus === 'failed';
}
function canRefreshBindingQr(task: PlatformFulfillmentTask) {
if (!task.account) return false;
return !['role_ready', 'bound', 'completed', 'cancelled'].includes(task.executionStatus);
}
export default function PlatformFulfillmentPage() {
const user = getUser();
const navigate = useNavigate();
const { can } = usePermissions(user);
const [queueBucket, setQueueBucket] = useState('current');
const [saleModeFilter, setSaleModeFilter] = 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 [collabSyncing, setCollabSyncing] = useState(false);
const [rowCollabSyncingId, setRowCollabSyncingId] = useState<number | null>(null);
const [allocatingTaskId, setAllocatingTaskId] = useState<number | null>(null);
const [restoreTarget, setRestoreTarget] = useState<PlatformFulfillmentTask | null>(null);
const [restoreReason, setRestoreReason] = useState('');
const [restoring, setRestoring] = useState(false);
const [manualReleaseTarget, setManualReleaseTarget] = useState<PlatformFulfillmentTask | null>(null);
const [manualReleaseReason, setManualReleaseReason] = useState('');
const [manualReleasing, setManualReleasing] = useState(false);
const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
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 [mappingEditingId, setMappingEditingId] = useState<number | null>(null);
const [mappingCampaignKey, setMappingCampaignKey] = useState('douyu-current');
const [mappingCampaignName, setMappingCampaignName] = useState('');
const [mappingGoodsId, setMappingGoodsId] = useState('');
const [mappingGoodsName, setMappingGoodsName] = useState('');
const [mappingPoints, setMappingPoints] = useState<number | null>(null);
const [mappingEnabled, setMappingEnabled] = useState(true);
const [mappingSaleMode, setMappingSaleMode] = useState<'presale' | 'direct' | 'manual' | 'unknown'>('unknown');
const [mappingAvailableFrom, setMappingAvailableFrom] = useState<Dayjs | null>(null);
const [mappingAvailableUntil, setMappingAvailableUntil] = useState<Dayjs | null>(null);
const [mappingFilterMode, setMappingFilterMode] = useState('');
const [mappingIncludeArchived, setMappingIncludeArchived] = useState(false);
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 [completedReleaseDelay, setCompletedReleaseDelay] = useState<number | null>(30);
const [manualCompletedReleaseDelay, setManualCompletedReleaseDelay] = useState<number | null>(120);
const [presaleWaitingReleaseTtl, setPresaleWaitingReleaseTtl] = useState<number | null>(null);
const [manualRequiredLeaseTtl, setManualRequiredLeaseTtl] = useState<number | null>(null);
const [orderMatchStartedAt, setOrderMatchStartedAt] = useState<Dayjs | null>(null);
const [savingSettings, setSavingSettings] = useState(false);
const [douyuActionLoading, setDouyuActionLoading] = useState('');
const [douyuActionType, setDouyuActionType] = useState('');
const [douyuActionBatchId, setDouyuActionBatchId] = useState('');
const [douyuActionTask, setDouyuActionTask] = useState<DouyuTaskItem | null>(null);
const [exchangeImageViewer, setExchangeImageViewer] = useState<{
url: string;
title: string;
} | null>(null);
const exchangeImageSaveAttempts = useRef(new Set<number>());
const [goldAmount, setGoldAmount] = useState(30);
const [giftCount, setGiftCount] = useState(1);
const loadTasks = useCallback(async (silent = false) => {
if (!silent) setLoading(true);
try {
const queueBackedStatus = queueBucket === 'current'
? 'unfinished'
: (['completed', 'cancelled'].includes(queueBucket) ? queueBucket : undefined);
const backendBucket = ['presale_waiting', 'ready_for_fulfillment', 'needs_action'].includes(queueBucket)
? queueBucket
: undefined;
const result = await platformFulfillmentApi.listTasks({
status: queueBackedStatus,
queue_bucket: backendBucket,
sale_mode: saleModeFilter || undefined,
keyword: keyword.trim() || undefined,
page,
page_size: pageSize,
});
setRows(result.items);
setTotal(result.pagination.total);
} catch (error) {
if (!silent) message.error(getErrorMessage(error));
} finally {
if (!silent) setLoading(false);
}
}, [keyword, page, pageSize, queueBucket, saleModeFilter]);
const loadDetail = useCallback(async (taskId: number, silent = false) => {
if (!silent) setDetailLoading(true);
try {
const result = await platformFulfillmentApi.getTask(taskId);
setDetail(result);
} catch (error) {
if (!silent) message.error(getErrorMessage(error));
} finally {
if (!silent) setDetailLoading(false);
}
}, []);
useEffect(() => {
void loadTasks();
}, [loadTasks]);
useEffect(() => {
const timer = window.setInterval(() => {
if (document.visibilityState === 'visible') void loadTasks(true);
}, 5000);
return () => window.clearInterval(timer);
}, [loadTasks]);
useEffect(() => {
void platformFulfillmentApi
.getSettings()
.then(setSettings)
.catch((error) => message.error(getErrorMessage(error)));
}, []);
useEffect(() => {
if (selectedId) void loadDetail(selectedId);
}, [loadDetail, selectedId]);
useEffect(() => {
if (!selectedId) return;
const timer = window.setInterval(() => {
if (document.visibilityState === 'visible') void loadDetail(selectedId, true);
}, 3000);
return () => window.clearInterval(timer);
}, [loadDetail, selectedId]);
useEffect(() => {
if (!douyuActionBatchId) return;
let stopped = false;
const loadActionTask = async () => {
try {
const items = await douyuApi.listTasks('elite', douyuActionBatchId);
if (!stopped) setDouyuActionTask(items[0] || null);
} catch {
// 保持当前任务快照,下一轮继续。
}
};
void loadActionTask();
const timer = window.setInterval(() => {
if (document.visibilityState === 'visible') void loadActionTask();
}, 2000);
return () => {
stopped = true;
window.clearInterval(timer);
};
}, [douyuActionBatchId]);
const selected = detail?.task || null;
const selectedExchangeTaskId = selected?.exchangeTaskId ?? null;
const selectedExchangeImageKey = selected?.exchangeResultImage?.objectKey || '';
const qrValue = selected?.bindTask?.qrUrl || '';
const douyuActionQrValue = douyuActionTask ? taskQrUrl(douyuActionTask) : '';
useEffect(() => {
if (qrValue) setQrOpen(true);
}, [qrValue]);
useEffect(() => {
if (
!selectedId
|| !selectedExchangeTaskId
|| selectedExchangeImageKey
|| exchangeImageSaveAttempts.current.has(selectedExchangeTaskId)
) {
return;
}
exchangeImageSaveAttempts.current.add(selectedExchangeTaskId);
void douyuApi.getTask(selectedExchangeTaskId)
.then(async (task) => {
if (task.status !== 'success' || !isExchangeTask(task)) return false;
await getExchangeImage(task);
return true;
})
.then((saved) => {
if (saved) void loadDetail(selectedId, true);
})
.catch(() => {
// 图片补存失败不影响履约详情;下次重新打开详情时会再次尝试。
exchangeImageSaveAttempts.current.delete(selectedExchangeTaskId);
});
}, [selectedId, selectedExchangeTaskId, selectedExchangeImageKey, loadDetail]);
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 performCollabSync = async (taskIds: number[], rowTaskId?: number) => {
if (rowTaskId) {
setRowCollabSyncingId(rowTaskId);
} else {
setCollabSyncing(true);
}
try {
const result = await platformFulfillmentApi.syncCollab(taskIds);
const syncedOrderNo =
result.items.find((item) => item.action === 'created' || item.action === 'updated')?.orderNo || '';
const summary = `外部协作同步完成:新增 ${result.created},更新 ${result.updated}${
taskIds.length === 1 && syncedOrderNo ? `,订单 ${syncedOrderNo}` : ''
}`;
if (result.failed || result.skipped) {
message.warning(`${summary},跳过 ${result.skipped},失败 ${result.failed}`);
const problems = result.items.filter(
(item) => item.action === 'failed' || item.action === 'skipped',
);
Modal.warning({
title: '部分履约任务未同步',
width: 560,
content: (
<Space direction="vertical" size={4}>
{problems.slice(0, 20).map((item) => (
<Text key={`${item.taskId}-${item.action}`} type="secondary">
#{item.taskId}:{item.reason || '未同步'}
</Text>
))}
{problems.length > 20 ? (
<Text type="secondary">另有 {problems.length - 20} 条未显示</Text>
) : null}
</Space>
),
});
} else {
message.success(summary);
}
if (!rowTaskId) setSelectedRowKeys([]);
await loadTasks();
if (selectedId) await loadDetail(selectedId, true);
} catch (error) {
message.error(getErrorMessage(error));
} finally {
if (rowTaskId) {
setRowCollabSyncingId(null);
} else {
setCollabSyncing(false);
}
}
};
const syncCollab = async () => {
const taskIds = selectedRowKeys.map(Number).filter((value) => Number.isInteger(value));
if (taskIds.length === 0) {
message.warning('请先勾选要同步的履约任务');
return;
}
await performCollabSync(taskIds);
};
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 requestAllocation = async (task: PlatformFulfillmentTask) => {
if (allocatingTaskId !== null) return;
setAllocatingTaskId(task.id);
try {
const result = await platformFulfillmentApi.allocate(task.id);
setDetail(result);
setSelectedId(result.task.id);
await loadTasks();
if (result.allocationQueued) {
message.info('选号请求已提交,后台完成后会自动刷新');
} else {
message.info('该任务已在选号队列中或已经分配,请稍候刷新');
}
} catch (error) {
message.error(getErrorMessage(error));
} finally {
setAllocatingTaskId(null);
}
};
const resetBinding = (task: PlatformFulfillmentTask) => {
Modal.confirm({
title: '重置角色资料和绑定记录?',
content:
'将清空本订单已填写的游戏角色、旧二维码和绑定失败状态,保留当前账号与租约。客户需要重新打开领取链接并填写角色资料。平台换绑冷却不会被绕过。',
okText: '确认重置',
okButtonProps: { danger: true },
cancelText: '取消',
onOk: () =>
runTaskAction(() =>
platformFulfillmentApi.resetBinding(task.id, '客服重置角色资料和绑定记录'),
),
});
};
const cancelTask = (task: PlatformFulfillmentTask) => {
Modal.confirm({
title: '确认取消履约任务?',
content:
'取消后会立即停止当前绑定或兑换任务,释放已占用的斗鱼账号,并通知订单侧更新为已取消。若属误操作,仅超级管理员可核对来源订单后恢复。',
okText: '确认取消并释放账号',
okButtonProps: { danger: true },
cancelText: '返回',
onOk: () =>
runTaskAction(() =>
platformFulfillmentApi.cancel(task.id, '运营取消并释放账号'),
),
});
};
const restoreTask = async () => {
if (!restoreTarget) return;
const reason = restoreReason.trim();
if (reason.length < 2) {
message.warning('请填写恢复原因');
return;
}
setRestoring(true);
try {
const result = await platformFulfillmentApi.restore(restoreTarget.id, reason);
setDetail(result);
setSelectedId(result.task.id);
setRestoreTarget(null);
setRestoreReason('');
await loadTasks();
message.success('任务已恢复并重新进入履约队列');
} catch (error) {
message.error(getErrorMessage(error));
} finally {
setRestoring(false);
}
};
const releaseTaskToManual = async () => {
if (!manualReleaseTarget) return;
const reason = manualReleaseReason.trim();
if (reason.length < 2) {
message.warning('请填写转人工原因');
return;
}
setManualReleasing(true);
try {
const result = await platformFulfillmentApi.releaseToManual(
manualReleaseTarget.id,
reason,
);
setDetail(result);
setSelectedId(result.task.id);
setManualReleaseTarget(null);
setManualReleaseReason('');
await loadTasks();
message.success('账号已释放,任务已转人工处理');
} catch (error) {
message.error(getErrorMessage(error));
} finally {
setManualReleasing(false);
}
};
const runDouyuAccountAction = async (taskType: string) => {
if (!selected?.account) {
message.warning('当前履约任务还没有分配斗鱼账号');
return;
}
if (!can('douyu:task')) {
message.warning('当前账号没有斗鱼任务执行权限');
return;
}
if (taskType === 'exchange_goods' && !selected.commodityId) {
message.warning('当前订单还没有配置斗鱼商品映射');
return;
}
const payload: Record<string, unknown> = {};
if (taskType === 'create_gold_qr') payload.amount = Math.max(1, Number(goldAmount) || 1);
if (taskType === 'donate_elite_gift') payload.gift_count = Math.max(1, Number(giftCount) || 1);
if (taskType === 'exchange_goods') payload.commodity_id = selected.commodityId;
setDouyuActionLoading(taskType);
setDouyuActionTask(null);
try {
const result = await douyuApi.createTasks({
account_ids: [selected.account.id],
task_type: taskType,
handbook_scope: 'elite',
concurrency: 1,
payload,
platform_task_id: selected.id,
});
setDouyuActionType(taskType);
setDouyuActionBatchId(result.batch_id);
message.success(`${DOUYU_ACTION_LABELS[taskType] || '斗鱼任务'}已提交`);
if (taskType === 'exchange_goods' && selectedId) {
await loadDetail(selectedId, true);
await loadTasks(true);
}
} catch (error) {
message.error(getErrorMessage(error));
if (taskType === 'exchange_goods') {
if (selectedId) await loadDetail(selectedId, true);
await loadTasks(true);
}
} finally {
setDouyuActionLoading('');
}
};
const closeDouyuAction = () => {
setDouyuActionBatchId('');
setDouyuActionTask(null);
if (selectedId) void loadDetail(selectedId, true);
void loadTasks();
};
const copyExchangeImageViewer = async (url = exchangeImageViewer?.url) => {
if (!url) return;
try {
const blob = await fetchExchangeImageBlob(url);
await copyImageToClipboard(blob);
message.success('兑换结果图片已复制');
} catch (error) {
message.error(`复制兑换结果图片失败:${getErrorMessage(error)}`);
}
};
const downloadExchangeImageViewer = (
url = exchangeImageViewer?.url,
title = exchangeImageViewer?.title,
) => {
if (!url) return;
const link = document.createElement('a');
link.href = url;
link.download = `${title || '斗鱼兑换结果'}.png`;
link.click();
};
const resetMappingForm = (task?: PlatformFulfillmentTask) => {
setMappingEditingId(null);
setMappingSku(task?.internalSkuKey || '');
setMappingCampaignKey(task?.campaignKey || 'douyu-current');
setMappingCampaignName(task?.campaignName || '');
setMappingGoodsId(task?.commodityId || '');
setMappingGoodsName('');
setMappingPoints(task?.requiredPoints ?? null);
setMappingEnabled(true);
setMappingSaleMode(task?.saleMode || 'unknown');
setMappingAvailableFrom(task?.offerAvailableFrom ? dayjs(task.offerAvailableFrom) : null);
setMappingAvailableUntil(task?.offerAvailableUntil ? dayjs(task.offerAvailableUntil) : null);
};
const loadMappingRows = async (
keyword = mappingSku.trim(),
mode = mappingFilterMode,
includeArchived = mappingIncludeArchived,
) => {
const rows = await platformFulfillmentApi.listMappings({
keyword,
sale_mode: mode || undefined,
include_archived: includeArchived,
});
setMappings(rows);
};
const openMapping = async (task?: PlatformFulfillmentTask) => {
resetMappingForm(task);
setMappingOpen(true);
setMappingGoodsLoading(true);
try {
const [goodsRows, mappingRows] = await Promise.all([
douyuApi.listLiveGoods(),
platformFulfillmentApi.listMappings({
keyword: task?.internalSkuKey || '',
sale_mode: mappingFilterMode || undefined,
include_archived: mappingIncludeArchived,
}),
]);
setGoods(goodsRows);
setMappings(mappingRows);
if (goodsRows.length === 0) {
message.warning('斗鱼活动商品为空,请稍后刷新商品列表');
}
} catch (error) {
message.error(getErrorMessage(error));
} finally {
setMappingGoodsLoading(false);
}
};
const editMapping = (row: PlatformFulfillmentMapping) => {
setMappingEditingId(row.id);
setMappingSku(row.internalSkuKey);
setMappingCampaignKey(row.campaignKey || 'douyu-current');
setMappingCampaignName(row.campaignName || '');
setMappingGoodsId(row.commodityId);
setMappingGoodsName(row.goodsName);
setMappingPoints(row.requiredPoints);
setMappingEnabled(row.enabled);
setMappingSaleMode(row.saleMode);
setMappingAvailableFrom(row.availableFrom ? dayjs(row.availableFrom) : null);
setMappingAvailableUntil(row.availableUntil ? dayjs(row.availableUntil) : null);
};
const runMappingAction = (
row: PlatformFulfillmentMapping,
action: 'enable' | 'disable' | 'archive' | 'restore',
) => {
const label = {
enable: '启用',
disable: '停用',
archive: '归档',
restore: '恢复',
}[action];
Modal.confirm({
title: `${label}映射`,
content: `${row.internalSkuKey} / ${row.campaignKey}`,
onOk: async () => {
try {
await platformFulfillmentApi.mappingAction(row.id, action);
message.success(`映射已${label}`);
await loadMappingRows();
await loadTasks();
} catch (error) {
message.error(getErrorMessage(error));
}
},
});
};
const removeMapping = (row: PlatformFulfillmentMapping) => {
Modal.confirm({
title: '删除映射',
content: row.affectedTasks > 0
? `该映射还有 ${row.affectedTasks} 个关联任务,只能归档。`
: '映射删除后不可恢复。',
okButtonProps: { danger: true },
onOk: async () => {
try {
await platformFulfillmentApi.deleteMapping(row.id);
message.success('映射已删除');
await loadMappingRows();
} catch (error) {
message.error(getErrorMessage(error));
}
},
});
};
const reloadMappingGoods = async () => {
setMappingGoodsLoading(true);
try {
const rows = await douyuApi.listLiveGoods();
setGoods(rows);
if (rows.length === 0) {
message.warning('斗鱼活动商品为空,请稍后重试');
} else {
message.success(`已加载 ${rows.length} 个斗鱼活动商品`);
}
} catch (error) {
message.error(getErrorMessage(error));
} finally {
setMappingGoodsLoading(false);
}
};
const selectGoods = (commodityId: string) => {
const item = goods.find((row) => row.commodity_id === commodityId);
setMappingGoodsId(commodityId);
setMappingGoodsName(item?.name || '');
if (item?.score != null) setMappingPoints(Number(item.score));
};
const saveMapping = async () => {
if (!mappingSku.trim() || !mappingCampaignKey.trim() || !mappingGoodsId || !mappingSaleMode) {
message.warning('请填写内部 SKU、活动批次、销售模式并选择斗鱼商品');
return;
}
if (mappingSaleMode === 'unknown') {
message.warning('请选择预售、直接兑换或人工销售模式');
return;
}
const item = goods.find((row) => row.commodity_id === mappingGoodsId);
try {
const payload = {
internal_sku_key: mappingSku.trim(),
campaign_key: mappingCampaignKey.trim(),
campaign_name: mappingCampaignName.trim(),
commodity_id: mappingGoodsId,
goods_name: item?.name || mappingGoodsName,
required_points: mappingPoints,
sale_mode: mappingSaleMode,
available_from: mappingAvailableFrom?.toISOString() || null,
available_until: mappingAvailableUntil?.toISOString() || null,
enabled: mappingEnabled,
};
if (mappingEditingId) {
await platformFulfillmentApi.updateMapping(mappingEditingId, payload);
} else {
await platformFulfillmentApi.createMapping(payload);
}
message.success('商品映射已保存');
resetMappingForm();
await loadMappingRows();
await loadTasks();
} catch (error) {
message.error(getErrorMessage(error));
}
};
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);
}
setOrderMatchStartedAt(
settings?.orderMatchStartedAt ? dayjs(settings.orderMatchStartedAt) : null,
);
setCompletedReleaseDelay(settings?.completedReleaseDelayMinutes ?? 30);
setManualCompletedReleaseDelay(
settings?.manualCompletedReleaseDelayMinutes ?? 120,
);
setPresaleWaitingReleaseTtl(
settings?.presaleWaitingReleaseTtlMinutes ?? null,
);
setManualRequiredLeaseTtl(
settings?.manualRequiredLeaseTtlMinutes ?? null,
);
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;
}
if (!orderMatchStartedAt) {
message.warning('请选择订单匹配起算时间');
return;
}
setSavingSettings(true);
try {
const result = await platformFulfillmentApi.updateSettings({
leaseDurationMinutes: minutes,
completedReleaseDelayMinutes: completedReleaseDelay,
manualCompletedReleaseDelayMinutes: manualCompletedReleaseDelay,
presaleWaitingReleaseTtlMinutes: presaleWaitingReleaseTtl,
manualRequiredLeaseTtlMinutes: manualRequiredLeaseTtl,
orderMatchStartedAt: orderMatchStartedAt.toISOString(),
});
setSettings(result);
setSettingsOpen(false);
message.success('履约同步设置已更新');
if (selectedId) await loadDetail(selectedId);
await loadTasks();
} catch (error) {
message.error(getErrorMessage(error));
} finally {
setSavingSettings(false);
}
};
const columns: ColumnsType<PlatformFulfillmentTask> = [
{
title: '任务 ID',
dataIndex: 'id',
key: 'id',
width: 100,
fixed: 'left',
render: (value: number) => (
<Text copyable={{ text: String(value) }}>#{value}</Text>
),
},
{
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">
{providerLabel(task.provider)} / {task.shopName || task.shopId || '-'}
</Text>
<Text type="secondary">支付时间:{task.paidAt ? formatTime(task.paidAt) : '-'}</Text>
</Space>
),
},
{
title: '商品映射',
key: 'mapping',
width: 230,
render: (_, task) => (
<Space direction="vertical" size={2}>
<Text ellipsis title={task.commodityId}>
{task.goodsName || task.skuName || task.internalSkuKey || '未映射'}
</Text>
<Text type="secondary">{task.requiredPoints != null ? `${task.requiredPoints} 积分` : '价格未知'}</Text>
</Space>
),
},
{
title: '分类',
key: 'classification',
width: 190,
render: (_, task) => (
<Space direction="vertical" size={3}>
<Space size={4}>
<Tag color={task.saleMode === 'presale' ? 'gold' : task.saleMode === 'direct' ? 'green' : 'default'}>
{SALE_MODE_LABELS[task.saleMode] || task.saleMode}
</Tag>
<Tag>{AVAILABILITY_LABELS[task.availabilityState] || task.availabilityState}</Tag>
</Space>
<Text type="secondary" ellipsis title={task.campaignName || task.campaignKey || '-'}>
{task.campaignName || task.campaignKey || '未设置活动批次'}
</Text>
{task.offerAvailableFrom ? (
<Text type="secondary">开放:{formatTime(task.offerAvailableFrom)}</Text>
) : null}
</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 ? '占用中' : '未占用'} · {task.lease ? leaseExpiresLabel(task.lease.expiresAt) : '-'}
</Text>
</Space>
) : (
<Text type="secondary">未分配</Text>
),
},
{
title: '绑定',
key: 'binding',
width: 180,
render: (_, task) => (
<Space direction="vertical" size={2}>
<Tag>{bindingStatusLabel(task.bindingStatus)}</Tag>
<Text>{task.bindTask?.roleName || (task.bindTask?.bindPhase === 'role_ready' ? '角色待确认' : '-')}</Text>
</Space>
),
},
{
title: '状态',
key: 'status',
width: 180,
render: (_, task) => (
<Space direction="vertical" size={4}>
<Tag color={STATUS_COLORS[task.executionStatus] || 'default'}>{statusLabel(task.executionStatus)}</Tag>
<Text type="secondary">兑换:{exchangeStatusLabel(task.exchangeStatus)}</Text>
{task.manualReason ? (
<Text type="danger">
{MANUAL_REASON_LABELS[task.manualReason] || task.manualReason}
</Text>
) : null}
</Space>
),
},
{
title: '外部协作',
key: 'collab',
width: 150,
render: (_, task) =>
task.collabOrder ? (
<Space direction="vertical" size={2}>
<Tag color={task.collabOrder.status === 'done' ? 'success' : 'blue'}>
{collabStatusLabel(task.collabOrder.status)}
</Tag>
<Space size={2}>
{can('douyu:collab:view') ? (
<Button
type="link"
size="small"
style={{ height: 'auto', padding: 0 }}
onClick={() => navigate(`/douyu/collab?orderId=${task.collabOrder?.id}`)}
>
{task.collabOrder.orderNo}
</Button>
) : (
<Text>{task.collabOrder.orderNo}</Text>
)}
<Text copyable={{ text: task.collabOrder.orderNo }} />
</Space>
</Space>
) : (
<Text type="secondary">未同步</Text>
),
},
{
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>
<Button
size="small"
type={task.collabOrder ? 'default' : 'primary'}
icon={<LinkOutlined />}
loading={rowCollabSyncingId === task.id}
disabled={
!can('platform_fulfillment:use') ||
collabSyncing ||
(rowCollabSyncingId !== null && rowCollabSyncingId !== task.id)
}
onClick={() => void performCollabSync([task.id], 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 />}
loading={allocatingTaskId === task.id}
disabled={allocatingTaskId !== null && allocatingTaskId !== task.id}
onClick={() => void requestAllocation(task)}
>
人工重试选号
</Button>
) : null}
{canRefreshBindingQr(task) ? (
<Button size="small" icon={<ReloadOutlined />} onClick={() => void runTaskAction(() => platformFulfillmentApi.startBinding(task.id))}>
刷新二维码
</Button>
) : null}
{task.executionStatus === 'role_ready' ? (
<Button size="small" type="primary" icon={<CheckCircleOutlined />} onClick={() => void runTaskAction(() => platformFulfillmentApi.confirmBinding(task.id))}>
确认绑定
</Button>
) : null}
{canResetBinding(task) ? (
<Button
size="small"
danger
icon={<UndoOutlined />}
onClick={() => resetBinding(task)}
>
重置角色资料
</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 && canRefreshBindingQr(selected) ? (
<Button
icon={<ReloadOutlined />}
onClick={() => void runTaskAction(() => platformFulfillmentApi.startBinding(selected.id))}
>
刷新二维码
</Button>
) : null}
{selected.account &&
selected.executionStatus !== 'completed' &&
selected.executionStatus !== 'cancelled' &&
can('platform_fulfillment:use') ? (
<Button
icon={<UserSwitchOutlined />}
onClick={() => {
setManualReleaseTarget(selected);
setManualReleaseReason('以外部单协作人工处理为准');
}}
>
释放并转人工
</Button>
) : null}
{canResetBinding(selected) ? (
<Button danger icon={<UndoOutlined />} onClick={() => resetBinding(selected)}>
重置角色资料
</Button>
) : null}
{can('platform_fulfillment:cancel') &&
selected.executionStatus !== 'completed' &&
selected.executionStatus !== 'cancelled' ? (
<Button danger onClick={() => cancelTask(selected)}>
取消
</Button>
) : null}
{can('platform_fulfillment:restore') &&
selected.executionStatus === 'cancelled' &&
selected.issueCode !== 'source_cancelled' ? (
<Button
type="primary"
icon={<UndoOutlined />}
onClick={() => {
setRestoreTarget(selected);
setRestoreReason('');
}}
>
恢复任务
</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">系统自动检测账号并选号;只有缺货、CK 异常或资格失败时转人工处理。客户扫码绑定后,运营可直接开通宝典、充值或兑换皮肤。</Text>
</div>
<Space wrap>
<Tag>进行中租约:{leaseDurationLabel(settings?.leaseDurationMinutes)}</Tag>
<Tag>订单起算:{settings?.orderMatchStartedAt ? formatTime(settings.orderMatchStartedAt) : '-'}</Tag>
<Button
icon={<SettingOutlined />}
disabled={!can('platform_fulfillment:admin')}
onClick={openLeaseSettings}
>
租约设置
</Button>
<Button icon={<LinkOutlined />} disabled={!can('platform_fulfillment:admin')} onClick={() => void openMapping()}>
商品映射
</Button>
<Button
icon={<LinkOutlined />}
loading={collabSyncing}
disabled={
!can('platform_fulfillment:use') ||
selectedRowKeys.length === 0 ||
rowCollabSyncingId !== null
}
onClick={() => void syncCollab()}
>
同步外部单协作{selectedRowKeys.length > 0 ? `(${selectedRowKeys.length})` : ''}
</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 }}
/>
<Segmented
value={queueBucket}
options={QUEUE_BUCKET_OPTIONS}
onChange={(value) => {
setQueueBucket(String(value));
setPage(1);
}}
/>
<Select
value={saleModeFilter}
options={[
{ value: '', label: '全部销售模式' },
...Object.entries(SALE_MODE_LABELS).map(([value, label]) => ({ value, label })),
]}
onChange={(value) => {
setSaleModeFilter(value);
setPage(1);
}}
style={{ width: 150 }}
/>
<Button icon={<ReloadOutlined />} onClick={() => void loadTasks()}>
刷新
</Button>
</Space>
<Table<PlatformFulfillmentTask>
rowKey="id"
loading={loading}
columns={columns}
dataSource={rows}
rowSelection={{
selectedRowKeys,
onChange: setSelectedRowKeys,
}}
scroll={{ x: 2100 }}
pagination={{
current: page,
pageSize,
total,
showSizeChanger: true,
onChange: (nextPage, nextSize) => {
setPage(nextPage);
setPageSize(nextSize);
},
}}
locale={{ emptyText: <Empty description="暂无直播账号履约任务" /> }}
/>
</Card>
<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.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}
{selected.exchangeResultImage ? (
<Card
size="small"
title="兑换结果凭证"
extra={(
<Space>
<Button
size="small"
icon={<CopyOutlined />}
onClick={() => void copyExchangeImageViewer(selected.exchangeResultImage!.url)}
>
复制图片
</Button>
<Button
size="small"
icon={<DownloadOutlined />}
onClick={() => downloadExchangeImageViewer(
selected.exchangeResultImage!.url,
`斗鱼兑换结果-${selected.skuName || selected.platformOrderId}`,
)}
>
下载图片
</Button>
</Space>
)}
>
<div
onClick={() => setExchangeImageViewer({
url: selected.exchangeResultImage!.url,
title: `斗鱼兑换结果-${selected.skuName || selected.platformOrderId}`,
})}
style={{ cursor: 'zoom-in', textAlign: 'center' }}
title="点击查看大图"
>
<img
src={selected.exchangeResultImage.url}
alt="兑换结果凭证"
style={{
width: '100%',
maxWidth: 180,
height: 'auto',
borderRadius: 8,
border: '1px solid #f0f0f0',
}}
/>
</div>
</Card>
) : 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.goodsName || selected.skuName || '未映射'}
</Descriptions.Item>
<Descriptions.Item label="销售模式">
{SALE_MODE_LABELS[selected.saleMode] || selected.saleMode}
</Descriptions.Item>
<Descriptions.Item label="开放状态">
{AVAILABILITY_LABELS[selected.availabilityState] || selected.availabilityState}
</Descriptions.Item>
<Descriptions.Item label="活动批次" span={2}>
{selected.campaignName || selected.campaignKey || '-'}
</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="外部协作单" span={2}>
{selected.collabOrder
? `${selected.collabOrder.orderNo} · ${collabStatusLabel(selected.collabOrder.status)}`
: '未同步'}
</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="精英宝典操作">
<Space direction="vertical" size={12} style={{ width: '100%' }}>
<Text type="secondary">
直接复用斗鱼精英宝典工作台任务,作用于当前履约账号;开通和充值会在任务窗口展示支付二维码。
</Text>
<Space wrap>
<Button
icon={<ReloadOutlined />}
disabled={!selected.account || !can('douyu:task')}
loading={douyuActionLoading === 'query_elite_status'}
onClick={() => void runDouyuAccountAction('query_elite_status')}
>
查询宝典状态
</Button>
<Button
type="primary"
icon={<CreditCardOutlined />}
disabled={!selected.account || !can('douyu:task')}
loading={douyuActionLoading === 'create_elite_qr'}
onClick={() => void runDouyuAccountAction('create_elite_qr')}
>
开通精英宝典
</Button>
</Space>
<Space wrap>
<Space.Compact>
<InputNumber
min={1}
precision={0}
value={goldAmount}
onChange={(value) => setGoldAmount(Number(value) || 1)}
addonBefore="鱼翅"
style={{ width: 150 }}
/>
<Button
icon={<CreditCardOutlined />}
disabled={!selected.account || !can('douyu:task')}
loading={douyuActionLoading === 'create_gold_qr'}
onClick={() => void runDouyuAccountAction('create_gold_qr')}
>
充值鱼翅
</Button>
</Space.Compact>
<Space.Compact>
<InputNumber
min={1}
precision={0}
value={giftCount}
onChange={(value) => setGiftCount(Number(value) || 1)}
addonBefore="数量"
style={{ width: 130 }}
/>
<Button
icon={<GiftOutlined />}
disabled={!selected.account || !can('douyu:task')}
loading={douyuActionLoading === 'donate_elite_gift'}
onClick={() => void runDouyuAccountAction('donate_elite_gift')}
>
赠送精英令
</Button>
</Space.Compact>
<Button
type="primary"
icon={<ShoppingOutlined />}
disabled={
!selected.account ||
!can('douyu:task') ||
!selected.commodityId ||
selected.executionStatus === 'completed' ||
selected.exchangeStatus === 'manual_done' ||
Boolean(selected.exchangeResultImage)
}
loading={douyuActionLoading === 'exchange_goods'}
onClick={() => void runDouyuAccountAction('exchange_goods')}
>
兑换当前订单皮肤
</Button>
</Space>
</Space>
</Card>
<Card size="small" title="当前操作">
{actionButtons}
</Card>
<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)} ·{' '}
{event.actorRoleLabel || ACTOR_TYPE_LABELS[event.actorType] || '系统'}
{event.actorName ? ` · ${event.actorName}` : ''}
{event.actorId ? ` · ID ${event.actorId}` : ''}
</Text>
</Space>
),
}))}
/>
</div>
</Card>
</Space>
)}
</Drawer>
<Modal
open={Boolean(douyuActionBatchId)}
title={DOUYU_ACTION_LABELS[douyuActionType] || '斗鱼精英宝典操作'}
footer={
<Button onClick={closeDouyuAction}>
关闭
</Button>
}
onCancel={closeDouyuAction}
width={520}
>
<Space direction="vertical" size={14} style={{ width: '100%', alignItems: 'center' }}>
{douyuActionTask ? (
<>
<Tag color={TASK_STATUS_COLORS[douyuActionTask.status] || 'default'}>
{TASK_STATUS_LABELS[douyuActionTask.status] || douyuActionTask.status}
</Tag>
<Text>{douyuActionTask.message || '任务执行中'}</Text>
{douyuActionQrValue ? (
<QRCode value={douyuActionQrValue} size={260} />
) : null}
{douyuActionType === 'exchange_goods' && douyuActionTask.status === 'success' ? (
<ExchangeResultImage
task={douyuActionTask}
variant="detail"
onClick={(_task, url) => setExchangeImageViewer({
url,
title: `斗鱼兑换结果-${selected?.skuName || selected?.platformOrderId || douyuActionTask.id}`,
})}
/>
) : null}
</>
) : (
<Text type="secondary">任务已提交,正在等待斗鱼执行器返回结果...</Text>
)}
</Space>
</Modal>
<Modal
open={Boolean(exchangeImageViewer)}
title="兑换结果图片"
width={620}
centered
footer={(
<Space>
<Button onClick={() => setExchangeImageViewer(null)}>关闭</Button>
<Button icon={<CopyOutlined />} onClick={() => void copyExchangeImageViewer()}>
复制图片
</Button>
<Button icon={<DownloadOutlined />} onClick={() => downloadExchangeImageViewer()}>
下载图片
</Button>
</Space>
)}
onCancel={() => setExchangeImageViewer(null)}
>
{exchangeImageViewer ? (
<img
src={exchangeImageViewer.url}
alt="兑换结果"
style={{ width: '100%', maxHeight: '72vh', objectFit: 'contain', display: 'block' }}
/>
) : null}
</Modal>
<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
title={`恢复已取消任务 ${restoreTarget ? `#${restoreTarget.id}` : ''}`}
open={Boolean(restoreTarget)}
okText="确认恢复"
cancelText="取消"
confirmLoading={restoring}
onOk={() => void restoreTask()}
onCancel={() => {
setRestoreTarget(null);
setRestoreReason('');
}}
>
<Space direction="vertical" size={12} style={{ width: '100%' }}>
<Alert
type="warning"
showIcon
message="恢复后会重新进入履约队列"
description="系统不会复用已释放的旧账号;若商品映射缺失,任务会先恢复到待映射状态。"
/>
<Input.TextArea
rows={3}
maxLength={2000}
showCount
value={restoreReason}
placeholder="请填写恢复原因,例如:客服误点取消,经核对订单仍有效"
onChange={(event) => setRestoreReason(event.target.value)}
/>
</Space>
</Modal>
<Modal
title={`释放并转人工 ${manualReleaseTarget ? `#${manualReleaseTarget.id}` : ''}`}
open={Boolean(manualReleaseTarget)}
okText="确认转人工"
cancelText="取消"
confirmLoading={manualReleasing}
onOk={() => void releaseTaskToManual()}
onCancel={() => {
setManualReleaseTarget(null);
setManualReleaseReason('');
}}
>
<Space direction="vertical" size={12} style={{ width: '100%' }}>
<Alert
type="warning"
showIcon
message="释放当前账号后不会自动重新选号"
description="任务会进入“待人工”,并通知订单侧当前由人工处理。"
/>
<Input.TextArea
rows={3}
maxLength={2000}
showCount
value={manualReleaseReason}
placeholder="请填写转人工原因"
onChange={(event) => setManualReleaseReason(event.target.value)}
/>
</Space>
</Modal>
<Modal
open={settingsOpen}
title="履约同步与租约设置"
okText="保存设置"
confirmLoading={savingSettings}
onOk={() => void saveLeaseSettings()}
onCancel={() => setSettingsOpen(false)}
>
<Space direction="vertical" size={16} style={{ width: '100%' }}>
<div>
<Text strong>订单匹配起算时间</Text>
<DatePicker
showTime
allowClear={false}
value={orderMatchStartedAt}
onChange={setOrderMatchStartedAt}
format="YYYY-MM-DD HH:mm"
style={{ width: '100%', marginTop: 8 }}
/>
<Text type="secondary">
只同步此时间之后支付的 order_site 人工订单,历史任务保留但不再展示或自动处理。
</Text>
</div>
<div>
<Text strong>进行中任务兜底 TTL</Text>
<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}
<Text type="secondary">
默认无限制。这里的 TTL 只作用于普通进行中状态,不会覆盖预售等待开放和人工处理状态。
</Text>
</div>
<div>
<Text strong>终态释放与特殊状态策略</Text>
<Text type="secondary">
留空表示永久保留;0 表示命中该状态后立即释放。
</Text>
<Row gutter={12} style={{ marginTop: 8 }}>
<Col span={12}>
<Text type="secondary">自动兑换完成保留</Text>
<InputNumber
min={0}
precision={0}
value={completedReleaseDelay}
onChange={setCompletedReleaseDelay}
placeholder="留空=永久"
addonAfter="分钟"
style={{ width: '100%' }}
/>
</Col>
<Col span={12}>
<Text type="secondary">人工兑换完成保留</Text>
<InputNumber
min={0}
precision={0}
value={manualCompletedReleaseDelay}
onChange={setManualCompletedReleaseDelay}
placeholder="留空=永久"
addonAfter="分钟"
style={{ width: '100%' }}
/>
</Col>
</Row>
<Row gutter={12} style={{ marginTop: 8 }}>
<Col span={12}>
<Text type="secondary">预售等待开放 TTL</Text>
<InputNumber
min={0}
precision={0}
value={presaleWaitingReleaseTtl}
onChange={setPresaleWaitingReleaseTtl}
placeholder="留空=永久"
addonAfter="分钟"
style={{ width: '100%' }}
/>
</Col>
<Col span={12}>
<Text type="secondary">人工处理 TTL</Text>
<InputNumber
min={0}
precision={0}
value={manualRequiredLeaseTtl}
onChange={setManualRequiredLeaseTtl}
placeholder="留空=永久"
addonAfter="分钟"
style={{ width: '100%' }}
/>
</Col>
</Row>
</div>
<Alert
type="info"
showIcon
message="按任务状态应用租约策略"
description="保存后会按每个任务当前状态重新计算租约,不会把所有预售、人工和进行中任务统一套用同一个 TTL。"
/>
</Space>
</Modal>
<Modal
open={mappingOpen}
title="斗鱼商品映射管理"
width={1120}
okText="保存映射"
onOk={() => void saveMapping()}
onCancel={() => setMappingOpen(false)}
>
<Space direction="vertical" size={14} style={{ width: '100%' }}>
<Space wrap>
<Select
value={mappingFilterMode}
options={[
{ value: '', label: '全部销售模式' },
...Object.entries(SALE_MODE_LABELS).map(([value, label]) => ({ value, label })),
]}
onChange={(value) => {
setMappingFilterMode(value);
void loadMappingRows(mappingSku.trim(), value).catch((error) => message.error(getErrorMessage(error)));
}}
style={{ width: 160 }}
/>
<Space>
<Text>显示已归档</Text>
<Switch
checked={mappingIncludeArchived}
onChange={(checked) => {
setMappingIncludeArchived(checked);
void platformFulfillmentApi.listMappings({
keyword: mappingSku.trim(),
sale_mode: mappingFilterMode || undefined,
include_archived: checked,
}).then(setMappings).catch((error) => message.error(getErrorMessage(error)));
}}
/>
</Space>
<Button onClick={() => resetMappingForm()}>
新建映射
</Button>
</Space>
<Space wrap style={{ width: '100%' }}>
<Input placeholder="内部 SKU,例如 套装-兔兔白日梦" value={mappingSku} onChange={(event) => setMappingSku(event.target.value)} style={{ width: 260 }} />
<Input placeholder="活动批次,例如 douyu-2026-11-return" value={mappingCampaignKey} onChange={(event) => setMappingCampaignKey(event.target.value)} style={{ width: 260 }} />
<Input placeholder="活动名称,例如 11 月返场" value={mappingCampaignName} onChange={(event) => setMappingCampaignName(event.target.value)} style={{ width: 220 }} />
</Space>
<Space.Compact style={{ width: '100%' }}>
<Select
showSearch
optionFilterProp="label"
loading={mappingGoodsLoading}
placeholder={mappingGoodsLoading ? '正在加载斗鱼活动商品…' : '选择斗鱼精英宝典商品'}
value={mappingGoodsId || undefined}
onChange={selectGoods}
options={[
...goods.map((item) => ({
value: item.commodity_id,
label: `${item.name || item.commodity_id} · ${item.score ?? '-'} 积分`,
})),
...(mappingGoodsId && !goods.some((item) => item.commodity_id === mappingGoodsId)
? [{
value: mappingGoodsId,
label: `${mappingGoodsName || mappingGoodsId} · 当前已缓存`,
}]
: []),
]}
notFoundContent={mappingGoodsLoading ? null : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无活动商品" />}
style={{ flex: 1 }}
/>
<Button icon={<ReloadOutlined />} loading={mappingGoodsLoading} onClick={() => void reloadMappingGoods()}>
刷新商品
</Button>
</Space.Compact>
<Space wrap>
<Text>销售模式</Text>
<Select
value={mappingSaleMode}
options={Object.entries(SALE_MODE_LABELS).map(([value, label]) => ({ value, label }))}
onChange={setMappingSaleMode}
style={{ width: 140 }}
/>
<Text>所需积分</Text>
<InputNumber min={0} value={mappingPoints} onChange={(value) => setMappingPoints(value)} />
<Text>启用</Text>
<Switch checked={mappingEnabled} onChange={setMappingEnabled} />
</Space>
<Space wrap>
<Text>商品开放时间</Text>
<DatePicker
showTime
value={mappingAvailableFrom}
onChange={setMappingAvailableFrom}
placeholder="开始时间"
/>
<Text>至</Text>
<DatePicker
showTime
value={mappingAvailableUntil}
onChange={setMappingAvailableUntil}
placeholder="结束时间"
/>
</Space>
<Tabs
items={[
{
key: 'current',
label: '当前映射',
children: (
<Table<PlatformFulfillmentMapping>
rowKey="id"
size="small"
pagination={false}
dataSource={mappings}
columns={[
{ title: '内部 SKU', dataIndex: 'internalSkuKey', width: 150 },
{
title: '活动批次',
key: 'campaign',
width: 170,
render: (_: unknown, row) => (
<Space direction="vertical" size={0}>
<Text>{row.campaignName || row.campaignKey}</Text>
<Text type="secondary" style={{ fontSize: 12 }}>{row.campaignKey}</Text>
</Space>
),
},
{ title: '商品', dataIndex: 'goodsName', width: 150 },
{ title: '商品 ID', dataIndex: 'commodityId', width: 180 },
{
title: '分类',
key: 'saleMode',
width: 130,
render: (_: unknown, row) => (
<Space direction="vertical" size={2}>
<Tag color={row.saleMode === 'presale' ? 'gold' : row.saleMode === 'direct' ? 'green' : 'default'}>
{SALE_MODE_LABELS[row.saleMode] || row.saleMode}
</Tag>
<Tag>{AVAILABILITY_LABELS[row.availabilityState] || row.availabilityState}</Tag>
</Space>
),
},
{ title: '积分', dataIndex: 'requiredPoints', width: 80 },
{ title: '影响任务', dataIndex: 'affectedTasks', width: 90 },
{
title: '状态',
dataIndex: 'enabled',
width: 100,
render: (value: boolean, row) => (
<Tag color={row.archivedAt ? 'default' : value ? 'green' : 'orange'}>
{row.archivedAt ? '已归档' : value ? '启用' : '停用'}
</Tag>
),
},
{
title: '操作',
key: 'actions',
width: 310,
render: (_: unknown, row) => (
<Space wrap size={4}>
<Button size="small" disabled={Boolean(row.archivedAt)} onClick={() => editMapping(row)}>
编辑
</Button>
{row.archivedAt ? (
<Button size="small" onClick={() => runMappingAction(row, 'restore')}>
恢复
</Button>
) : (
<>
<Button
size="small"
onClick={() => runMappingAction(row, row.enabled ? 'disable' : 'enable')}
>
{row.enabled ? '停用' : '启用'}
</Button>
<Button size="small" onClick={() => runMappingAction(row, 'archive')}>
归档
</Button>
</>
)}
<Button size="small" danger onClick={() => removeMapping(row)}>
删除
</Button>
</Space>
),
},
]}
scroll={{ x: 1300 }}
/>
),
},
]}
/>
</Space>
</Modal>
</Space>
);
}