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

3177 lines
126 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, Image, 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, PlatformFulfillmentBindingLog, 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 CUSTOMER_PLATFORM_LABELS: Record<string, string> = {
wechat: '微信',
qq: 'QQ',
};
const CUSTOMER_SYSTEM_LABELS: Record<string, string> = {
ios: '苹果',
android: '安卓',
};
function customerMatchTone(profile: NonNullable<PlatformFulfillmentTask['customerProfile']>) {
if (profile.roleMatched === false || profile.channelMatched === false) return 'red';
if (profile.roleMatched === true && profile.channelMatched === true) return 'green';
return 'gold';
}
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: '待扫码',
waiting_bind: '待重新绑定',
role_ready: '待确认角色',
bound: '已绑定',
failed: '绑定失败',
};
const BINDING_STATUS_COLORS: Record<string, string> = {
not_started: 'default',
preparing: 'processing',
qr_pending: 'gold',
waiting_bind: 'orange',
role_ready: 'purple',
bound: 'green',
failed: 'red',
};
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 MANUAL_REASON_LABELS: Record<string, string> = {
points_short: '积分不足',
elite_not_opened: '宝典未开通',
limit_reached: '已达限兑',
binding_failed: '绑定异常',
account_cooldown: '账号冷却',
other_manual: '其他人工',
};
const SALE_MODE_TAB_STORAGE_KEY = 'platform_fulfillment_sale_mode_tab';
const QUEUE_BUCKET_OPTIONS = [
{ value: 'all', label: '全部' },
{ value: 'current', label: '当前待办' },
{ value: 'pending_mapping', label: '待映射' },
{ value: 'ready_for_fulfillment', label: '可履约' },
{ value: 'needs_action', label: '需要人工' },
{ value: 'completed', label: '已完成' },
{ value: 'cancelled', label: '已取消' },
];
const PRESALE_QUEUE_BUCKET_OPTIONS = [
{ value: 'all', label: '全部' },
{ value: 'current', label: '当前待办' },
{ value: 'presale_waiting', label: '预售待开放' },
{ value: 'pending_mapping', 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: '忽略账号旧角色',
binding_synced_from_account: '同步账号最新角色绑定',
binding_false_confirmation_reverted: '纠正误判的账号历史绑定',
binding_pending_task_linked: '关联最新待确认角色',
binding_pending_observation_superseded: '旧待确认角色已被最新绑定替换',
binding_role_locked_elsewhere: '用户角色已被其他账号占用',
binding_account_locked_elsewhere: '斗鱼账号 7 天内已绑定其他角色',
binding_observation_confirmed: '账号观测确认角色绑定',
binding_confirmed: '履约绑定已确认',
binding_manually_confirmed: '人工确认绑定',
binding_reused_existing_pair: '复用同账号同角色',
binding_sync_rejected: '忽略不匹配的绑定证据',
binding_scanned_role_mismatch: '扫码角色与下单资料不一致',
binding_verified: '斗鱼绑定复核通过',
binding_verify_failed: '斗鱼绑定复核未通过',
binding_verify_error: '斗鱼绑定复核查询异常',
customer_profile_saved: '客户提交游戏资料',
customer_profile_updated: '工作台修改客户资料',
eligibility_check_failed: '兑换资格查询失败',
eligibility_auto_refresh_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: '没有可分配账号',
capability_cache_miss: '账号商品能力待补货',
account_lease_conflict: '候选账号正被其他任务占用',
account_pool_busy: '资格账号暂时全部占用',
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: '游戏角色仍在换绑冷却期',
customer_role_bound_elsewhere: '用户角色 7 天内已绑定其他斗鱼账号',
account_role_bound_elsewhere: '斗鱼账号 7 天内已绑定其他角色',
lease_expired: '账号租约已过期',
manual_required: '需要人工处理',
source_cancelled: '来源订单已取消',
};
const DOUYU_ACTION_LABELS: Record<string, string> = {
query_game_name: '刷新角色绑定',
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 bindingStatusColor(value: string) {
return BINDING_STATUS_COLORS[value] || 'default';
}
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') ||
value.includes('binding_synced')
) {
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('、') || '未满足分配条件'}`;
});
if (lines.length) return lines.join(';');
const counts =
detail.availabilityCounts && typeof detail.availabilityCounts === 'object'
? (detail.availabilityCounts as Record<string, unknown>)
: {};
const eligible = Number(counts['account:eligible'] || 0);
const roleCooldown = Number(counts['account:roleCooldown'] || 0);
const leased = Number(counts['account:leased'] || 0);
const collab = Number(counts['account:activeCollab'] || 0);
const summary = [
eligible ? `具备资格账号 ${eligible}` : '',
roleCooldown ? `换绑冷却 ${roleCooldown}` : '',
leased ? `任务租约占用 ${leased}` : '',
collab ? `协作单占用 ${collab}` : '',
].filter(Boolean);
return summary.length
? `${summary.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 === 'eligibility_auto_refresh_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 === 'binding_synced_from_account') {
const channel = String(detail.gameChannel || '');
return `账号已确认角色 ${String(detail.roleName || '-')}${channel ? `(${channel})` : ''}`;
}
if (event.eventType === 'binding_observation_confirmed') {
const pending = String(detail.pendingRoleName || '');
const observed = String(detail.observedRoleName || '-');
return pending && pending !== observed
? `账号已绑定 ${observed};原待确认角色 ${pending} 已失效`
: `账号已绑定 ${observed}`;
}
if (event.eventType === 'binding_pending_observation_superseded') {
return `原待确认角色 ${String(detail.pendingRoleName || '-')} 已被当前绑定 ${String(detail.observedRoleName || '-')} 替换`;
}
if (event.eventType === 'binding_confirmed') {
const channel = String(detail.confirmedChannel || '');
return `已确认订单角色 ${String(detail.confirmedRoleName || '-')}${channel ? `(${channel})` : ''}`;
}
if (event.eventType === 'binding_manually_confirmed') {
const note = String(detail.note || '').trim();
return `人工确认角色 ${String(detail.roleName || '-')}${note ? `;依据:${note}` : ''}`;
}
if (event.eventType === 'binding_reused_existing_pair') {
return `本次扫码角色 ${String(detail.roleName || '-')} 与账号当前角色一致,直接复用`;
}
if (event.eventType === 'binding_account_locked_elsewhere') {
return String(detail.message || '斗鱼账号 7 天内已绑定其他角色,请换号或等待');
}
if (event.eventType === 'binding_role_locked_elsewhere') {
return String(detail.message || `用户角色已被其他账号占用,请复用原账号或等待`);
}
if (event.eventType === 'binding_sync_rejected') {
const reason = String(detail.reason || '');
if (reason === 'target_mismatch') {
return `确认角色 ${String(detail.confirmedRoleName || '-')} 与订单目标 ${String(detail.targetRoleName || '-')} 不一致,未结算`;
}
if (reason === 'source_outside_lease') return '账号绑定任务创建于本单租约之前,已忽略';
if (reason === 'missing_target') return '本单没有待确认角色,账号确认任务未结算';
return '该绑定任务不属于当前订单,已忽略';
}
if (event.eventType === 'binding_scanned_role_mismatch') {
const channel = String(detail.channel || '');
return `扫到角色「${String(detail.scannedRoleName || '-')}」${channel ? `(${channel})` : ''},与下单填写「${String(detail.expectedRoleName || '-')}」不一致`;
}
if (event.eventType === 'binding_verified') {
const channel = String(detail.channel || '');
const mode = detail.automatic ? '自动复核' : '人工复核';
return `${mode}通过:斗鱼当前已绑定「${String(detail.roleName || '-')}」${channel ? `(${channel})` : ''}`;
}
if (event.eventType === 'binding_verify_failed') {
return String(detail.message || `斗鱼复核未通过:实际 ${String(detail.actualRoleName || '未生效')},目标 ${String(detail.expectedRoleName || '-')}`);
}
if (event.eventType === 'binding_verify_error') {
return `复核查询斗鱼接口失败:${String(detail.error || '未知错误')}`;
}
if (event.eventType === 'customer_profile_saved') {
const plat = CUSTOMER_PLATFORM_LABELS[String(detail.platform || '')] || String(detail.platform || '-');
const sys = CUSTOMER_SYSTEM_LABELS[String(detail.system || '')] || String(detail.system || '-');
return `客户提交资料:角色 ${String(detail.customerRoleName || '-')}(${plat} / ${sys})`;
}
if (event.eventType === 'customer_profile_updated') {
const plat = CUSTOMER_PLATFORM_LABELS[String(detail.platform || '')] || String(detail.platform || '-');
const sys = CUSTOMER_SYSTEM_LABELS[String(detail.system || '')] || String(detail.system || '-');
const prev = String(detail.previousRoleName || '');
const next = String(detail.customerRoleName || '-');
const roleText = prev && prev !== next ? `${prev} → ${next}` : next;
return `修改客户资料:${roleText}(${plat} / ${sys})${detail.reopenedBinding ? ';已重置失败状态待重扫' : ''}`;
}
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);
}
function canReallocateAndBind(task: PlatformFulfillmentTask) {
return Boolean(
!task.account &&
task.customerProfile &&
task.executionStatus === 'manual_required' &&
['binding_failed', 'lease_expired', 'role_changed'].includes(task.issueCode),
);
}
function canManualConfirmBinding(task: PlatformFulfillmentTask) {
if (!task.account) return false;
return !['bound', 'completed', 'cancelled'].includes(task.executionStatus);
}
export default function PlatformFulfillmentPage() {
const user = getUser();
const navigate = useNavigate();
const { can } = usePermissions(user);
const [queueBucket, setQueueBucket] = useState('all');
const [saleModeTab, setSaleModeTab] = useState<'direct' | 'presale' | 'unknown' | 'legacy'>(() => {
const saved = localStorage.getItem(SALE_MODE_TAB_STORAGE_KEY);
if (saved === 'presale' || saved === 'unknown' || saved === 'legacy') return saved;
return 'direct';
});
useEffect(() => {
localStorage.setItem(SALE_MODE_TAB_STORAGE_KEY, saleModeTab);
}, [saleModeTab]);
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 [manualBindTarget, setManualBindTarget] = useState<PlatformFulfillmentTask | null>(null);
const [manualBindRole, setManualBindRole] = useState('');
const [manualBindNote, setManualBindNote] = useState('');
const [manualBinding, setManualBinding] = useState(false);
const [profileEditTarget, setProfileEditTarget] = useState<PlatformFulfillmentTask | null>(null);
const [profileEditRole, setProfileEditRole] = useState('');
const [profileEditPlatform, setProfileEditPlatform] = useState<'wechat' | 'qq'>('wechat');
const [profileEditSystem, setProfileEditSystem] = useState<'ios' | 'android'>('ios');
const [profileEditReopen, setProfileEditReopen] = useState(true);
const [profileEditSaving, setProfileEditSaving] = useState(false);
const [verifyingBinding, setVerifyingBinding] = useState(false);
const manualBindCurrentRole =
manualBindTarget?.bindingEvidence?.accountCurrentRole || '';
const manualBindMismatch = Boolean(
manualBindCurrentRole &&
manualBindRole.trim() &&
manualBindRole.trim() !== manualBindCurrentRole,
);
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 [bindingRefreshing, setBindingRefreshing] = useState(false);
const [qrOpen, setQrOpen] = useState(false);
const [bindingQrImage, setBindingQrImage] = useState('');
const [bindingQrLoading, setBindingQrLoading] = useState(false);
const [mappingOpen, setMappingOpen] = useState(false);
const [mappingEditorOpen, setMappingEditorOpen] = useState(false);
const [mappingSaving, setMappingSaving] = useState(false);
const [mappingKeyword, setMappingKeyword] = useState('');
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 = [
'pending_mapping',
'presale_waiting',
'ready_for_fulfillment',
'needs_action',
].includes(queueBucket)
? queueBucket
: undefined;
const result = await platformFulfillmentApi.listTasks({
status: queueBackedStatus,
queue_bucket: queueBucket === 'all' ? 'all' : backendBucket,
sale_mode: saleModeTab === 'legacy' ? undefined : saleModeTab,
flow_version: saleModeTab === 'legacy' ? 1 : 2,
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, saleModeTab]);
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);
}, 10000);
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);
}, 5000);
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();
}, 3000);
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) : '';
const openBindingQr = async () => {
const bindTaskId = selected?.bindTask?.id;
setQrOpen(true);
setBindingQrImage('');
if (!bindTaskId) return;
setBindingQrLoading(true);
try {
const task = await douyuApi.getTask(bindTaskId);
const image = task.result?.mini_qrcode_image;
if (typeof image === 'string') setBindingQrImage(image);
} catch {
// 小程序码详情读取失败时保留原链接二维码作为回退。
} finally {
setBindingQrLoading(false);
}
};
const closeBindingQr = () => {
setQrOpen(false);
setBindingQrImage('');
setBindingQrLoading(false);
};
useEffect(() => {
setQrOpen(false);
setBindingQrImage('');
setBindingQrLoading(false);
}, [selectedId]);
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 releaseHeldAccount = (task: PlatformFulfillmentTask) => {
Modal.confirm({
title: `释放任务 #${task.id} 的保留账号?`,
content:
'绑定失败账号默认保留到绑定成功或人工释放。释放后任务会回到待分配,客户需要重新选号后刷新二维码。',
okText: '释放账号',
okButtonProps: { danger: true },
cancelText: '取消',
onOk: () =>
runTaskAction(() => platformFulfillmentApi.release(task.id)),
});
};
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 openManualBinding = (task: PlatformFulfillmentTask) => {
setManualBindTarget(task);
setManualBindRole(task.bindingEvidence?.accountCurrentRole || '');
setManualBindNote('');
};
const confirmManualBinding = async () => {
if (!manualBindTarget) return;
const role = manualBindRole.trim();
const note = manualBindNote.trim();
if (!role) {
message.warning('请填写客户确认的游戏角色');
return;
}
if (manualBindCurrentRole && role !== manualBindCurrentRole) {
message.error(`账号当前角色是「${manualBindCurrentRole}」,不能人工确认「${role}」`);
return;
}
if (note.length < 2) {
message.warning('请填写人工确认依据/备注');
return;
}
setManualBinding(true);
try {
const result = await platformFulfillmentApi.manualConfirmBinding(
manualBindTarget.id,
role,
note,
);
setDetail(result);
setSelectedId(result.task.id);
setManualBindTarget(null);
setManualBindRole('');
setManualBindNote('');
await loadTasks();
message.success('已人工确认绑定');
} catch (error) {
message.error(getErrorMessage(error));
} finally {
setManualBinding(false);
}
};
const submitOperatorConfirm = async (task: PlatformFulfillmentTask) => {
try {
const result = await platformFulfillmentApi.operatorConfirmBinding(task.id);
setDetail(result);
setSelectedId(result.task.id);
await loadTasks();
message.success('已代客户提交确认,等待绑定结果');
} catch (error) {
message.error(getErrorMessage(error));
}
};
const openProfileEdit = (task: PlatformFulfillmentTask) => {
setProfileEditTarget(task);
setProfileEditRole(task.customerProfile?.roleName || '');
setProfileEditPlatform(task.customerProfile?.platform === 'qq' ? 'qq' : 'wechat');
setProfileEditSystem(task.customerProfile?.system === 'android' ? 'android' : 'ios');
setProfileEditReopen(task.bindingStatus === 'failed');
};
const saveCustomerProfile = async () => {
if (!profileEditTarget) return;
const role = profileEditRole.trim();
if (!role) {
message.warning('请填写客户游戏角色名');
return;
}
setProfileEditSaving(true);
try {
const result = await platformFulfillmentApi.updateCustomerProfile(
profileEditTarget.id,
{
customerRoleName: role,
customerPlatform: profileEditPlatform,
customerSystem: profileEditSystem,
reopenBinding: profileEditReopen,
},
);
setDetail(result);
setSelectedId(result.task.id);
setProfileEditTarget(null);
await loadTasks();
message.success('客户资料已更新');
} catch (error) {
message.error(getErrorMessage(error));
} finally {
setProfileEditSaving(false);
}
};
const verifyTaskBinding = async (task: PlatformFulfillmentTask) => {
setVerifyingBinding(true);
try {
const result = await platformFulfillmentApi.verifyBinding(task.id);
setDetail(result);
setSelectedId(result.task.id);
await loadTasks();
if (result.task.bindingStatus === 'bound') {
message.success('斗鱼复核通过:当前绑定已生效且角色一致');
} else {
message.warning(result.task.lastError || '斗鱼复核未通过,已转人工处理');
}
} catch (error) {
message.error(getErrorMessage(error));
} finally {
setVerifyingBinding(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 refreshSelectedBinding = async () => {
if (!selectedId) return;
setBindingRefreshing(true);
try {
const result = await platformFulfillmentApi.refreshBinding(selectedId);
setDetail(result);
await loadTasks(true);
if (result.task.bindTask?.bindReadyForConfirm) {
message.success(
`当前待确认角色:${result.task.bindTask.roleName || '-'}`,
);
} else {
message.success('角色绑定状态已刷新');
}
} catch (error) {
message.error(getErrorMessage(error));
} finally {
setBindingRefreshing(false);
}
};
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 = mappingKeyword.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);
if (task) setMappingEditorOpen(true);
setMappingGoodsLoading(true);
try {
const keyword = task?.internalSkuKey || '';
setMappingKeyword(keyword);
const [goodsRows, mappingRows] = await Promise.all([
douyuApi.listLiveGoods(),
platformFulfillmentApi.listMappings({
keyword,
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 openMappingCreate = () => {
resetMappingForm();
setMappingEditorOpen(true);
};
const editMapping = (row: PlatformFulfillmentMapping) => {
setMappingEditorOpen(true);
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 (mappingSaving) return;
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,
};
setMappingSaving(true);
if (mappingEditingId) {
await platformFulfillmentApi.updateMapping(mappingEditingId, payload);
} else {
await platformFulfillmentApi.createMapping(payload);
}
message.success('商品映射已保存');
setMappingEditorOpen(false);
resetMappingForm();
await loadMappingRows();
await loadTasks();
} catch (error) {
message.error(getErrorMessage(error));
} finally {
setMappingSaving(false);
}
};
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: 270,
render: (_, task) => (
<Space direction="vertical" size={3}>
<Text ellipsis title={task.commodityId}>
{task.goodsName || task.skuName || task.internalSkuKey || '未映射'}
</Text>
<Space size={6} wrap>
<Tag color={task.saleMode === 'presale' ? 'gold' : task.saleMode === 'direct' ? 'green' : 'default'}>
{SALE_MODE_LABELS[task.saleMode] || task.saleMode}
</Tag>
<Text type="secondary">
{task.requiredPoints != null ? `${task.requiredPoints} 积分` : '价格未知'}
</Text>
</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: 220,
render: (_, task) => {
const customerRole = task.customerProfile?.roleName?.trim() || '';
const scannedRole = task.bindTask?.roleName?.trim() || '';
const scannedChannel = [task.bindTask?.areaName, task.bindTask?.platName].filter(Boolean).join(' / ');
return (
<Space direction="vertical" size={2}>
<Tag color={bindingStatusColor(task.bindingStatus)}>
{bindingStatusLabel(task.bindingStatus)}
</Tag>
{task.account && task.bindingStatus === 'failed' ? (
<Tag color="orange">账号保留中</Tag>
) : null}
<Text ellipsis title={customerRole || '未填写'}>
客户提交角色:{customerRole || '未填写'}
</Text>
<Text
type={scannedRole ? undefined : 'secondary'}
style={{ fontSize: 12 }}
ellipsis
title={scannedRole ? (scannedChannel ? `${scannedRole} (${scannedChannel})` : scannedRole) : '未识别'}
>
扫码绑定角色:{scannedRole || '未识别'}
{scannedRole && scannedChannel ? ` · ${scannedChannel}` : ''}
</Text>
{task.bindingStatus === 'bound' ? (
<Text type="secondary" style={{ fontSize: 12 }}>
换绑时间:{formatTime(task.account?.roleChangeAvailableAt) || '无冷却'}
</Text>
) : null}
</Space>
);
},
},
{
title: '游戏主页',
key: 'customer_home_images',
width: 120,
render: (_, task) => {
const images = task.customerProfile?.homeImages || [];
if (images.length === 0) return <Text type="secondary">未上传</Text>;
return (
<Image.PreviewGroup items={images.map((item) => item.url)}>
<Space size={4} wrap>
{images.slice(0, 2).map((item, index) => (
<Image
key={`${item.objectKey || item.url}-${index}`}
src={item.thumbnailUrl || item.url}
width={44}
height={44}
style={{ objectFit: 'cover', borderRadius: 4 }}
alt={`游戏主页截图 ${index + 1}`}
/>
))}
</Space>
</Image.PreviewGroup>
);
},
},
{
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>
{saleModeTab === 'presale' ? (
<Button
size="small"
type={task.collabOrder ? 'default' : 'primary'}
icon={<LinkOutlined />}
loading={rowCollabSyncingId === task.id}
disabled={
!can('platform_fulfillment:use') ||
task.bindingStatus !== 'bound' ||
collabSyncing ||
(rowCollabSyncingId !== null && rowCollabSyncingId !== task.id)
}
onClick={() => void performCollabSync([task.id], task.id)}
>
同步到斗鱼预售台账
</Button>
) : null}
{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}
{canReallocateAndBind(task) ? (
<Button
size="small"
type="primary"
icon={<UserSwitchOutlined />}
loading={allocatingTaskId === task.id}
disabled={allocatingTaskId !== null && allocatingTaskId !== task.id}
onClick={() => void requestAllocation(task)}
>
重新选号并绑定
</Button>
) : null}
{task.account && task.bindingStatus === 'failed' ? (
<Button size="small" danger onClick={() => releaseHeldAccount(task)}>
释放账号
</Button>
) : null}
{task.executionStatus === 'role_ready' ? (
<Button size="small" type="primary" icon={<CheckCircleOutlined />} onClick={() => void runTaskAction(() => platformFulfillmentApi.confirmBinding(task.id))}>
代客户确认
</Button>
) : null}
{canManualConfirmBinding(task) && task.executionStatus !== 'role_ready' && task.bindTask?.roleName ? (
<Button size="small" type="primary" icon={<CheckCircleOutlined />} onClick={() => void submitOperatorConfirm(task)}>
代客户确认
</Button>
) : null}
{can('platform_fulfillment:use') && canManualConfirmBinding(task) ? (
<Button size="small" danger icon={<CheckCircleOutlined />} onClick={() => openManualBinding(task)}>
强制确认
</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 centeredColumns = columns
.filter((column) => saleModeTab !== 'direct' || column.key !== 'collab')
.map((column) => ({
...column,
align: 'center' as const,
onHeaderCell: () => ({ style: { textAlign: 'center' as const } }),
}));
const selectedCollabReady =
selectedRowKeys.length > 0 &&
rows.filter((row) => selectedRowKeys.map(String).includes(String(row.id))).length ===
selectedRowKeys.length &&
rows
.filter((row) => selectedRowKeys.map(String).includes(String(row.id)))
.every((row) => row.bindingStatus === 'bound');
const actionButtons = selected ? (
<Space wrap>
{selected.bindTask?.qrUrl ? (
<Button icon={<QrcodeOutlined />} onClick={() => void openBindingQr()}>
查看二维码
</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 && canReallocateAndBind(selected) ? (
<Button
type="primary"
icon={<UserSwitchOutlined />}
loading={allocatingTaskId === selected.id}
onClick={() => void requestAllocation(selected)}
>
重新选号并绑定
</Button>
) : null}
{selected &&
selected.executionStatus !== 'role_ready' &&
selected.executionStatus !== 'bound' &&
(selected.bindingEvidence?.scannedRole || selected.bindTask?.roleName) ? (
<Button type="primary" icon={<CheckCircleOutlined />} onClick={() => void submitOperatorConfirm(selected)}>
代客户确认
</Button>
) : null}
{selected && can('platform_fulfillment:use') && canManualConfirmBinding(selected) ? (
<Button danger icon={<CheckCircleOutlined />} onClick={() => openManualBinding(selected)}>
强制确认
</Button>
) : null}
{selected &&
selected.account &&
selected.bindingStatus === 'bound' &&
!['completed', 'cancelled'].includes(selected.executionStatus) &&
can('platform_fulfillment:use') ? (
<Button
icon={<SyncOutlined />}
loading={verifyingBinding}
onClick={() => void verifyTaskBinding(selected)}
>
复核绑定
</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>
{saleModeTab === 'presale' ? (
<Button
icon={<LinkOutlined />}
loading={collabSyncing}
disabled={
!can('platform_fulfillment:use') ||
selectedRowKeys.length === 0 ||
!selectedCollabReady ||
rowCollabSyncingId !== null
}
onClick={() => void syncCollab()}
>
同步到斗鱼预售台账{selectedRowKeys.length > 0 ? `(${selectedRowKeys.length})` : ''}
</Button>
) : null}
<Button type="primary" loading={syncing} icon={<SyncOutlined />} onClick={() => void sync()}>
同步待履约订单
</Button>
</Space>
</Space>
</Card>
<Tabs
activeKey={saleModeTab}
onChange={(value) => {
const next =
value === 'presale'
? 'presale'
: value === 'unknown'
? 'unknown'
: value === 'legacy'
? 'legacy'
: 'direct';
setSaleModeTab(next);
if (next !== 'presale' && queueBucket === 'presale_waiting') {
setQueueBucket('current');
}
setSelectedRowKeys([]);
setPage(1);
}}
items={[
{ key: 'direct', label: '直接兑换' },
{ key: 'presale', label: '预售' },
{ key: 'unknown', label: '未分类' },
{ key: 'legacy', label: '历史任务' },
]}
/>
{saleModeTab === 'legacy' ? (
<Alert
type="warning"
showIcon
message="历史任务仅允许人工处理,不参与自动选号、自动重试和预售台账同步。"
/>
) : null}
<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={
saleModeTab === 'presale' ? PRESALE_QUEUE_BUCKET_OPTIONS : QUEUE_BUCKET_OPTIONS
}
onChange={(value) => {
setQueueBucket(String(value));
setSelectedRowKeys([]);
setPage(1);
}}
/>
<Button icon={<ReloadOutlined />} onClick={() => void loadTasks()}>
刷新
</Button>
</Space>
<Table<PlatformFulfillmentTask>
rowKey="id"
loading={loading}
columns={centeredColumns}
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="活动批次" 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="绑定状态">
<Tag color={bindingStatusColor(selected.bindingStatus)}>
{bindingStatusLabel(selected.bindingStatus)}
</Tag>
</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="用户资料(order_site)"
extra={
can('platform_fulfillment:use') &&
!['completed', 'cancelled'].includes(selected.executionStatus) &&
selected.bindingStatus !== 'bound' ? (
<Button size="small" onClick={() => openProfileEdit(selected)}>
修改资料
</Button>
) : null
}
>
{selected.customerProfile ? (
<Space direction="vertical" size={10} style={{ width: '100%' }}>
<Descriptions bordered size="small" column={2}>
<Descriptions.Item label="客户角色" span={2}>
{selected.customerProfile.roleName || '未填写'}
</Descriptions.Item>
<Descriptions.Item label="登录方式">
{CUSTOMER_PLATFORM_LABELS[selected.customerProfile.platform] || selected.customerProfile.platform || '-'}
</Descriptions.Item>
<Descriptions.Item label="系统">
{CUSTOMER_SYSTEM_LABELS[selected.customerProfile.system] || selected.customerProfile.system || '-'}
</Descriptions.Item>
<Descriptions.Item label="平台当前角色">
{selected.customerProfile.platformRoleName || '未识别'}
</Descriptions.Item>
<Descriptions.Item label="平台渠道">
{selected.customerProfile.platformChannel || '-'}
</Descriptions.Item>
<Descriptions.Item label="绑定比对" span={2}>
<Space wrap size={6}>
<Tag color={customerMatchTone(selected.customerProfile)}>
{selected.customerProfile.message}
</Tag>
{selected.customerProfile.updatedAt ? (
<Text type="secondary">更新 {formatTime(selected.customerProfile.updatedAt)}</Text>
) : null}
</Space>
</Descriptions.Item>
</Descriptions>
{selected.customerProfile.homeImages.length ? (
<Image.PreviewGroup
items={selected.customerProfile.homeImages.map((item) => item.url)}
>
<Space wrap size={8}>
{selected.customerProfile.homeImages.map((item, index) => (
<Image
key={`${item.objectKey || item.url}-${index}`}
src={item.thumbnailUrl || item.url}
width={96}
height={96}
style={{ objectFit: 'cover', borderRadius: 6 }}
alt={`游戏主页截图 ${index + 1}`}
/>
))}
</Space>
</Image.PreviewGroup>
) : (
<Text type="secondary">没有游戏主页截图</Text>
)}
</Space>
) : (
<Empty
image={Empty.PRESENTED_IMAGE_SIMPLE}
description="客户尚未同步资料和游戏主页截图"
/>
)}
</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="当前游戏渠道">
{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="绑定判定(QYOOB / cjm / 7 天锁)">
{selected.bindingEvidence ? (
<Space direction="vertical" size={10} style={{ width: '100%' }}>
{!selected.bindingEvidence.scannedRole && selected.bindingEvidence.accountCurrentRole ? (
<Alert
type="info"
showIcon
message={`账号已有角色 ${selected.bindingEvidence.accountCurrentRole},但本次没有扫码证据`}
description="列表显示“待扫码”是准确的:账号历史角色不能被当成本次扫码。请让客户扫码,或确认客户角色后使用“人工确认绑定”。"
/>
) : null}
<Descriptions bordered size="small" column={2}>
<Descriptions.Item label="动作通道" span={2}>
{selected.bindingEvidence.actionAliases.join(' / ') || '-'}
<Text type="secondary">
{' '}系统选中:{selected.bindingEvidence.selectedAlias || '-'}
{selected.bindingEvidence.selectedActionable ? '(动作通道)' : '(非动作通道)'}
</Text>
</Descriptions.Item>
<Descriptions.Item label="QYOOB 当前已绑定" span={2}>
{selected.bindingEvidence.actionCurrent ? (
<Space wrap>
<Tag color="green">bindAct=1</Tag>
<Text strong>{selected.bindingEvidence.actionCurrent.roleName}</Text>
{selected.bindingEvidence.actionCurrent.channel ? (
<Text type="secondary">{selected.bindingEvidence.actionCurrent.channel}</Text>
) : null}
</Space>
) : (
<Text type="secondary">未识别</Text>
)}
</Descriptions.Item>
<Descriptions.Item label="QYOOB 本次待确认" span={2}>
{selected.bindingEvidence.actionPending ? (
<Space wrap>
<Tag color="gold">bindAct=0</Tag>
<Text strong>{selected.bindingEvidence.actionPending.roleName}</Text>
{selected.bindingEvidence.actionPending.channel ? (
<Text type="secondary">{selected.bindingEvidence.actionPending.channel}</Text>
) : null}
</Space>
) : (
<Text type="secondary">未出现(等待动作通道)</Text>
)}
</Descriptions.Item>
<Descriptions.Item label="cjm 最新(仅参考)" span={2}>
{selected.bindingEvidence.legacyLatest ? (
<Space wrap>
<Tag>legacy</Tag>
<Text strong>{selected.bindingEvidence.legacyLatest.roleName}</Text>
<Text type="secondary">不能直接确认</Text>
</Space>
) : (
<Text type="secondary">-</Text>
)}
</Descriptions.Item>
<Descriptions.Item label="本次扫码角色" span={2}>
{selected.bindingEvidence.scannedRole ? (
<Text strong>{selected.bindingEvidence.scannedRole}</Text>
) : selected.bindingEvidence.mismatchedRole ? (
<Space wrap>
<Tag color="red">扫到不匹配角色</Tag>
<Text strong>{selected.bindingEvidence.mismatchedRole.roleName}</Text>
{selected.bindingEvidence.mismatchedRole.channel ? (
<Text type="secondary">{selected.bindingEvidence.mismatchedRole.channel}</Text>
) : null}
{selected.bindingEvidence.mismatchedRole.expectedRoleName ? (
<Text type="secondary">
(下单填写:{selected.bindingEvidence.mismatchedRole.expectedRoleName})
</Text>
) : null}
</Space>
) : (
<Text type="secondary">未扫码(账号已有角色仅作参考)</Text>
)}
</Descriptions.Item>
<Descriptions.Item label="账号当前角色" span={2}>
{selected.bindingEvidence.accountCurrentRole ? (
<Text>{selected.bindingEvidence.accountCurrentRole}</Text>
) : (
<Text type="secondary">-</Text>
)}
{selected.bindingEvidence.baselineRole ? (
<Text type="secondary">(扫码前基线:{selected.bindingEvidence.baselineRole})</Text>
) : null}
</Descriptions.Item>
<Descriptions.Item label="本次可确认" span={2}>
<Space wrap>
<Tag color={selected.bindingEvidence.confirmable ? 'green' : 'default'}>
{selected.bindingEvidence.confirmable ? '可以确认' : '不可确认'}
</Tag>
<Text type="secondary">
{selected.bindingEvidence.decisionReason || '-'}
</Text>
{selected.bindingEvidence.samePair ? (
<Tag color="blue">本次扫码与账号当前角色相同,可复用</Tag>
) : selected.bindingEvidence.accountCurrentRole && !selected.bindingEvidence.scannedRole ? (
<Tag>账号已有角色,本次未扫码</Tag>
) : null}
</Space>
</Descriptions.Item>
<Descriptions.Item label="角色 7 天锁" span={2}>
{selected.bindingEvidence.roleLock ? (
<Text>
{selected.bindingEvidence.roleLock.roleName} 已绑{' '}
{selected.bindingEvidence.roleLock.accountName},
{formatTime(selected.bindingEvidence.roleLock.reusableAt)} 后可复用
</Text>
) : (
<Text type="secondary">未发现(仅本系统记录)</Text>
)}
</Descriptions.Item>
<Descriptions.Item label="账号 7 天锁" span={2}>
{selected.bindingEvidence.accountLock ? (
<Text>
7 天内绑过 {selected.bindingEvidence.accountLock.roleName},
{formatTime(selected.bindingEvidence.accountLock.reusableAt)} 后可换绑
</Text>
) : (
<Text type="secondary">未发现(仅本系统记录)</Text>
)}
</Descriptions.Item>
</Descriptions>
</Space>
) : (
<Text type="secondary">暂无绑定证据</Text>
)}
</Card>
<Card size="small" title="角色接口日志(诊断)">
{detail?.bindingLogs?.length ? (
<Table<PlatformFulfillmentBindingLog>
size="small"
rowKey="id"
pagination={false}
dataSource={detail.bindingLogs}
scroll={{ x: 1180, y: 260 }}
columns={[
{
title: '时间',
dataIndex: 'createdAt',
width: 150,
render: (value: string) => formatTime(value),
},
{ title: '阶段', dataIndex: 'stage', width: 170 },
{ title: '通道', dataIndex: 'actAlias', width: 135 },
{ title: '角色', dataIndex: 'roleName', width: 120, render: (v: string) => v || '-' },
{
title: '区服平台',
key: 'channel',
width: 145,
render: (_: unknown, row: PlatformFulfillmentBindingLog) =>
[row.areaName, row.platName].filter(Boolean).join(' / ') || '-',
},
{
title: '标志 (act/role/needAct/needRole)',
key: 'flags',
width: 185,
render: (_: unknown, row: PlatformFulfillmentBindingLog) => (
<Text code style={{ fontSize: 12 }}>
{`${row.bindAct ? 1 : 0}/${row.bindRole ? 1 : 0}/${row.needBindAct ? 1 : 0}/${row.needBindRole ? 1 : 0}`}
</Text>
),
},
{
title: '换绑等待',
dataIndex: 'changeRoleWaitTime',
width: 90,
render: (value: number | null) => value ?? '-',
},
{
title: '结果',
dataIndex: 'message',
render: (value: string, row: PlatformFulfillmentBindingLog) =>
row.error === 0 ? 'OK' : `${String(row.error ?? '')} ${value || ''}`.trim(),
},
]}
/>
) : (
<Text type="secondary">暂无接口日志</Text>
)}
</Card>
<Card size="small" title="精英宝典操作">
<Space direction="vertical" size={12} style={{ width: '100%' }}>
<Text type="secondary">
直接复用斗鱼精英宝典工作台任务,作用于当前履约账号;开通和充值会在任务窗口展示支付二维码。
</Text>
<Space wrap>
<Button
icon={<SyncOutlined />}
disabled={!selected.account || !can('douyu:task')}
loading={bindingRefreshing}
onClick={() => void refreshSelectedBinding()}
>
刷新角色绑定
</Button>
<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={closeBindingQr}
>
<Space direction="vertical" align="center" style={{ width: '100%' }}>
{bindingQrLoading ? (
<Text type="secondary">正在加载小程序码...</Text>
) : bindingQrImage ? (
<div style={{
display: 'inline-flex',
padding: 10,
borderRadius: 8,
background: '#fff',
lineHeight: 0,
}}>
<img
src={bindingQrImage}
alt="客户扫码绑定小程序码"
style={{ width: 260, height: 260, objectFit: 'contain' }}
/>
</div>
) : 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
title={`人工强制确认 ${manualBindTarget ? `#${manualBindTarget.id}` : ''}`}
open={Boolean(manualBindTarget)}
okText="强制绑定"
cancelText="取消"
confirmLoading={manualBinding}
okButtonProps={{
disabled: manualBindMismatch || !manualBindRole.trim() || manualBindNote.trim().length < 2,
}}
onOk={() => void confirmManualBinding()}
onCancel={() => {
setManualBindTarget(null);
setManualBindRole('');
setManualBindNote('');
}}
>
<Space direction="vertical" size={12} style={{ width: '100%' }}>
<Alert
type="warning"
showIcon
message="强制确认会跳过 actBind 直接把订单标记为已绑定"
description="只在账号当前角色已经确认绑定到该角色、但缺少本次扫码证据时使用;必须填写依据。普通代确认请用“代客户确认”。"
/>
{manualBindMismatch ? (
<Alert
type="error"
showIcon
message="确认角色与账号当前角色不一致"
description="人工确认只能用于账号已经绑定到该角色的场景;换绑必须先完成 actBind 或使用正确账号。"
/>
) : null}
<Text type="secondary">
账号当前角色:{manualBindTarget?.bindingEvidence?.accountCurrentRole || '未知'}
{manualBindTarget?.bindingEvidence?.scannedRole
? `;本次扫码角色:${manualBindTarget.bindingEvidence.scannedRole}`
: ';本次未扫码'}
</Text>
<div>
<Text strong>确认角色</Text>
<Input
value={manualBindRole}
maxLength={128}
placeholder="客户确认的游戏角色"
onChange={(event) => setManualBindRole(event.target.value)}
style={{ marginTop: 8 }}
/>
</div>
<div>
<Text strong>确认依据 / 备注</Text>
<Input.TextArea
rows={3}
maxLength={500}
showCount
value={manualBindNote}
placeholder="例如:客户已在精英宝典完成绑定,客服核对角色一致"
onChange={(event) => setManualBindNote(event.target.value)}
style={{ marginTop: 8 }}
/>
</div>
</Space>
</Modal>
<Modal
title={`修改用户资料 ${profileEditTarget ? `#${profileEditTarget.id}` : ''}`}
open={Boolean(profileEditTarget)}
okText="保存资料"
cancelText="取消"
confirmLoading={profileEditSaving}
okButtonProps={{ disabled: !profileEditRole.trim() }}
onOk={() => void saveCustomerProfile()}
onCancel={() => setProfileEditTarget(null)}
>
<Space direction="vertical" size={12} style={{ width: '100%' }}>
<Alert
type="info"
showIcon
message="请对照客户主页截图核对并修正"
description="修改后会同步写入时间线和订单侧;若正在扫码中会立即按新角色名重算。"
/>
<div>
<Text strong>客户游戏角色名</Text>
<Input
value={profileEditRole}
maxLength={128}
placeholder="请输入正确游戏角色名"
onChange={(event) => setProfileEditRole(event.target.value)}
style={{ marginTop: 8 }}
/>
</div>
<Row gutter={12}>
<Col span={12}>
<Text strong>登录方式</Text>
<Select
value={profileEditPlatform}
onChange={(value) => setProfileEditPlatform(value)}
style={{ width: '100%', marginTop: 8 }}
options={[
{ value: 'wechat', label: '微信' },
{ value: 'qq', label: 'QQ' },
]}
/>
</Col>
<Col span={12}>
<Text strong>系统</Text>
<Select
value={profileEditSystem}
onChange={(value) => setProfileEditSystem(value)}
style={{ width: '100%', marginTop: 8 }}
options={[
{ value: 'ios', label: '苹果' },
{ value: 'android', label: '安卓' },
]}
/>
</Col>
</Row>
{profileEditTarget?.bindingStatus === 'failed' ? (
<Space align="center">
<Switch checked={profileEditReopen} onChange={setProfileEditReopen} />
<Text>保存后重置绑定失败状态(清空旧报错,便于重新出码扫码)</Text>
</Space>
) : null}
</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={1080}
footer={null}
onCancel={() => {
setMappingOpen(false);
setMappingEditorOpen(false);
}}
>
<Space direction="vertical" size={12} style={{ width: '100%' }}>
<Space wrap style={{ width: '100%', justifyContent: 'space-between' }}>
<Space wrap>
<Input.Search
allowClear
value={mappingKeyword}
placeholder="搜索内部 SKU / 商品"
style={{ width: 260 }}
onChange={(event) => setMappingKeyword(event.target.value)}
onSearch={(value) => {
setMappingKeyword(value);
void loadMappingRows(value).catch((error) => message.error(getErrorMessage(error)));
}}
/>
<Select
value={mappingFilterMode}
options={[
{ value: '', label: '全部销售模式' },
...Object.entries(SALE_MODE_LABELS).map(([value, label]) => ({ value, label })),
]}
onChange={(value) => {
setMappingFilterMode(value);
void loadMappingRows(mappingKeyword.trim(), value).catch((error) => message.error(getErrorMessage(error)));
}}
style={{ width: 150 }}
/>
<Space size={6}>
<Text type="secondary">显示已归档</Text>
<Switch
checked={mappingIncludeArchived}
onChange={(checked) => {
setMappingIncludeArchived(checked);
void loadMappingRows(mappingKeyword.trim(), mappingFilterMode, checked).catch((error) => message.error(getErrorMessage(error)));
}}
/>
</Space>
</Space>
<Space>
<Button icon={<ReloadOutlined />} onClick={() => void loadMappingRows().catch((error) => message.error(getErrorMessage(error)))}>
刷新
</Button>
<Button type="primary" onClick={openMappingCreate}>
新建映射
</Button>
</Space>
</Space>
<Text type="secondary" style={{ fontSize: 12 }}>
共 {mappings.length} 条映射;编辑、停用、归档、删除都在“更多”里,不需要横向滚动。
</Text>
<Table<PlatformFulfillmentMapping>
rowKey="id"
size="small"
tableLayout="fixed"
pagination={{ pageSize: 10, hideOnSinglePage: true, showSizeChanger: false }}
dataSource={mappings}
columns={[
{
title: '内部 SKU',
dataIndex: 'internalSkuKey',
width: 170,
ellipsis: true,
render: (value: string, row) => (
<Space direction="vertical" size={0} style={{ maxWidth: '100%' }}>
<Text strong ellipsis style={{ maxWidth: '100%' }}>{value}</Text>
<Text type="secondary" style={{ fontSize: 12 }} ellipsis>
{row.campaignName || row.campaignKey || '-'}
</Text>
</Space>
),
},
{
title: '商品',
dataIndex: 'goodsName',
width: 250,
ellipsis: true,
render: (value: string, row) => (
<Space direction="vertical" size={0} style={{ maxWidth: '100%' }}>
<Text ellipsis style={{ maxWidth: '100%' }}>{value || row.commodityId || '-'}</Text>
<Text type="secondary" style={{ fontSize: 12 }} ellipsis>
{row.commodityId}
</Text>
</Space>
),
},
{
title: '分类',
key: 'saleMode',
width: 90,
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>
</Space>
),
},
{ title: '积分', dataIndex: 'requiredPoints', width: 70 },
{ title: '影响任务', dataIndex: 'affectedTasks', width: 80 },
{
title: '状态',
dataIndex: 'enabled',
width: 80,
render: (value: boolean, row) => (
<Tag color={row.archivedAt ? 'default' : value ? 'green' : 'orange'}>
{row.archivedAt ? '已归档' : value ? '启用' : '停用'}
</Tag>
),
},
{
title: '操作',
key: 'actions',
width: 250,
render: (_: unknown, row) => (
<Space size={2} wrap>
<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>
),
},
]}
/>
</Space>
</Modal>
<Modal
title={mappingEditingId ? '编辑商品映射' : '新建商品映射'}
open={mappingEditorOpen}
width={620}
centered
okText="保存映射"
cancelText="取消"
confirmLoading={mappingSaving}
onOk={() => void saveMapping()}
onCancel={() => setMappingEditorOpen(false)}
>
<Space direction="vertical" size={14} style={{ width: '100%' }}>
<div>
<Text strong>内部 SKU</Text>
<Input
value={mappingSku}
placeholder="例如 套装-兔兔白日梦"
onChange={(event) => setMappingSku(event.target.value)}
style={{ marginTop: 6 }}
/>
</div>
<Row gutter={12}>
<Col span={12}>
<Text strong>活动批次</Text>
<Input
value={mappingCampaignKey}
placeholder="douyu-current"
onChange={(event) => setMappingCampaignKey(event.target.value)}
style={{ marginTop: 6 }}
/>
</Col>
<Col span={12}>
<Text strong>活动名称</Text>
<Input
value={mappingCampaignName}
placeholder="例如 11 月返场"
onChange={(event) => setMappingCampaignName(event.target.value)}
style={{ marginTop: 6 }}
/>
</Col>
</Row>
<div>
<Text strong>斗鱼精英宝典商品</Text>
<Space.Compact style={{ width: '100%', marginTop: 6 }}>
<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>
</div>
<Row gutter={12}>
<Col span={9}>
<Text strong>销售模式</Text>
<Select
value={mappingSaleMode}
options={Object.entries(SALE_MODE_LABELS).map(([value, label]) => ({ value, label }))}
onChange={setMappingSaleMode}
style={{ width: '100%', marginTop: 6 }}
/>
</Col>
<Col span={8}>
<Text strong>所需积分</Text>
<InputNumber
min={0}
value={mappingPoints}
onChange={(value) => setMappingPoints(value)}
style={{ width: '100%', marginTop: 6 }}
/>
</Col>
<Col span={7}>
<Text strong>启用</Text>
<div style={{ marginTop: 6 }}>
<Switch checked={mappingEnabled} onChange={setMappingEnabled} />
</div>
</Col>
</Row>
<div>
<Text strong>商品开放时间</Text>
<Space wrap style={{ width: '100%', marginTop: 6 }}>
<DatePicker showTime value={mappingAvailableFrom} onChange={setMappingAvailableFrom} placeholder="开始时间" />
<Text>至</Text>
<DatePicker showTime value={mappingAvailableUntil} onChange={setMappingAvailableUntil} placeholder="结束时间" />
</Space>
</div>
<Alert
type={mappingEditingId ? 'info' : 'success'}
showIcon
message={mappingEditingId ? '修改后会同步影响订单选号和兑换资格判断' : '保存后会立即进入商品映射列表'}
description="内部 SKU 必须和 order_site 订单商品一致;商品 ID 来自斗鱼精英宝典活动。"
/>
</Space>
</Modal>
</Space>
);
}