diff --git a/tests/test_douyu_payment_sessions.py b/tests/test_douyu_payment_sessions.py new file mode 100644 index 0000000..5d3d0bf --- /dev/null +++ b/tests/test_douyu_payment_sessions.py @@ -0,0 +1,144 @@ +import pytest +from fastapi import HTTPException + +from web.backend.models import Account, DouyuTask, User +from web.backend.routers.douyu import _require_batch_owner +from web.backend.services.douyu_service import ( + DouyuActivePaymentError, + create_douyu_planned_tasks, +) + + +def _user(db, username: str) -> User: + user = User(username=username, password_hash="hash", role="operation") + db.add(user) + db.flush() + return user + + +def _account(db, username: str) -> Account: + account = Account( + username=username, + password="password", + email=f"{username}@example.com", + email_password="mail-password", + cookie=f"acf_uid={username}", + ) + db.add(account) + db.flush() + return account + + +def test_active_payment_blocks_same_account_across_users(db): + owner = _user(db, "payment-owner") + other = _user(db, "payment-other") + account = _account(db, "payment-account") + db.commit() + + first_batch, _ = create_douyu_planned_tasks( + db, + [account.id], + "create_elite_qr", + "elite", + owner.id, + ) + + with pytest.raises(DouyuActivePaymentError, match=first_batch): + create_douyu_planned_tasks( + db, + [account.id], + "create_gold_qr", + "elite", + other.id, + ) + + task = ( + db.query(DouyuTask) + .filter(DouyuTask.batch_id == first_batch) + .one() + ) + task.status = "stopped" + db.commit() + + second_batch, count = create_douyu_planned_tasks( + db, + [account.id], + "create_gold_qr", + "elite", + other.id, + ) + assert second_batch != first_batch + assert count == 1 + + +def test_active_payment_does_not_block_non_payment_task(db): + owner = _user(db, "payment-owner") + account = _account(db, "payment-account") + db.commit() + + create_douyu_planned_tasks( + db, + [account.id], + "create_elite_qr", + "elite", + owner.id, + ) + batch_id, count = create_douyu_planned_tasks( + db, + [account.id], + "query_points", + "elite", + owner.id, + ) + + assert batch_id + assert count == 1 + + +def test_active_payment_does_not_block_distinct_accounts(db): + owner = _user(db, "payment-owner") + first = _account(db, "payment-first") + second = _account(db, "payment-second") + db.commit() + + create_douyu_planned_tasks( + db, + [first.id], + "create_elite_qr", + "elite", + owner.id, + ) + batch_id, count = create_douyu_planned_tasks( + db, + [second.id], + "create_elite_qr", + "elite", + owner.id, + ) + + assert batch_id + assert count == 1 + + +def test_operation_cannot_stop_another_users_batch(db): + owner = _user(db, "payment-owner") + other = _user(db, "payment-other") + admin = User(username="payment-admin", password_hash="hash", role="super_admin") + account = _account(db, "payment-account") + db.add(admin) + db.commit() + + batch_id, _ = create_douyu_planned_tasks( + db, + [account.id], + "create_elite_qr", + "elite", + owner.id, + ) + + _require_batch_owner(db, owner, batch_id) + with pytest.raises(HTTPException) as exc_info: + _require_batch_owner(db, other, batch_id) + assert exc_info.value.status_code == 403 + + _require_batch_owner(db, admin, batch_id) diff --git a/tests/test_douyu_workbench_scopes.py b/tests/test_douyu_workbench_scopes.py index 85c2f80..2af3505 100644 --- a/tests/test_douyu_workbench_scopes.py +++ b/tests/test_douyu_workbench_scopes.py @@ -114,6 +114,13 @@ class TestDouyuWorkbenchScope: "elite", self.user.id, ) + elite_task = ( + self.session.query(DouyuTask) + .filter(DouyuTask.batch_id == elite_batch) + .one() + ) + elite_task.status = "stopped" + self.session.commit() esports_batch, _ = create_douyu_planned_tasks( self.session, [self.account.id], diff --git a/web/backend/routers/douyu.py b/web/backend/routers/douyu.py index 0ec3e6b..d6eab4a 100644 --- a/web/backend/routers/douyu.py +++ b/web/backend/routers/douyu.py @@ -62,7 +62,9 @@ from ..services.douyu_runner import DouyuBatchRunner, douyu_batch_registry from ..services.douyu_service import ( DOUYU_CONFIG_FIELDS, DOUYU_HANDBOOK_TASK_TYPES, + DOUYU_ACTIVE_TASK_STATUSES, SUPPORTED_DOUYU_TASK_TYPES, + DouyuActivePaymentError, apply_douyu_config_defaults, cleanup_orphan_douyu_tasks, cookie_holding_filter, @@ -294,8 +296,8 @@ def _require_task_account_access( def _require_batch_owner(db: Session, current: User, batch_id: str) -> None: - """客服只能停止或订阅自己创建的任务批次。""" - if _can_view_all(current): + """除超级管理员外,只能停止或订阅自己创建的任务批次。""" + if current.role == "super_admin": return exists = ( db.query(DouyuTask.id) @@ -819,7 +821,7 @@ async def create_task_batch( cleanup_orphan_douyu_tasks( db, active_batch_ids=douyu_batch_registry.active_ids(), - statuses=("pending", "running"), + statuses=DOUYU_ACTIVE_TASK_STATUSES, message="任务已中断(无执行器接管)", ) @@ -833,6 +835,8 @@ async def create_task_batch( req.payload, platform_task_id=req.platform_task_id, ) + except DouyuActivePaymentError as exc: + raise HTTPException(status_code=409, detail=str(exc)) from exc except ValueError as exc: raise HTTPException(status_code=400, detail=str(exc)) from exc if count == 0: @@ -976,7 +980,7 @@ def cleanup_orphan_tasks( cleaned = cleanup_orphan_douyu_tasks( db, active_batch_ids=douyu_batch_registry.active_ids(), - statuses=("pending", "running"), + statuses=DOUYU_ACTIVE_TASK_STATUSES, message="任务已中断(无执行器接管)", ) return { diff --git a/web/backend/services/douyu_service.py b/web/backend/services/douyu_service.py index c127d65..0c74543 100644 --- a/web/backend/services/douyu_service.py +++ b/web/backend/services/douyu_service.py @@ -139,6 +139,15 @@ DOUYU_CONFIG_DEFAULTS = { DOUYU_CONFIG_FIELDS = tuple(DOUYU_CONFIG_DEFAULTS.keys()) DOUYU_ACTIVE_TASK_STATUSES = ("planned", "pending", "running") +DOUYU_ACTIVE_PAYMENT_TASK_TYPES = ( + "create_elite_qr", + "create_esports_qr", + "create_gold_qr", +) + + +class DouyuActivePaymentError(ValueError): + """同一账号已有未结束的充值任务。""" def douyu_config_value(field: str, value): @@ -252,6 +261,61 @@ def visible_douyu_task_accounts(db: Session, account_ids: list[int]) -> list[Acc ) +def _lock_payment_accounts( + db: Session, + accounts: list[Account], + task_type: str, +) -> None: + """串行化同一账号的充值任务创建,并拒绝并行充值。 + + 只锁账号行还不够:MySQL 默认 REPEATABLE READ 下,普通查询可能继续读取 + 旧快照。冲突任务查询同样使用 ``FOR UPDATE``,保证等待锁的事务能看到前一个 + 请求刚提交的任务。 + """ + if task_type not in DOUYU_ACTIVE_PAYMENT_TASK_TYPES or not accounts: + return + account_ids = sorted({account.id for account in accounts}) + locked_ids = { + account_id + for (account_id,) in ( + db.query(Account.id) + .filter(Account.id.in_(account_ids)) + .order_by(Account.id.asc()) + .with_for_update() + .all() + ) + } + if locked_ids != set(account_ids): + raise ValueError("部分斗鱼账号不存在,请刷新后重试") + + conflict = ( + db.query(DouyuTask) + .filter( + DouyuTask.account_id.in_(account_ids), + DouyuTask.status.in_(DOUYU_ACTIVE_TASK_STATUSES), + DouyuTask.task_type.in_(DOUYU_ACTIVE_PAYMENT_TASK_TYPES), + ) + .order_by(DouyuTask.id.desc()) + .with_for_update() + .first() + ) + if conflict is None: + return + account = next( + (item for item in accounts if item.id == conflict.account_id), + None, + ) + label = ( + (account.nickname or account.username or account.uid or f"#{account.id}") + if account is not None + else f"#{conflict.account_id}" + ) + raise DouyuActivePaymentError( + f"账号 {label} 已有充值任务处理中(批次 {conflict.batch_id})," + "请先完成或停止该充值" + ) + + def update_account_profile_from_cookie(account: Account, cookie: str) -> None: """从 Cookie 回填 uid/nickname。""" profile = DouyuActivityClient.profile_from_cookie(cookie) @@ -284,6 +348,7 @@ def create_douyu_planned_tasks( raise ValueError("该任务不属于当前工作台") accounts = visible_douyu_task_accounts(db, account_ids) + _lock_payment_accounts(db, accounts, task_type) if ( task_type in {"refresh_goods", "refresh_esports_goods", "refresh_xpd_goods"} and accounts diff --git a/web/frontend/src/pages/douyu-tasks/DouyuTasksPage.tsx b/web/frontend/src/pages/douyu-tasks/DouyuTasksPage.tsx index 9d6951e..14c5f15 100644 --- a/web/frontend/src/pages/douyu-tasks/DouyuTasksPage.tsx +++ b/web/frontend/src/pages/douyu-tasks/DouyuTasksPage.tsx @@ -1,6 +1,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { - Alert, Button, Card, Input, InputNumber, Modal, QRCode, Select, Space, Table, Tag, Tooltip, Typography, theme, + Alert, Button, Card, Input, InputNumber, Modal, Popconfirm, QRCode, Select, + Space, Table, Tabs, Tag, Tooltip, Typography, theme, } from 'antd'; import type { TableProps } from 'antd'; import { @@ -39,6 +40,8 @@ import { DOUYU_GOLD_AMOUNT_STORAGE_KEY, DOUYU_GIFT_COUNT_STORAGE_KEY, DOUYU_LAYOUT_MODE_STORAGE_KEY, + DOUYU_PAYMENT_SESSIONS_STORAGE_KEY, + DOUYU_PAYMENT_TASK_TYPE_SET, DOUYU_WORKBENCH_IDS_STORAGE_KEY, CONFIRM_FAIL_TIP_SECONDS, resultText, @@ -63,12 +66,25 @@ import { } from './config'; const { Text } = Typography; -const DOUYU_PAYMENT_TASK_TYPES = [ - 'create_elite_qr', - 'create_esports_qr', - 'create_gold_qr', -] as const; -const DOUYU_PAYMENT_TASK_TYPE_SET = new Set(DOUYU_PAYMENT_TASK_TYPES); + +interface DouyuPaySession { + batchId: string; + taskType: string; + accountIds: number[]; + createdAt: number; + ownerUserId: number; +} + +interface DouyuPaySessionView { + session: DouyuPaySession; + items: PaymentQrQueueItem[]; + taskByItemKey: Map; + readyCount: number; + queuedCount: number; + doneCount: number; + errorCount: number; + active: boolean; +} function parseAccountNames(text: string): string[] { const seen = new Set(); @@ -94,6 +110,61 @@ function payTaskAccountLabel(task: DouyuTaskItem): string { || `#${task.account_id}`; } +function paySessionTypeLabel(taskType: string): string { + if (taskType === 'create_elite_qr') return '精英宝典'; + if (taskType === 'create_esports_qr') return '电竞手册'; + if (taskType === 'create_gold_qr') return '鱼翅充值'; + return '充值'; +} + +function paySessionTime(createdAt: number): string { + return new Date(createdAt).toLocaleTimeString('zh-CN', { + hour: '2-digit', + minute: '2-digit', + hour12: false, + }); +} + +function mergeTaskRows(...groups: DouyuTaskItem[][]): DouyuTaskItem[] { + const rows = new Map(); + for (const group of groups) { + for (const task of group) rows.set(task.id, task); + } + return Array.from(rows.values()); +} + +function readPaySessions(storageKey: string): DouyuPaySession[] { + if (!storageKey) return []; + try { + const raw = JSON.parse(localStorage.getItem(storageKey) || '[]') as unknown; + if (!Array.isArray(raw)) return []; + return raw.flatMap((item): DouyuPaySession[] => { + if (!item || typeof item !== 'object') return []; + const row = item as Record; + if ( + typeof row.batchId !== 'string' + || !row.batchId + || typeof row.taskType !== 'string' + || !DOUYU_PAYMENT_TASK_TYPE_SET.has(row.taskType) + || !Array.isArray(row.accountIds) + || typeof row.createdAt !== 'number' + || typeof row.ownerUserId !== 'number' + ) return []; + return [{ + batchId: row.batchId, + taskType: row.taskType, + accountIds: row.accountIds + .map((value) => Number(value)) + .filter((value) => Number.isInteger(value) && value > 0), + createdAt: row.createdAt, + ownerUserId: row.ownerUserId, + }]; + }).slice(0, 8); + } catch { + return []; + } +} + function isLoopbackPaymentUrl(value: string): boolean { return /^https?:\/\/(localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\])(:|\/|$)/i.test(value); } @@ -168,7 +239,10 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind }) const [qrTaskIds, setQrTaskIds] = useState([]); const [activeQrTaskId, setActiveQrTaskId] = useState(null); const [esportsBindTask, setEsportsBindTask] = useState(null); - const [payBatchIds, setPayBatchIds] = useState([]); + const [paySessions, setPaySessions] = useState([]); + const [activePayBatchId, setActivePayBatchId] = useState(null); + const [paySessionTasks, setPaySessionTasks] = useState>({}); + const [stoppingPayBatchId, setStoppingPayBatchId] = useState(null); const [payOpen, setPayOpen] = useState(false); const [zoomPayTask, setZoomPayTask] = useState(null); const qrCanvasWrapRef = useRef(null); @@ -176,7 +250,6 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind }) const payQrCanvasWrapRef = useRef(null); const autoOpenedQrTaskIds = useRef>(new Set()); const autoOpenedEsportsBindTaskIds = useRef>(new Set()); - const autoOpenedPayTaskIds = useRef>(new Set()); const autoCopiedExchangeTaskIds = useRef>(new Set()); const autoNotifiedConfirmFailedTaskIds = useRef>(new Set()); const [confirmFailTip, setConfirmFailTip] = useState<{ taskId: number; message: string } | null>(null); @@ -185,9 +258,14 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind }) const [xpdPurchaseRecordsAccountId, setXpdPurchaseRecordsAccountId] = useState(null); const [nowSeconds, setNowSeconds] = useState(0); const locallyStartedBatchIds = useRef>(new Set()); + const paySessionsRef = useRef([]); + const paySessionsHydratedKeyRef = useRef(''); + const paySessionsSkipPersistRef = useRef(false); const autoOpenQrReady = useRef(false); const autoOpenEsportsBindReady = useRef(false); - const autoOpenPayReady = useRef(false); + const paySessionsStorageKey = user?.id + ? DOUYU_PAYMENT_SESSIONS_STORAGE_KEY(handbook, user.id) + : ''; const logs = useWebSocketLogs(); const canConfig = can('douyu:config'); @@ -197,6 +275,40 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind }) const timer = window.setInterval(updateNow, 1000); return () => window.clearInterval(timer); }, []); + + useEffect(() => { + const restored = readPaySessions(paySessionsStorageKey).filter( + (session) => isAdmin || session.ownerUserId === user?.id, + ); + paySessionsRef.current = restored; + paySessionsSkipPersistRef.current = true; + paySessionsHydratedKeyRef.current = paySessionsStorageKey; + setPaySessions(restored); + setPaySessionTasks({}); + setActivePayBatchId(restored[0]?.batchId || null); + }, [isAdmin, paySessionsStorageKey, user?.id]); + + useEffect(() => { + paySessionsRef.current = paySessions; + if ( + !paySessionsStorageKey + || paySessionsHydratedKeyRef.current !== paySessionsStorageKey + ) return; + if (paySessionsSkipPersistRef.current) { + paySessionsSkipPersistRef.current = false; + return; + } + localStorage.setItem(paySessionsStorageKey, JSON.stringify(paySessions)); + }, [paySessions, paySessionsStorageKey]); + + useEffect(() => { + if ( + activePayBatchId + && paySessions.some((session) => session.batchId === activePayBatchId) + ) return; + setActivePayBatchId(paySessions[0]?.batchId || null); + }, [activePayBatchId, paySessions]); + const latestQueryGameTaskByAccount = useMemo(() => { const map = new Map(); for (const task of tasks) { @@ -390,7 +502,6 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind }) } autoOpenQrReady.current = true; autoOpenEsportsBindReady.current = true; - autoOpenPayReady.current = true; } } if (cfgResult.status === 'fulfilled' && cfgResult.value) setConfig(cfgResult.value); @@ -403,6 +514,53 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind }) } }, [accountPage, accountPageSize, accountSearch, canConfig, handbook, isEsportsHandbook, isPeaceHandbook, workbenchIds]); + const setPaySessionsSafely = useCallback( + (updater: (current: DouyuPaySession[]) => DouyuPaySession[]) => { + setPaySessions((current) => { + const next = updater(current); + paySessionsRef.current = next; + return next; + }); + }, + [], + ); + + const loadPaySessionTasks = useCallback(async (batchIds: string[]) => { + const ids = Array.from(new Set(batchIds.filter(Boolean))); + if (ids.length === 0) return; + const results = await Promise.allSettled( + ids.map((batchId) => douyuApi.listTasks(handbook, batchId)), + ); + const loaded: Record = {}; + results.forEach((result, index) => { + if (result.status === 'fulfilled') loaded[ids[index]] = result.value; + }); + setPaySessionTasks((current) => ({ ...current, ...loaded })); + setPaySessionsSafely((sessions) => { + let changed = false; + const next = sessions.map((session) => { + const known = loaded[session.batchId]; + if (!known?.length) return session; + const additional = known + .map((task) => task.account_id) + .filter((accountId) => !session.accountIds.includes(accountId)); + if (additional.length === 0) return session; + changed = true; + return { + ...session, + accountIds: [...session.accountIds, ...new Set(additional)], + }; + }); + return changed ? next : sessions; + }); + }, [handbook, setPaySessionsSafely]); + + useEffect(() => { + void loadPaySessionTasks( + paySessionsRef.current.map((session) => session.batchId), + ); + }, [loadPaySessionTasks, paySessionsStorageKey]); + const loadTasks = useCallback(async () => { if (tasksLoadingRef.current) return; tasksLoadingRef.current = true; @@ -413,12 +571,15 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind }) // 批次已结束时清理 busy 标记,避免 onResult 丢失导致永久锁住 setRunningBatchIds(new Set()); } + void loadPaySessionTasks( + paySessionsRef.current.map((session) => session.batchId), + ); } catch { // 轮询失败不打扰操作 } finally { tasksLoadingRef.current = false; } - }, [handbook]); + }, [handbook, loadPaySessionTasks]); useEffect(() => { loadData(); }, [loadData]); @@ -482,6 +643,14 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind }) () => visibleTasks.some((task) => ['pending', 'running', 'planned'].includes(task.status)), [visibleTasks], ); + const hasActivePayTasks = useMemo( + () => paySessions.some((session) => ( + (paySessionTasks[session.batchId] || []).some( + (task) => ['pending', 'running', 'planned'].includes(task.status), + ) + )), + [paySessionTasks, paySessions], + ); // 正在执行任务的账号集合,用于按账号维度禁用,避免同一账号并发跑不同类型任务 const runningAccountIds = useMemo(() => { @@ -494,26 +663,35 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind }) return set; }, [visibleTasks]); - // 从后端任务派生正在运行的批次 ID(刷新页面后仍可恢复,用于显示停止按钮) + // 只恢复当前用户自己创建的活跃批次;管理员全量可见不等于可以一键停掉别人。 const activeBatchIds = useMemo(() => { const set = new Set(); for (const task of visibleTasks) { - if (['pending', 'running', 'planned'].includes(task.status) && task.batch_id) { + if ( + task.created_by === user?.id + && ['pending', 'running', 'planned'].includes(task.status) + && task.batch_id + ) { set.add(task.batch_id); } } return set; - }, [visibleTasks]); + }, [user?.id, visibleTasks]); const selectedHasRunning = selectedIds.some((id) => runningAccountIds.has(id)); // 任务状态由 WS(level=task) 即时推送;轮询仅作兜底(多标签页/断线重连), // 有活跃任务或 WS 连接时 5 秒一次,空闲 30 秒轻量刷新 useEffect(() => { - const intervalMs = hasActiveTasks || logs.connected || runningBatchIds.size > 0 ? 5000 : 30000; + const intervalMs = ( + hasActiveTasks + || hasActivePayTasks + || logs.connected + || runningBatchIds.size > 0 + ) ? 5000 : 30000; const timer = setInterval(loadTasks, intervalMs); return () => clearInterval(timer); - }, [hasActiveTasks, loadTasks, logs.connected, runningBatchIds]); + }, [hasActivePayTasks, hasActiveTasks, loadTasks, logs.connected, runningBatchIds]); const openQrTask = useCallback((task: DouyuTaskItem, activate = true) => { autoOpenedQrTaskIds.current.add(task.id); @@ -544,14 +722,89 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind }) setEsportsBindTask(task); }, [closeAllQrTasks]); - const openPayTasks = useCallback((batchId?: string) => { - if (batchId) { - setPayBatchIds((prev) => (prev.includes(batchId) ? prev : [...prev, batchId])); - } + const addPaySession = useCallback((session: DouyuPaySession) => { + setPaySessionsSafely((current) => { + const existing = current.find((item) => item.batchId === session.batchId); + if (existing) { + return current.map((item) => ( + item.batchId === session.batchId + ? { + ...item, + accountIds: [ + ...item.accountIds, + ...session.accountIds.filter( + (accountId) => !item.accountIds.includes(accountId), + ), + ], + } + : item + )); + } + return [session, ...current].slice(0, 8); + }); + setActivePayBatchId(session.batchId); closeAllQrTasks(); setEsportsBindTask(null); setPayOpen(true); - }, [closeAllQrTasks]); + void loadPaySessionTasks([session.batchId]); + }, [closeAllQrTasks, loadPaySessionTasks, setPaySessionsSafely]); + + const openPayBatch = useCallback(async ( + batchId: string, + taskHint?: DouyuTaskItem, + ) => { + const existing = paySessionsRef.current.find( + (session) => session.batchId === batchId, + ); + if (existing) { + if (existing.ownerUserId !== user?.id && !isAdmin) { + message.warning('该充值批次属于其他用户,请在自己的充值会话中操作'); + return; + } + setActivePayBatchId(batchId); + closeAllQrTasks(); + setEsportsBindTask(null); + setPayOpen(true); + void loadPaySessionTasks([batchId]); + return; + } + + let batchTasks: DouyuTaskItem[] = taskHint ? [taskHint] : []; + try { + batchTasks = await douyuApi.listTasks(handbook, batchId); + } catch { + // 任务提示仍可用于校验归属并先建立只含一个账号的会话。 + } + if (batchTasks.length === 0 && taskHint) batchTasks = [taskHint]; + const ownerTask = batchTasks[0] || taskHint; + if (!ownerTask) { + message.warning('未找到该充值批次的任务记录'); + return; + } + if (ownerTask.created_by !== user?.id && !isAdmin) { + message.warning('该充值批次属于其他用户,请在自己的充值会话中操作'); + return; + } + const ordered = [...batchTasks].sort((a, b) => a.id - b.id); + addPaySession({ + batchId, + taskType: ownerTask.task_type, + accountIds: ordered + .map((task) => task.account_id) + .filter((accountId, index, values) => values.indexOf(accountId) === index), + createdAt: ownerTask.created_at + ? new Date(ownerTask.created_at).getTime() + : new Date().getTime(), + ownerUserId: ownerTask.created_by, + }); + }, [ + addPaySession, + closeAllQrTasks, + handbook, + isAdmin, + loadPaySessionTasks, + user?.id, + ]); // 自动弹出最新绑定二维码(running 有 url 即可);多账号并行,不互斥 useEffect(() => { @@ -583,27 +836,6 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind }) if (nextTask) openEsportsBindTask(nextTask); }, [esportsBindTask, openEsportsBindTask, visibleTasks]); - // 自动弹出支付二维码 - useEffect(() => { - if (!autoOpenPayReady.current) return; - const nextPayTasks = visibleTasks - .filter((task) => ( - locallyStartedBatchIds.current.has(task.batch_id) - && hasPaymentQrcode(task) - && !paymentArrived(task) - && !autoOpenedPayTaskIds.current.has(task.id) - )) - .sort((a, b) => a.id - b.id); - if (nextPayTasks.length === 0) return; - for (const task of nextPayTasks) { - autoOpenedPayTaskIds.current.add(task.id); - } - setPayBatchIds((prev) => [ - ...new Set([...prev, ...nextPayTasks.map((task) => task.batch_id)]), - ]); - setPayOpen(true); - }, [visibleTasks]); - // 兑换成功后自动生成结果图片并复制到剪贴板(批量时最后完成的覆盖剪贴板) useEffect(() => { if (!autoOpenQrReady.current) return; @@ -691,9 +923,12 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind }) useEffect(() => { if (!zoomPayTask) return; - const latest = tasks.find((task) => task.id === zoomPayTask.id); + const latest = tasks.find((task) => task.id === zoomPayTask.id) + || Object.values(paySessionTasks) + .flat() + .find((task) => task.id === zoomPayTask.id); if (latest && latest !== zoomPayTask) setZoomPayTask(latest); - }, [tasks, zoomPayTask]); + }, [paySessionTasks, tasks, zoomPayTask]); // 多批次并发:不再用全局 busy 标志阻塞 UI,刷新频率直接用各子条件判断 @@ -766,10 +1001,13 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind }) // 只有本页面创建的批次才允许主动弹二维码,防止其他工作台/浏览器的任务打扰当前操作。 locallyStartedBatchIds.current.add(result.batch_id); if (DOUYU_PAYMENT_TASK_TYPE_SET.has(taskType)) { - setPayBatchIds((prev) => ( - prev.includes(result.batch_id) ? prev : [...prev, result.batch_id] - )); - setPayOpen(true); + addPaySession({ + batchId: result.batch_id, + taskType, + accountIds: Array.from(new Set(ids)), + createdAt: new Date().getTime(), + ownerUserId: user?.id || 0, + }); } setRunningBatchIds((prev) => new Set(prev).add(result.batch_id)); logs.connectBatch(result.batch_id, `/api/douyu/ws/${result.batch_id}`, { @@ -785,6 +1023,31 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind }) onTask: (rawTask) => { const task = rawTask as unknown as DouyuTaskItem; if (task.handbook_scope !== handbook) return; + if ( + paySessionsRef.current.some( + (session) => session.batchId === task.batch_id, + ) + ) { + setPaySessionTasks((current) => { + const rows = current[task.batch_id] || []; + return { + ...current, + [task.batch_id]: [ + ...rows.filter((item) => item.id !== task.id), + task, + ].sort((a, b) => a.id - b.id), + }; + }); + setPaySessionsSafely((sessions) => sessions.map((session) => ( + session.batchId === task.batch_id + && !session.accountIds.includes(task.account_id) + ? { + ...session, + accountIds: [...session.accountIds, task.account_id], + } + : session + ))); + } // 已有任务原位更新保持排序;新任务插入头部(与后端 id desc 一致) setTasks((prev) => { if (prev.some((t) => t.id === task.id)) { @@ -801,17 +1064,59 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind }) } }; - const stopBatch = async () => { - const ids = Array.from(new Set([...runningBatchIds, ...activeBatchIds])); + const stopBatchIds = async (batchIds: string[]) => { + const ids = Array.from(new Set(batchIds.filter(Boolean))); if (ids.length === 0) return; try { await Promise.all(ids.map((id) => douyuApi.stopBatch(id))); message.success('已停止'); + await Promise.all([ + loadTasks(), + loadPaySessionTasks(ids), + ]); } catch (error) { message.error(getErrorMessage(error)); } }; + const stopBatch = () => { + void stopBatchIds([...runningBatchIds, ...activeBatchIds]); + }; + + const stopActivePaySession = async () => { + const session = paySessionsRef.current.find( + (item) => item.batchId === activePayBatchId, + ); + if (!session || session.ownerUserId !== user?.id) return; + setStoppingPayBatchId(session.batchId); + try { + await stopBatchIds([session.batchId]); + } finally { + setStoppingPayBatchId(null); + } + }; + + const closeActivePaySession = () => { + const batchId = activePayBatchId; + if (!batchId) return; + const remaining = paySessionsRef.current.filter( + (session) => session.batchId !== batchId, + ); + setPaySessionsSafely((sessions) => ( + sessions.filter((session) => session.batchId !== batchId) + )); + setPaySessionTasks((current) => { + const next = { ...current }; + delete next[batchId]; + return next; + }); + setActivePayBatchId(remaining[0]?.batchId || null); + if (remaining.length === 0) { + setPayOpen(false); + setZoomPayTask(null); + } + }; + const saveConfig = async (values: DouyuConfig) => { try { const saved = await douyuApi.updateConfig(values); @@ -1483,10 +1788,18 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind }) // success 收尾(「已生成绑定二维码,未检测到新扫码角色」),二维码必须留着。 const url = taskQrUrl(task); if (!url) return null; + if ( + task + && DOUYU_PAYMENT_TASK_TYPE_SET.has(task.task_type) + && task.created_by !== user?.id + && !isAdmin + ) { + return 他人处理中; + } const openTask = () => { if (!task) return; if (hasBindQrcode(task)) openQrTask(task); - else if (hasPaymentQrcode(task)) openPayTasks(task.batch_id); + else if (hasPaymentQrcode(task)) void openPayBatch(task.batch_id, task); else if (task.task_type === 'get_xpd_bind_qr') openQrTask(task); else openEsportsBindTask(task); }; @@ -1571,73 +1884,173 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind }) if (configOpen && config) setConfigFormValues({ ...config }); }, [configOpen, config]); - const payBatchIdSet = useMemo(() => new Set(payBatchIds), [payBatchIds]); - const payTasks = useMemo( - () => tasks.filter( - (task) => DOUYU_PAYMENT_TASK_TYPE_SET.has(task.task_type) - && payBatchIdSet.has(task.batch_id), - ), - [payBatchIdSet, tasks], + const accountById = useMemo( + () => new Map(accounts.map((account) => [account.id, account])), + [accounts], ); - const payFailedTasks = useMemo( - () => payTasks.filter( - (task) => !hasPaymentQrcode(task) - && ['failed', 'error', 'stopped'].includes(task.status), - ), - [payTasks], - ); - const payQueuedTasks = useMemo( - () => payTasks.filter( - (task) => !hasPaymentQrcode(task) - && ['planned', 'pending', 'running'].includes(task.status), - ), - [payTasks], - ); - const payReadyTasks = useMemo( - () => payTasks.filter( - (task) => hasPaymentQrcode(task) - && !paymentArrived(task) - && !['failed', 'error', 'stopped'].includes(task.status), - ), - [payTasks], - ); - const payDoneCount = payTasks.length - payReadyTasks.length - payQueuedTasks.length - payFailedTasks.length; - const payTaskById = useMemo(() => new Map(payTasks.map((task) => [task.id, task])), [payTasks]); - const payQueueItems = useMemo(() => { - const ready = payReadyTasks.map((task) => { - const qrValue = taskQrUrl(task); + const paySessionViews = useMemo(() => ( + paySessions.map((session) => { + const batchTasks = mergeTaskRows( + tasks.filter((task) => ( + task.batch_id === session.batchId + && DOUYU_PAYMENT_TASK_TYPE_SET.has(task.task_type) + )), + paySessionTasks[session.batchId] || [], + ); + const taskByAccount = new Map(); + for (const task of batchTasks.sort((a, b) => a.id - b.id)) { + taskByAccount.set(task.account_id, task); + } + const accountIds = [ + ...session.accountIds, + ...Array.from(taskByAccount.keys()).filter( + (accountId) => !session.accountIds.includes(accountId), + ), + ]; + const items: PaymentQrQueueItem[] = []; + const taskByItemKey = new Map(); + let readyCount = 0; + let queuedCount = 0; + let doneCount = 0; + let errorCount = 0; + let active = runningBatchIds.has(session.batchId); + + for (const accountId of accountIds) { + const task = taskByAccount.get(accountId); + const key = `${session.batchId}:${accountId}`; + const account = accountById.get(accountId); + const accountLabel = task + ? payTaskAccountLabel(task) + : account?.nickname + || account?.username + || account?.uid + || `#${accountId}`; + const subtitle = `${paySessionTypeLabel(session.taskType)} · UID ${ + task?.account_uid || account?.uid || '-' + }`; + + if (task && paymentArrived(task)) { + doneCount += 1; + continue; + } + if (task && ['planned', 'pending', 'running'].includes(task.status)) { + active = true; + } + const qrValue = taskQrUrl(task); + if (qrValue) { + readyCount += 1; + const terminal = Boolean( + task && ['failed', 'error', 'stopped'].includes(task.status), + ); + const terminalLabel = task + ? TASK_STATUS_LABELS[task.status] || task.status + : ''; + items.push({ + key, + title: accountLabel, + subtitle, + description: task?.message || '', + phase: 'ready', + qrValue, + copyValue: qrValue, + statusLabel: terminal + ? `${terminalLabel} · 待确认到账` + : resultText(task?.result, 'payment_status_label') + || TASK_STATUS_LABELS[task?.status || ''] + || '等待扫码', + statusColor: terminal + ? TASK_STATUS_COLORS[task?.status || ''] || 'warning' + : TASK_STATUS_COLORS[task?.status || ''] || 'processing', + warning: [ + isLoopbackPaymentUrl(qrValue) + ? '二维码是本机地址(localhost),手机无法扫码' + : '', + terminal + ? '任务已结束但二维码仍保留,到账状态尚未确认' + : '', + ].filter(Boolean).join(';'), + }); + if (task) taskByItemKey.set(key, task); + continue; + } + + if (!task) { + if (nowSeconds > 0 && nowSeconds * 1000 - session.createdAt > 15_000) { + errorCount += 1; + items.push({ + key, + title: accountLabel, + subtitle, + phase: 'error', + error: '未创建任务,账号可能没有有效 CK 或已失去操作权限', + }); + continue; + } + queuedCount += 1; + items.push({ + key, + title: accountLabel, + subtitle, + phase: 'queued', + }); + continue; + } + + if (['planned', 'pending', 'running'].includes(task.status)) { + queuedCount += 1; + taskByItemKey.set(key, task); + items.push({ + key, + title: accountLabel, + subtitle, + phase: task.status === 'pending' || task.status === 'running' + ? 'generating' + : 'queued', + }); + continue; + } + + errorCount += 1; + taskByItemKey.set(key, task); + items.push({ + key, + title: accountLabel, + subtitle, + phase: 'error', + error: task.message || '支付码生成失败', + }); + } + return { - key: task.id, - title: payTaskAccountLabel(task), - subtitle: `${payTaskTypeLabel(task)} · UID ${task.account_uid || '-'}`, - description: task.message || '', - phase: 'ready' as const, - qrValue, - copyValue: qrValue, - statusLabel: resultText(task.result, 'payment_status_label') - || TASK_STATUS_LABELS[task.status] - || task.status, - statusColor: TASK_STATUS_COLORS[task.status] || 'default', - warning: isLoopbackPaymentUrl(qrValue) - ? '二维码是本机地址(localhost),手机无法扫码' - : '', + session, + items, + taskByItemKey, + readyCount, + queuedCount, + doneCount, + errorCount, + active, }; - }); - const queued = payQueuedTasks.map((task) => ({ - key: `queued-${task.id}`, - title: payTaskAccountLabel(task), - subtitle: `${payTaskTypeLabel(task)} · UID ${task.account_uid || '-'}`, - phase: task.status === 'running' ? 'generating' as const : 'queued' as const, - })); - const failed = payFailedTasks.map((task) => ({ - key: `failed-${task.id}`, - title: payTaskAccountLabel(task), - subtitle: `${payTaskTypeLabel(task)} · UID ${task.account_uid || '-'}`, - phase: 'error' as const, - error: task.message || '支付码生成失败', - })); - return [...ready, ...queued, ...failed]; - }, [payFailedTasks, payQueuedTasks, payReadyTasks]); + }) + ), [ + accountById, + nowSeconds, + paySessionTasks, + paySessions, + runningBatchIds, + tasks, + ]); + const activePaySessionView = paySessionViews.find( + (view) => view.session.batchId === activePayBatchId, + ) || paySessionViews[0]; + const payReadyCount = activePaySessionView?.readyCount || 0; + const payQueuedCount = activePaySessionView?.queuedCount || 0; + const payDoneCount = activePaySessionView?.doneCount || 0; + const payErrorCount = activePaySessionView?.errorCount || 0; + const activePaySessionOwned = Boolean( + activePaySessionView + && activePaySessionView.session.ownerUserId === user?.id, + ); const zoomPayUrl = taskQrUrl(zoomPayTask); const copyPaymentLink = async (value: string) => { if (!value) { @@ -2098,7 +2511,19 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind }) {canConfig && } - {(activeBatchIds.size > 0 || runningBatchIds.size > 0) && } + {(activeBatchIds.size > 0 || runningBatchIds.size > 0) && ( + + + + )} @@ -2567,10 +2992,11 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind }) 支付码 - {payQueueItems.length > 0 - ? `(${payReadyTasks.length} 个待扫码` - + `${payQueuedTasks.length ? ` · ${payQueuedTasks.length} 个排队中` : ''}` - + `${payDoneCount ? ` · ${payDoneCount} 个已完成` : ''})` + {activePaySessionView + ? `(${payReadyCount} 个可扫码` + + `${payQueuedCount ? ` · ${payQueuedCount} 个生成中` : ''}` + + `${payErrorCount ? ` · ${payErrorCount} 个失败` : ''}` + + `${payDoneCount ? ` · ${payDoneCount} 个已到账` : ''})` : ''} @@ -2579,35 +3005,75 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind }) onCancel={() => setPayOpen(false)} footer={( - - 多选账号会并行生成多个码;支付到账后自动从待扫码队列移除 - - + + )} + )} centered width={920} > - 0 - ? '待扫码队列已清空,支付完成的账号已自动移除' - : '当前没有待扫码支付码'} - queuedText="正在排队生成斗鱼支付码" - onZoom={(item) => { - const task = payTaskById.get(Number(item.key)); - if (task) setZoomPayTask(task); - }} - onCopy={(item) => void copyPaymentLink(item.copyValue || item.qrValue || '')} - /> + {paySessionViews.length > 0 ? ( + { + setActivePayBatchId(batchId); + void loadPaySessionTasks([batchId]); + }} + items={paySessionViews.map((view) => ({ + key: view.session.batchId, + label: ( + + + {paySessionTypeLabel(view.session.taskType)} + {' · '} + {paySessionTime(view.session.createdAt)} + + + {view.doneCount}/{view.session.accountIds.length} + + + ), + children: ( + 0 + ? '当前批次已到账,支付完成的账号已原位移除' + : '当前批次没有待扫码支付码'} + queuedText="正在并行生成斗鱼支付码" + onZoom={(item) => { + const task = view.taskByItemKey.get(String(item.key)); + if (task) setZoomPayTask(task); + }} + onCopy={(item) => void copyPaymentLink( + item.copyValue || item.qrValue || '', + )} + /> + ), + }))} + /> + ) : ( + 当前没有充值会话 + )} - ) : ['failed', 'error', 'stopped'].includes(zoomPayTask.status) ? ( - ) : zoomPayUrl ? ( + {['failed', 'error', 'stopped'].includes(zoomPayTask.status) && ( + + )}
+ ) : ['failed', 'error', 'stopped'].includes(zoomPayTask.status) ? ( + ) : ( 支付码生成中... )} diff --git a/web/frontend/src/pages/douyu-tasks/config.tsx b/web/frontend/src/pages/douyu-tasks/config.tsx index 743d212..8e07eaa 100644 --- a/web/frontend/src/pages/douyu-tasks/config.tsx +++ b/web/frontend/src/pages/douyu-tasks/config.tsx @@ -8,6 +8,15 @@ export { eliteIsExpired, eliteStatusText } from '../../utils/douyuElite'; export type HandbookKind = 'elite' | 'esports' | 'peace'; +export const DOUYU_PAYMENT_TASK_TYPES = [ + 'create_elite_qr', + 'create_esports_qr', + 'create_gold_qr', +] as const; +export const DOUYU_PAYMENT_TASK_TYPE_SET = new Set( + DOUYU_PAYMENT_TASK_TYPES, +); + export const TASK_STATUS_COLORS: Record = { planned: 'default', pending: 'default', @@ -123,6 +132,10 @@ export const PEACE_TASK_TYPES = new Set([ export const DOUYU_GOLD_AMOUNT_STORAGE_KEY = 'douyu_task_gold_amount'; export const DOUYU_GIFT_COUNT_STORAGE_KEY = 'douyu_task_gift_count'; export const DOUYU_LAYOUT_MODE_STORAGE_KEY = 'douyu_task_layout_mode'; +export const DOUYU_PAYMENT_SESSIONS_STORAGE_KEY = ( + kind: HandbookKind, + userId: number, +) => `douyu_payment_sessions_v1_${kind}_${userId}`; // v2 避开旧版页面切换时写入其他工作台的共享账号列表。 export const DOUYU_WORKBENCH_IDS_STORAGE_KEY = (kind: HandbookKind) => `douyu_task_workbench_ids_v2_${kind}`; export const CONFIRM_FAIL_TIP_SECONDS = 6; @@ -151,7 +164,7 @@ export function taskQrUrl(task: DouyuTaskItem | null | undefined): string { if (!task) return ''; if (task.task_type === 'get_bind_qr') return resultText(task.result, 'url'); if (task.task_type === 'get_xpd_bind_qr') return resultText(task.result, 'url'); - if (['create_elite_qr', 'create_esports_qr', 'create_gold_qr'].includes(task.task_type)) { + if (DOUYU_PAYMENT_TASK_TYPE_SET.has(task.task_type)) { return resultText(task.result, 'pay_url'); } if (['prepare_esports_bind', 'get_esports_bind_qr'].includes(task.task_type)) { @@ -190,13 +203,13 @@ export function hasBindQrcode(task: DouyuTaskItem | null | undefined): boolean { export function hasPaymentQrcode(task: DouyuTaskItem | null | undefined): boolean { return Boolean( task - && ['create_elite_qr', 'create_esports_qr', 'create_gold_qr'].includes(task.task_type) + && DOUYU_PAYMENT_TASK_TYPE_SET.has(task.task_type) && resultText(task.result, 'pay_url'), ); } export function paymentArrived(task: DouyuTaskItem | null | undefined): boolean { - if (!task || !['create_elite_qr', 'create_esports_qr', 'create_gold_qr'].includes(task.task_type)) return false; + if (!task || !DOUYU_PAYMENT_TASK_TYPE_SET.has(task.task_type)) return false; if (task.status !== 'success') return false; return task.result?.gold_recharged === true || task.result?.elite_opened === true