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 = { wechat: '微信', qq: 'QQ', }; const CUSTOMER_SYSTEM_LABELS: Record = { ios: '苹果', android: '安卓', }; function customerMatchTone(profile: NonNullable) { 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 = { 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: '待扫码', waiting_bind: '待重新绑定', role_ready: '待确认角色', bound: '已绑定', failed: '绑定失败', }; const BINDING_STATUS_COLORS: Record = { not_started: 'default', preparing: 'processing', qr_pending: 'gold', waiting_bind: 'orange', role_ready: 'purple', bound: 'green', failed: 'red', }; 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 MANUAL_REASON_LABELS: Record = { 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 = { 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: '忽略账号旧角色', 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 = { 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 = { 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 }) { 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('、') || '未满足分配条件'}`; }); if (lines.length) return lines.join(';'); const counts = detail.availabilityCounts && typeof detail.availabilityCounts === 'object' ? (detail.availabilityCounts as Record) : {}; 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([]); 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 [manualBindTarget, setManualBindTarget] = useState(null); const [manualBindRole, setManualBindRole] = useState(''); const [manualBindNote, setManualBindNote] = useState(''); const [manualBinding, setManualBinding] = useState(false); const [profileEditTarget, setProfileEditTarget] = useState(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([]); const [selectedId, setSelectedId] = useState(null); const [detail, setDetail] = useState(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(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 = [ '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: ( {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 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 = {}; 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 = [ { 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: 270, render: (_, task) => ( {task.goodsName || task.skuName || task.internalSkuKey || '未映射'} {SALE_MODE_LABELS[task.saleMode] || task.saleMode} {task.requiredPoints != null ? `${task.requiredPoints} 积分` : '价格未知'} {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: 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 ( {bindingStatusLabel(task.bindingStatus)} {task.account && task.bindingStatus === 'failed' ? ( 账号保留中 ) : null} 客户提交角色:{customerRole || '未填写'} 扫码绑定角色:{scannedRole || '未识别'} {scannedRole && scannedChannel ? ` · ${scannedChannel}` : ''} {task.bindingStatus === 'bound' ? ( 换绑时间:{formatTime(task.account?.roleChangeAvailableAt) || '无冷却'} ) : null} ); }, }, { title: '游戏主页', key: 'customer_home_images', width: 120, render: (_, task) => { const images = task.customerProfile?.homeImages || []; if (images.length === 0) return 未上传; return ( item.url)}> {images.slice(0, 2).map((item, index) => ( {`游戏主页截图 ))} ); }, }, { 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) => ( {saleModeTab === 'presale' ? ( ) : null} {task.executionStatus === 'pending_mapping' ? ( ) : null} {task.executionStatus === 'ready' ? ( ) : null} {canRefreshBindingQr(task) ? ( ) : null} {canReallocateAndBind(task) ? ( ) : null} {task.account && task.bindingStatus === 'failed' ? ( ) : null} {task.executionStatus === 'role_ready' ? ( ) : null} {canManualConfirmBinding(task) && task.executionStatus !== 'role_ready' && task.bindTask?.roleName ? ( ) : null} {can('platform_fulfillment:use') && canManualConfirmBinding(task) ? ( ) : null} {canResetBinding(task) ? ( ) : null} {task.executionStatus === 'bound' ? ( <> ) : null} ), }, ]; 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 ? ( {selected.bindTask?.qrUrl ? ( ) : null} {selected.account ? ( ) : null} {selected && canRefreshBindingQr(selected) ? ( ) : null} {selected && canReallocateAndBind(selected) ? ( ) : null} {selected && selected.executionStatus !== 'role_ready' && selected.executionStatus !== 'bound' && (selected.bindingEvidence?.scannedRole || selected.bindTask?.roleName) ? ( ) : null} {selected && can('platform_fulfillment:use') && canManualConfirmBinding(selected) ? ( ) : null} {selected && selected.account && selected.bindingStatus === 'bound' && !['completed', 'cancelled'].includes(selected.executionStatus) && can('platform_fulfillment:use') ? ( ) : 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) : '-'} {saleModeTab === 'presale' ? ( ) : null}
{ 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' ? ( ) : null} { setKeyword(event.target.value); setPage(1); }} style={{ width: 300 }} /> { setQueueBucket(String(value)); setSelectedRowKeys([]); setPage(1); }} /> 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: }} /> {statusLabel(selected.executionStatus)} {exchangeStatusLabel(selected.exchangeStatus)}
) : null } onClose={() => setSelectedId(null)} > {detailLoading || !selected ? ( 加载中... ) : ( {selected.issueCode || selected.lastError ? ( ) : exchangeStatusHint(selected.exchangeStatus) ? ( ) : null} {selected.exchangeResultImage ? ( )} >
setExchangeImageViewer({ url: selected.exchangeResultImage!.url, title: `斗鱼兑换结果-${selected.skuName || selected.platformOrderId}`, })} style={{ cursor: 'zoom-in', textAlign: 'center' }} title="点击查看大图" > 兑换结果凭证
) : null}
{selected.platformOrderId || '-'} {selected.skuName || selected.internalSkuKey || '-'} {selected.internalSkuKey || '-'} {selected.goodsName || selected.skuName || '未映射'} {SALE_MODE_LABELS[selected.saleMode] || selected.saleMode} {selected.campaignName || selected.campaignKey || '-'} {money(selected.orderAmountFen)} {selected.requiredPoints ?? '-'} {statusLabel(selected.executionStatus)} {bindingStatusLabel(selected.bindingStatus)} {selected.collabOrder ? `${selected.collabOrder.orderNo} · ${collabStatusLabel(selected.collabOrder.status)}` : '未同步'} {exchangeStatusLabel(selected.exchangeStatus)} {issueLabel(selected.issueCode)} openProfileEdit(selected)}> 修改资料 ) : null } > {selected.customerProfile ? ( {selected.customerProfile.roleName || '未填写'} {CUSTOMER_PLATFORM_LABELS[selected.customerProfile.platform] || selected.customerProfile.platform || '-'} {CUSTOMER_SYSTEM_LABELS[selected.customerProfile.system] || selected.customerProfile.system || '-'} {selected.customerProfile.platformRoleName || '未识别'} {selected.customerProfile.platformChannel || '-'} {selected.customerProfile.message} {selected.customerProfile.updatedAt ? ( 更新 {formatTime(selected.customerProfile.updatedAt)} ) : null} {selected.customerProfile.homeImages.length ? ( item.url)} > {selected.customerProfile.homeImages.map((item, index) => ( {`游戏主页截图 ))} ) : ( 没有游戏主页截图 )} ) : ( )} {selected.account ? ( {selected.account.nickname || selected.account.username} {ckStatusLabel(selected.account.ckCheckStatus)} {eliteOpenedLabel(selected.account.eliteOpened)} {selected.account.points ?? '-'} {selected.account.goldBalance ?? '-'} {bindStatusLabel(selected.account.roleBindStatus)} {selected.account.gameName || '-'} {selected.account.gameChannel || '-'} {formatTime(selected.account.roleChangeAvailableAt) || '无冷却'} {selected.lease ? leaseExpiresLabel(selected.lease.expiresAt) : '-'} ) : ( )}
{selected.bindingEvidence ? ( {!selected.bindingEvidence.scannedRole && selected.bindingEvidence.accountCurrentRole ? ( ) : null} {selected.bindingEvidence.actionAliases.join(' / ') || '-'} {' '}系统选中:{selected.bindingEvidence.selectedAlias || '-'} {selected.bindingEvidence.selectedActionable ? '(动作通道)' : '(非动作通道)'} {selected.bindingEvidence.actionCurrent ? ( bindAct=1 {selected.bindingEvidence.actionCurrent.roleName} {selected.bindingEvidence.actionCurrent.channel ? ( {selected.bindingEvidence.actionCurrent.channel} ) : null} ) : ( 未识别 )} {selected.bindingEvidence.actionPending ? ( bindAct=0 {selected.bindingEvidence.actionPending.roleName} {selected.bindingEvidence.actionPending.channel ? ( {selected.bindingEvidence.actionPending.channel} ) : null} ) : ( 未出现(等待动作通道) )} {selected.bindingEvidence.legacyLatest ? ( legacy {selected.bindingEvidence.legacyLatest.roleName} 不能直接确认 ) : ( - )} {selected.bindingEvidence.scannedRole ? ( {selected.bindingEvidence.scannedRole} ) : selected.bindingEvidence.mismatchedRole ? ( 扫到不匹配角色 {selected.bindingEvidence.mismatchedRole.roleName} {selected.bindingEvidence.mismatchedRole.channel ? ( {selected.bindingEvidence.mismatchedRole.channel} ) : null} {selected.bindingEvidence.mismatchedRole.expectedRoleName ? ( (下单填写:{selected.bindingEvidence.mismatchedRole.expectedRoleName}) ) : null} ) : ( 未扫码(账号已有角色仅作参考) )} {selected.bindingEvidence.accountCurrentRole ? ( {selected.bindingEvidence.accountCurrentRole} ) : ( - )} {selected.bindingEvidence.baselineRole ? ( (扫码前基线:{selected.bindingEvidence.baselineRole}) ) : null} {selected.bindingEvidence.confirmable ? '可以确认' : '不可确认'} {selected.bindingEvidence.decisionReason || '-'} {selected.bindingEvidence.samePair ? ( 本次扫码与账号当前角色相同,可复用 ) : selected.bindingEvidence.accountCurrentRole && !selected.bindingEvidence.scannedRole ? ( 账号已有角色,本次未扫码 ) : null} {selected.bindingEvidence.roleLock ? ( {selected.bindingEvidence.roleLock.roleName} 已绑{' '} {selected.bindingEvidence.roleLock.accountName}, {formatTime(selected.bindingEvidence.roleLock.reusableAt)} 后可复用 ) : ( 未发现(仅本系统记录) )} {selected.bindingEvidence.accountLock ? ( 7 天内绑过 {selected.bindingEvidence.accountLock.roleName}, {formatTime(selected.bindingEvidence.accountLock.reusableAt)} 后可换绑 ) : ( 未发现(仅本系统记录) )} ) : ( 暂无绑定证据 )} {detail?.bindingLogs?.length ? ( 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) => ( {`${row.bindAct ? 1 : 0}/${row.bindRole ? 1 : 0}/${row.needBindAct ? 1 : 0}/${row.needBindRole ? 1 : 0}`} ), }, { 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(), }, ]} /> ) : ( 暂无接口日志 )} 直接复用斗鱼精英宝典工作台任务,作用于当前履约账号;开通和充值会在任务窗口展示支付二维码。 setGoldAmount(Number(value) || 1)} addonBefore="鱼翅" style={{ width: 150 }} /> setGiftCount(Number(value) || 1)} addonBefore="数量" style={{ width: 130 }} /> {actionButtons}
Date.parse(right.createdAt) - Date.parse(left.createdAt)) .slice(0, 50) .map((event) => ({ color: eventColor(event.eventType), children: ( {eventLabel(event.eventType)} {eventDescription(event)} {formatTime(event.createdAt)} ·{' '} {event.actorRoleLabel || ACTOR_TYPE_LABELS[event.actorType] || '系统'} {event.actorName ? ` · ${event.actorName}` : ''} {event.actorId ? ` · ID ${event.actorId}` : ''} ), }))} />
)} 关闭 } onCancel={closeDouyuAction} width={520} > {douyuActionTask ? ( <> {TASK_STATUS_LABELS[douyuActionTask.status] || douyuActionTask.status} {douyuActionTask.message || '任务执行中'} {douyuActionQrValue ? ( ) : null} {douyuActionType === 'exchange_goods' && douyuActionTask.status === 'success' ? ( setExchangeImageViewer({ url, title: `斗鱼兑换结果-${selected?.skuName || selected?.platformOrderId || douyuActionTask.id}`, })} /> ) : null} ) : ( 任务已提交,正在等待斗鱼执行器返回结果... )} )} onCancel={() => setExchangeImageViewer(null)} > {exchangeImageViewer ? ( 兑换结果 ) : null} {bindingQrLoading ? ( 正在加载小程序码... ) : bindingQrImage ? (
客户扫码绑定小程序码
) : qrValue ? ( ) : null} 请客户使用对应游戏平台扫码。二维码只用于当前履约作业。
void restoreTask()} onCancel={() => { setRestoreTarget(null); setRestoreReason(''); }} > setRestoreReason(event.target.value)} /> void releaseTaskToManual()} onCancel={() => { setManualReleaseTarget(null); setManualReleaseReason(''); }} > setManualReleaseReason(event.target.value)} /> void confirmManualBinding()} onCancel={() => { setManualBindTarget(null); setManualBindRole(''); setManualBindNote(''); }} > {manualBindMismatch ? ( ) : null} 账号当前角色:{manualBindTarget?.bindingEvidence?.accountCurrentRole || '未知'} {manualBindTarget?.bindingEvidence?.scannedRole ? `;本次扫码角色:${manualBindTarget.bindingEvidence.scannedRole}` : ';本次未扫码'}
确认角色 setManualBindRole(event.target.value)} style={{ marginTop: 8 }} />
确认依据 / 备注 setManualBindNote(event.target.value)} style={{ marginTop: 8 }} />
void saveCustomerProfile()} onCancel={() => setProfileEditTarget(null)} >
客户游戏角色名 setProfileEditRole(event.target.value)} style={{ marginTop: 8 }} />
登录方式 setProfileEditSystem(value)} style={{ width: '100%', marginTop: 8 }} options={[ { value: 'ios', label: '苹果' }, { value: 'android', label: '安卓' }, ]} /> {profileEditTarget?.bindingStatus === 'failed' ? ( 保存后重置绑定失败状态(清空旧报错,便于重新出码扫码) ) : null}
void saveLeaseSettings()} onCancel={() => setSettingsOpen(false)} >
订单匹配起算时间 只同步此时间之后支付的 order_site 人工订单,历史任务保留但不再展示或自动处理。
进行中任务兜底 TTL setLeaseDurationMode(value as 'unlimited' | 'minutes' | 'hours')} options={[ { label: '无限制', value: 'unlimited' }, { label: '按分钟', value: 'minutes' }, { label: '按小时', value: 'hours' }, ]} /> {leaseDurationMode !== 'unlimited' ? ( ) : null} 默认无限制。这里的 TTL 只作用于普通进行中状态,不会覆盖预售等待开放和人工处理状态。
终态释放与特殊状态策略 留空表示永久保留;0 表示命中该状态后立即释放。 自动兑换完成保留 人工兑换完成保留 预售等待开放 TTL 人工处理 TTL
{ setMappingOpen(false); setMappingEditorOpen(false); }} > setMappingKeyword(event.target.value)} onSearch={(value) => { setMappingKeyword(value); void loadMappingRows(value).catch((error) => message.error(getErrorMessage(error))); }} /> setMappingSku(event.target.value)} style={{ marginTop: 6 }} /> 活动批次 setMappingCampaignKey(event.target.value)} style={{ marginTop: 6 }} /> 活动名称 setMappingCampaignName(event.target.value)} style={{ marginTop: 6 }} />
斗鱼精英宝典商品 ({ value, label }))} onChange={setMappingSaleMode} style={{ width: '100%', marginTop: 6 }} /> 所需积分 setMappingPoints(value)} style={{ width: '100%', marginTop: 6 }} /> 启用
商品开放时间 至
); }