import type { DouyuCollabGoods, DouyuCollabOrder, DouyuCollabStatus, } from '../api/douyuCollab'; export function errorCodeOf(error: unknown): string { return (error as { errorCode?: string } | null)?.errorCode || ''; } export function hasTextInputFocus(): boolean { const active = document.activeElement; return ( active instanceof HTMLElement && (active.tagName === 'INPUT' || active.tagName === 'TEXTAREA' || active.isContentEditable) ); } /** 实时同步暂停开关按浏览器记住:刷新页面后仍保持暂停,直到手动恢复。 */ export const REALTIME_PAUSED_STORAGE_KEY = 'douyu.collab.realtime-paused'; export const REALTIME_WS_PATH = '/api/douyu/external-orders/ws'; export const COLUMN_LAYOUT_STORAGE_PREFIX = 'douyu.collab.columns'; export const DEFAULT_COLUMN_LAYOUT = [ { key: 'sequence', visible: true }, { key: 'order_shop', visible: true }, { key: 'owner', visible: true }, { key: 'account', visible: true }, { key: 'bind_role', visible: true }, { key: 'home_images', visible: true }, { key: 'gift', visible: true }, { key: 'status', visible: true }, { key: 'balances', visible: true }, { key: 'last_query', visible: true }, { key: 'updated', visible: true }, { key: 'actions', visible: true }, ] as const; export const COLUMN_LABELS: Record = { sequence: '序号', order_shop: '订单 / 店铺', owner: '负责人', account: '斗鱼账号', bind_role: '绑定角色', home_images: '主页截图', gift: '礼包 / 积分', status: '状态', balances: '鱼翅 / 积分', last_query: '最近查询', updated: '最后改动', actions: '操作', }; export type ColumnPreference = { key: string; visible: boolean }; export function normalizeColumnLayout(raw: unknown): ColumnPreference[] { const defaults = DEFAULT_COLUMN_LAYOUT.map((item) => ({ ...item })); if (!Array.isArray(raw)) return defaults; const known = new Set(defaults.map((item) => item.key)); const result: ColumnPreference[] = []; const seen = new Set(); for (const item of raw) { if (!item || typeof item !== 'object') continue; const row = item as { key?: unknown; visible?: unknown }; const key = String(row.key || ''); if (!known.has(key) || seen.has(key)) continue; seen.add(key); result.push({ key, visible: key === 'actions' ? true : row.visible !== false, }); } for (const item of defaults) { if (!seen.has(item.key)) result.push(item); } return result; } export function readColumnLayout(userId?: number): ColumnPreference[] { if (!userId) return normalizeColumnLayout(null); try { const raw = window.localStorage.getItem( `${COLUMN_LAYOUT_STORAGE_PREFIX}:${userId}`, ); return normalizeColumnLayout(raw ? JSON.parse(raw) : null); } catch { return normalizeColumnLayout(null); } } export function readRealtimePaused(): boolean { try { return window.localStorage.getItem(REALTIME_PAUSED_STORAGE_KEY) === '1'; } catch { return false; } } export function cardStyle(active: boolean) { return { borderColor: active ? '#1677ff' : undefined, cursor: 'pointer', } as const; } export const STATUS_META: Record = { incomplete: { label: '待补资料', color: 'default' }, to_recharge: { label: '待充值', color: 'blue' }, recharged: { label: '已充值', color: 'cyan' }, scripted: { label: '已上脚本', color: 'purple' }, done: { label: '抢购成功', color: 'green' }, points_error: { label: '积分异常', color: 'orange' }, role_error: { label: '账号角色异常', color: 'volcano' }, failed: { label: '抢购失败', color: 'red' }, void: { label: '已作废', color: 'default' }, }; export const STATUS_ORDER: DouyuCollabStatus[] = [ 'incomplete', 'to_recharge', 'recharged', 'scripted', 'done', 'points_error', 'role_error', 'failed', 'void', ]; export const FLOW_ORDER: DouyuCollabStatus[] = [ 'incomplete', 'to_recharge', 'recharged', 'scripted', 'done', ]; export const CK_META: Record = { unverified: { label: '未检测', color: 'default' }, valid: { label: 'CK 正常', color: 'green' }, invalid: { label: 'CK 异常', color: 'red' }, error: { label: 'CK 异常', color: 'red' }, '': { label: '未检测', color: 'default' }, }; export const COLLAB_ACTION_LABELS: Record = { 'douyu:collab:create': '新建预售单', 'douyu:collab:update': '编辑订单资料', 'douyu:collab:account': '更换账号', 'douyu:collab:account_unlink': '解除账号关联', 'douyu:collab:verify': '校验账号', 'douyu:collab:status': '修改订单状态', 'douyu:collab:status_auto': '自动推进订单状态', 'douyu:collab:void': '作废订单', 'douyu:collab:void_restore': '恢复作废订单', 'douyu:collab:points_error': '标记积分异常', 'douyu:collab:role_error': '标记角色异常', 'douyu:collab:activity': '查询兑换记录', 'douyu:collab:ck_export': '导出账号与登录凭据', 'douyu:collab:archive': '归档订单', 'douyu:collab:unarchive': '取消归档', 'douyu:collab:sync_from_platform_fulfillment': '同步直播履约单', 'douyu:collab:lease_acquired': '建立账号占用', 'douyu:collab:lease_released': '释放账号占用', 'douyu:collab:lease_takeover': '接管账号占用', 'douyu:collab:goods_refresh': '刷新活动商品', 'douyu:collab:shop_update': '修改店铺', 'douyu:collab:shop_delete': '删除店铺', 'douyu:collab:gift_update': '修改礼包', 'douyu:collab:gift_delete': '删除礼包', }; export const COLLAB_DETAIL_LABELS: Record = { order_no: '订单编号', orderNo: '平台订单编号', shop: '店铺', owner_id: '负责人编号', account_id: '内部账号编号', accountId: '内部账号编号', account_username: '斗鱼账号', accountName: '账号名称', account_uid: '斗鱼用户编号', account_nickname: '账号昵称', gift_name: '礼包', commodity_id: '商品编号', required_points: '所需积分', requiredPoints: '所需积分', home_images: '主页截图', bind_game_role: '绑定角色', role: '当前角色', ck_status: '登录凭据状态', ck: '登录凭据状态', fish_fin_balance: '鱼翅', points: '积分', points_balance: '当前积分', required_total: '同账号所需积分', surplus: '积分结余', message: '说明', scope: '查询范围', verdict: '查询判定', records: '兑换记录', records_matched: '命中记录', records_total: '记录总数', from: '原状态', to: '新状态', status: '状态', rollback: '是否回退', reason: '原因', taskId: '履约任务编号', created: '是否新建', released_lease: '是否释放账号占用', previous: '原账号信息', lease_id: '账号占用编号', purpose: '占用用途', batch_id: '批次编号', draft: '是否草稿', exchangeStatus: '兑换资格', softReasons: '后续处理', eliteOpened: '精英宝典已开通', limited: '是否达到限兑上限', limitedCount: '限兑商品数量', }; export const COLLAB_DETAIL_VALUE_LABELS: Record = { valid: '正常', invalid: '异常', error: '异常', unverified: '未检测', unknown: '无法判定', success: '成功', failed: '失败', incomplete: '待补资料', to_recharge: '待充值', recharged: '已充值', scripted: '已上脚本', done: '抢购成功', points_error: '积分异常', role_error: '账号角色异常', void: '已作废', allocated: '已分配', bound: '已绑定', ready: '待分配', manual_required: '已转人工', eligible: '资格正常', points_short: '积分不足', not_opened: '精英宝典未开通', activity: '兑换记录', balances: '鱼翅与积分', balance_manual: '人工查询鱼翅与积分', balance_batch: '批量查询鱼翅与积分', batch: '批量查询', platform_fulfillment: '直播账号履约', douyu_collab: '斗鱼预售台账', }; export const COLLAB_DETAIL_PREFERRED_KEYS = Object.keys(COLLAB_DETAIL_LABELS); export function collabActionLabel(action: string): string { return COLLAB_ACTION_LABELS[action] || '其他操作'; } export function collabCkLabel(status: string): string { if (status === 'valid') return '正常'; if (status === 'invalid' || status === 'error') return '异常'; return '未检测'; } export function collabValueLabel(value: unknown): string { if (typeof value === 'boolean') return value ? '是' : '否'; if (value === null || value === undefined || value === '') return '-'; if (typeof value === 'number') return String(value); if (Array.isArray(value)) { return value.map((item) => collabValueLabel(item)).filter((item) => item !== '-').join('、') || '-'; } if (typeof value === 'object') { const row = value as Record; if ('old' in row || 'new' in row) { return `${collabValueLabel(row.old)} → ${collabValueLabel(row.new)}`; } return '-'; } const text = String(value); return COLLAB_DETAIL_VALUE_LABELS[text] || collabText(text); } export function collabText(value: string): string { return value .replace(/\bCookie\b/gi, '登录凭据') .replace(/\bCK\b/gi, '登录凭据') .replace(/\s*act=[^,,;;\s]+/gi, '') .trim(); } export function collabTimelineDetailLines(detail: string): string[] { if (!detail) return []; let parsed: unknown; try { parsed = JSON.parse(detail); } catch { return ['明细格式无法识别']; } if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { return [collabValueLabel(parsed)]; } const data = parsed as Record; const lines: string[] = []; for (const key of COLLAB_DETAIL_PREFERRED_KEYS) { if (!(key in data)) continue; const value = data[key]; if (key === 'previous' && value && typeof value === 'object' && !Array.isArray(value)) { const previous = value as Record; const parts = [ previous.account_username ? `账号 ${collabValueLabel(previous.account_username)}` : '', previous.bind_game_role ? `角色 ${collabValueLabel(previous.bind_game_role)}` : '', previous.status ? `状态 ${collabValueLabel(previous.status)}` : '', ].filter(Boolean); if (parts.length) lines.push(`${COLLAB_DETAIL_LABELS[key]}:${parts.join(';')}`); continue; } if (key === 'ck_status' || key === 'ck') { lines.push(`${COLLAB_DETAIL_LABELS[key]}:${collabCkLabel(String(value || ''))}`); continue; } if (key === 'home_images') { const count = Array.isArray(value) ? value.length : Number(value || 0); lines.push(`${COLLAB_DETAIL_LABELS[key]}:${Number.isFinite(count) ? count : 0} 张`); continue; } const text = collabValueLabel(value); if (text !== '-') lines.push(`${COLLAB_DETAIL_LABELS[key]}:${text}`); } return lines; } export function formatTime(value?: string | null): string { if (!value) return '-'; const date = new Date(value); return Number.isNaN(date.getTime()) ? value : date.toLocaleString(); } export function pointsReasonMeta(reason: string): { label: string; color: string } { if (reason === 'shortage') return { label: '积分不足', color: 'red' }; if (reason === 'excess') return { label: '积分超阈值', color: 'orange' }; if (reason === 'ok') return { label: '积分正常', color: 'green' }; return { label: '未核账', color: 'default' }; } export function goodsOptions(goods: DouyuCollabGoods[], accountSpecific = false) { return goods .filter((item) => item.commodity_id && item.name) .map((item) => { const time = item.is_limited ? ' · 23返场/限时' : ''; const accountState = accountSpecific && item.status === '1' ? ' · 该账号已兑换' : item.open_status === 0 ? ' · 未开始' : ''; return { value: item.commodity_id, label: `${item.name} · ${item.score ?? '-'} 积分${time}${accountState}`, goods: item, disabled: accountSpecific && item.status === '1', }; }); } export interface OrderFormState { order_no: string; shop: string; owner_id: number | null; account_username: string; gift_name: string; commodity_id: string; required_points: number | null; home_images: string[]; remark: string; } export const EMPTY_FORM: OrderFormState = { order_no: '', shop: '', owner_id: null, account_username: '', gift_name: '', commodity_id: '', required_points: null, home_images: [], remark: '', }; export const SUCCESS_PURCHASE_FIELD_LABELS: Record = { order_no: '订单编号', account_username: '斗鱼用户名', gift_name: '礼包', commodity_id: '商品编号', required_points: '所需积分', }; export interface SuccessfulPurchaseChange { field: string; label: string; before: string; after: string; } export function successfulPurchaseChanges( order: DouyuCollabOrder, form: OrderFormState, ): SuccessfulPurchaseChange[] { const pairs: Array<[string, string | number | null, string | number | null]> = [ ['order_no', order.order_no, form.order_no.trim()], ['account_username', order.account_username, form.account_username.trim()], ['gift_name', order.gift_name, form.gift_name.trim()], ['commodity_id', order.commodity_id, form.commodity_id.trim()], ['required_points', order.required_points, form.required_points], ]; return pairs .filter(([, before, after]) => (before ?? '') !== (after ?? '')) .map(([field, before, after]) => ({ field, label: SUCCESS_PURCHASE_FIELD_LABELS[field] || field, before: before == null || before === '' ? '未填写' : String(before), after: after == null || after === '' ? '未填写' : String(after), })); }