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 = { 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 = { incomplete: '待补资料', to_recharge: '待充值', recharged: '已充值', scripted: '已上脚本', done: '抢购成功', points_error: '积分异常', role_error: '账号角色异常', failed: '抢购失败', void: '已作废', }; const BINDING_STATUS_LABELS: Record = { not_started: '未开始', preparing: '准备中', qr_pending: '待扫码', role_ready: '待确认角色', bound: '已绑定', failed: '绑定失败', }; const EXCHANGE_STATUS_LABELS: Record = { not_started: '未开始', eligible: '可兑换', points_short: '积分不足', not_opened: '精英宝典未开通', limited: '已达限兑上限', not_available: '商品当前不可兑换', check_failed: '资格查询失败', manual_done: '人工兑换完成', }; const SALE_MODE_LABELS: Record = { presale: '预售', direct: '直接兑换', manual: '人工', unknown: '未分类', }; const AVAILABILITY_LABELS: Record = { waiting_release: '待开放', available: '可兑换', sold_out: '已售罄', ended: '已结束', unknown: '未知', }; const MANUAL_REASON_LABELS: Record = { 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 = { system: '系统', user: '操作人', customer: '客户', connector: '连接器', }; const EVENT_LABELS: Record = { 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 = { 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 = { 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 }) { 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) : {}; 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([]); const [total, setTotal] = useState(0); const [loading, setLoading] = useState(false); const [syncing, setSyncing] = useState(false); const [collabSyncing, setCollabSyncing] = useState(false); const [rowCollabSyncingId, setRowCollabSyncingId] = useState(null); const [allocatingTaskId, setAllocatingTaskId] = useState(null); const [restoreTarget, setRestoreTarget] = useState(null); const [restoreReason, setRestoreReason] = useState(''); const [restoring, setRestoring] = useState(false); const [manualReleaseTarget, setManualReleaseTarget] = useState(null); const [manualReleaseReason, setManualReleaseReason] = useState(''); const [manualReleasing, setManualReleasing] = useState(false); const [selectedRowKeys, setSelectedRowKeys] = useState([]); const [selectedId, setSelectedId] = useState(null); const [detail, setDetail] = useState(null); const [detailLoading, setDetailLoading] = useState(false); const [qrOpen, setQrOpen] = useState(false); const [mappingOpen, setMappingOpen] = useState(false); const [mappingSku, setMappingSku] = useState(''); const [mappingEditingId, setMappingEditingId] = useState(null); const [mappingCampaignKey, setMappingCampaignKey] = useState('douyu-current'); const [mappingCampaignName, setMappingCampaignName] = useState(''); const [mappingGoodsId, setMappingGoodsId] = useState(''); const [mappingGoodsName, setMappingGoodsName] = useState(''); const [mappingPoints, setMappingPoints] = useState(null); const [mappingEnabled, setMappingEnabled] = useState(true); const [mappingSaleMode, setMappingSaleMode] = useState<'presale' | 'direct' | 'manual' | 'unknown'>('unknown'); const [mappingAvailableFrom, setMappingAvailableFrom] = useState(null); const [mappingAvailableUntil, setMappingAvailableUntil] = useState(null); const [mappingFilterMode, setMappingFilterMode] = useState(''); const [mappingIncludeArchived, setMappingIncludeArchived] = useState(false); const [goods, setGoods] = useState([]); const [mappingGoodsLoading, setMappingGoodsLoading] = useState(false); const [mappings, setMappings] = useState([]); const [settings, setSettings] = useState(null); const [settingsOpen, setSettingsOpen] = useState(false); const [leaseDurationMode, setLeaseDurationMode] = useState<'unlimited' | 'minutes' | 'hours'>('unlimited'); const [leaseDurationValue, setLeaseDurationValue] = useState(60); const [completedReleaseDelay, setCompletedReleaseDelay] = useState(30); const [manualCompletedReleaseDelay, setManualCompletedReleaseDelay] = useState(120); const [presaleWaitingReleaseTtl, setPresaleWaitingReleaseTtl] = useState(null); const [manualRequiredLeaseTtl, setManualRequiredLeaseTtl] = useState(null); const [orderMatchStartedAt, setOrderMatchStartedAt] = useState(null); const [savingSettings, setSavingSettings] = useState(false); const [douyuActionLoading, setDouyuActionLoading] = useState(''); const [douyuActionType, setDouyuActionType] = useState(''); const [douyuActionBatchId, setDouyuActionBatchId] = useState(''); const [douyuActionTask, setDouyuActionTask] = useState(null); const [exchangeImageViewer, setExchangeImageViewer] = useState<{ url: string; title: string; } | null>(null); const exchangeImageSaveAttempts = useRef(new Set()); 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: ( {problems.slice(0, 20).map((item) => ( #{item.taskId}:{item.reason || '未同步'} ))} {problems.length > 20 ? ( 另有 {problems.length - 20} 条未显示 ) : null} ), }); } 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) => { 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 = {}; 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 = [ { title: '任务 ID', dataIndex: 'id', key: 'id', width: 100, fixed: 'left', render: (value: number) => ( #{value} ), }, { title: '订单 / 商品', key: 'order', width: 280, render: (_, task) => ( {task.platformOrderId || `#${task.sourceOrderId}`} {task.skuName || task.internalSkuKey || '-'} {providerLabel(task.provider)} / {task.shopName || task.shopId || '-'} 支付时间:{task.paidAt ? formatTime(task.paidAt) : '-'} ), }, { title: '商品映射', key: 'mapping', width: 230, render: (_, task) => ( {task.goodsName || task.skuName || task.internalSkuKey || '未映射'} {task.requiredPoints != null ? `${task.requiredPoints} 积分` : '价格未知'} ), }, { title: '分类', key: 'classification', width: 190, render: (_, task) => ( {SALE_MODE_LABELS[task.saleMode] || task.saleMode} {AVAILABILITY_LABELS[task.availabilityState] || task.availabilityState} {task.campaignName || task.campaignKey || '未设置活动批次'} {task.offerAvailableFrom ? ( 开放:{formatTime(task.offerAvailableFrom)} ) : null} ), }, { title: '订单金额', dataIndex: 'orderAmountFen', width: 110, render: (value: number) => money(value), }, { title: '账号', key: 'account', width: 190, render: (_, task) => task.account ? ( {task.account.nickname || task.account.username} 积分 {task.account.points ?? '-'} · 鱼翅 {task.account.goldBalance ?? '-'} 租约 {task.lease ? '占用中' : '未占用'} · {task.lease ? leaseExpiresLabel(task.lease.expiresAt) : '-'} ) : ( 未分配 ), }, { title: '绑定', key: 'binding', width: 180, render: (_, task) => ( {bindingStatusLabel(task.bindingStatus)} {task.bindTask?.roleName || (task.bindTask?.bindPhase === 'role_ready' ? '角色待确认' : '-')} ), }, { title: '状态', key: 'status', width: 180, render: (_, task) => ( {statusLabel(task.executionStatus)} 兑换:{exchangeStatusLabel(task.exchangeStatus)} {task.manualReason ? ( {MANUAL_REASON_LABELS[task.manualReason] || task.manualReason} ) : null} ), }, { title: '外部协作', key: 'collab', width: 150, render: (_, task) => task.collabOrder ? ( {collabStatusLabel(task.collabOrder.status)} {can('douyu:collab:view') ? ( ) : ( {task.collabOrder.orderNo} )} ) : ( 未同步 ), }, { title: '更新时间', dataIndex: 'updatedAt', width: 160, render: (value: string) => formatTime(value), }, { title: '操作', key: 'actions', width: 330, render: (_, task) => ( {task.executionStatus === 'pending_mapping' ? ( ) : null} {task.executionStatus === 'ready' ? ( ) : null} {canRefreshBindingQr(task) ? ( ) : null} {task.executionStatus === 'role_ready' ? ( ) : null} {canResetBinding(task) ? ( ) : null} {task.executionStatus === 'bound' ? ( <> ) : null} ), }, ]; const actionButtons = selected ? ( {selected.bindTask?.qrUrl ? ( ) : null} {selected.account ? ( ) : null} {selected && canRefreshBindingQr(selected) ? ( ) : null} {selected.account && selected.executionStatus !== 'completed' && selected.executionStatus !== 'cancelled' && can('platform_fulfillment:use') ? ( ) : null} {canResetBinding(selected) ? ( ) : null} {can('platform_fulfillment:cancel') && selected.executionStatus !== 'completed' && selected.executionStatus !== 'cancelled' ? ( ) : null} {can('platform_fulfillment:restore') && selected.executionStatus === 'cancelled' && selected.issueCode !== 'source_cancelled' ? ( ) : null} ) : null; return (
直播账号履约工作台 系统自动检测账号并选号;只有缺货、CK 异常或资格失败时转人工处理。客户扫码绑定后,运营可直接开通宝典、充值或兑换皮肤。
进行中租约:{leaseDurationLabel(settings?.leaseDurationMinutes)} 订单起算:{settings?.orderMatchStartedAt ? formatTime(settings.orderMatchStartedAt) : '-'}
{ setKeyword(event.target.value); setPage(1); }} style={{ width: 300 }} /> { setQueueBucket(String(value)); setPage(1); }} /> ({ value, label })), ]} onChange={(value) => { setMappingFilterMode(value); void loadMappingRows(mappingSku.trim(), value).catch((error) => message.error(getErrorMessage(error))); }} style={{ width: 160 }} /> 显示已归档 { setMappingIncludeArchived(checked); void platformFulfillmentApi.listMappings({ keyword: mappingSku.trim(), sale_mode: mappingFilterMode || undefined, include_archived: checked, }).then(setMappings).catch((error) => message.error(getErrorMessage(error))); }} /> setMappingSku(event.target.value)} style={{ width: 260 }} /> setMappingCampaignKey(event.target.value)} style={{ width: 260 }} /> setMappingCampaignName(event.target.value)} style={{ width: 220 }} /> ({ value, label }))} onChange={setMappingSaleMode} style={{ width: 140 }} /> 所需积分 setMappingPoints(value)} /> 启用
商品开放时间 至 rowKey="id" size="small" pagination={false} dataSource={mappings} columns={[ { title: '内部 SKU', dataIndex: 'internalSkuKey', width: 150 }, { title: '活动批次', key: 'campaign', width: 170, render: (_: unknown, row) => ( {row.campaignName || row.campaignKey} {row.campaignKey} ), }, { title: '商品', dataIndex: 'goodsName', width: 150 }, { title: '商品 ID', dataIndex: 'commodityId', width: 180 }, { title: '分类', key: 'saleMode', width: 130, render: (_: unknown, row) => ( {SALE_MODE_LABELS[row.saleMode] || row.saleMode} {AVAILABILITY_LABELS[row.availabilityState] || row.availabilityState} ), }, { title: '积分', dataIndex: 'requiredPoints', width: 80 }, { title: '影响任务', dataIndex: 'affectedTasks', width: 90 }, { title: '状态', dataIndex: 'enabled', width: 100, render: (value: boolean, row) => ( {row.archivedAt ? '已归档' : value ? '启用' : '停用'} ), }, { title: '操作', key: 'actions', width: 310, render: (_: unknown, row) => ( {row.archivedAt ? ( ) : ( <> )} ), }, ]} scroll={{ x: 1300 }} /> ), }, ]} /> ); }