feat(douyu): 隔离充值会话并阻止同账号并发充值
This commit is contained in:
@@ -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)
|
||||||
@@ -114,6 +114,13 @@ class TestDouyuWorkbenchScope:
|
|||||||
"elite",
|
"elite",
|
||||||
self.user.id,
|
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(
|
esports_batch, _ = create_douyu_planned_tasks(
|
||||||
self.session,
|
self.session,
|
||||||
[self.account.id],
|
[self.account.id],
|
||||||
|
|||||||
@@ -62,7 +62,9 @@ from ..services.douyu_runner import DouyuBatchRunner, douyu_batch_registry
|
|||||||
from ..services.douyu_service import (
|
from ..services.douyu_service import (
|
||||||
DOUYU_CONFIG_FIELDS,
|
DOUYU_CONFIG_FIELDS,
|
||||||
DOUYU_HANDBOOK_TASK_TYPES,
|
DOUYU_HANDBOOK_TASK_TYPES,
|
||||||
|
DOUYU_ACTIVE_TASK_STATUSES,
|
||||||
SUPPORTED_DOUYU_TASK_TYPES,
|
SUPPORTED_DOUYU_TASK_TYPES,
|
||||||
|
DouyuActivePaymentError,
|
||||||
apply_douyu_config_defaults,
|
apply_douyu_config_defaults,
|
||||||
cleanup_orphan_douyu_tasks,
|
cleanup_orphan_douyu_tasks,
|
||||||
cookie_holding_filter,
|
cookie_holding_filter,
|
||||||
@@ -294,8 +296,8 @@ def _require_task_account_access(
|
|||||||
|
|
||||||
|
|
||||||
def _require_batch_owner(db: Session, current: User, batch_id: str) -> None:
|
def _require_batch_owner(db: Session, current: User, batch_id: str) -> None:
|
||||||
"""客服只能停止或订阅自己创建的任务批次。"""
|
"""除超级管理员外,只能停止或订阅自己创建的任务批次。"""
|
||||||
if _can_view_all(current):
|
if current.role == "super_admin":
|
||||||
return
|
return
|
||||||
exists = (
|
exists = (
|
||||||
db.query(DouyuTask.id)
|
db.query(DouyuTask.id)
|
||||||
@@ -819,7 +821,7 @@ async def create_task_batch(
|
|||||||
cleanup_orphan_douyu_tasks(
|
cleanup_orphan_douyu_tasks(
|
||||||
db,
|
db,
|
||||||
active_batch_ids=douyu_batch_registry.active_ids(),
|
active_batch_ids=douyu_batch_registry.active_ids(),
|
||||||
statuses=("pending", "running"),
|
statuses=DOUYU_ACTIVE_TASK_STATUSES,
|
||||||
message="任务已中断(无执行器接管)",
|
message="任务已中断(无执行器接管)",
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -833,6 +835,8 @@ async def create_task_batch(
|
|||||||
req.payload,
|
req.payload,
|
||||||
platform_task_id=req.platform_task_id,
|
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:
|
except ValueError as exc:
|
||||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||||
if count == 0:
|
if count == 0:
|
||||||
@@ -976,7 +980,7 @@ def cleanup_orphan_tasks(
|
|||||||
cleaned = cleanup_orphan_douyu_tasks(
|
cleaned = cleanup_orphan_douyu_tasks(
|
||||||
db,
|
db,
|
||||||
active_batch_ids=douyu_batch_registry.active_ids(),
|
active_batch_ids=douyu_batch_registry.active_ids(),
|
||||||
statuses=("pending", "running"),
|
statuses=DOUYU_ACTIVE_TASK_STATUSES,
|
||||||
message="任务已中断(无执行器接管)",
|
message="任务已中断(无执行器接管)",
|
||||||
)
|
)
|
||||||
return {
|
return {
|
||||||
|
|||||||
@@ -139,6 +139,15 @@ DOUYU_CONFIG_DEFAULTS = {
|
|||||||
|
|
||||||
DOUYU_CONFIG_FIELDS = tuple(DOUYU_CONFIG_DEFAULTS.keys())
|
DOUYU_CONFIG_FIELDS = tuple(DOUYU_CONFIG_DEFAULTS.keys())
|
||||||
DOUYU_ACTIVE_TASK_STATUSES = ("planned", "pending", "running")
|
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):
|
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:
|
def update_account_profile_from_cookie(account: Account, cookie: str) -> None:
|
||||||
"""从 Cookie 回填 uid/nickname。"""
|
"""从 Cookie 回填 uid/nickname。"""
|
||||||
profile = DouyuActivityClient.profile_from_cookie(cookie)
|
profile = DouyuActivityClient.profile_from_cookie(cookie)
|
||||||
@@ -284,6 +348,7 @@ def create_douyu_planned_tasks(
|
|||||||
raise ValueError("该任务不属于当前工作台")
|
raise ValueError("该任务不属于当前工作台")
|
||||||
|
|
||||||
accounts = visible_douyu_task_accounts(db, account_ids)
|
accounts = visible_douyu_task_accounts(db, account_ids)
|
||||||
|
_lock_payment_accounts(db, accounts, task_type)
|
||||||
if (
|
if (
|
||||||
task_type in {"refresh_goods", "refresh_esports_goods", "refresh_xpd_goods"}
|
task_type in {"refresh_goods", "refresh_esports_goods", "refresh_xpd_goods"}
|
||||||
and accounts
|
and accounts
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||||
import {
|
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';
|
} from 'antd';
|
||||||
import type { TableProps } from 'antd';
|
import type { TableProps } from 'antd';
|
||||||
import {
|
import {
|
||||||
@@ -39,6 +40,8 @@ import {
|
|||||||
DOUYU_GOLD_AMOUNT_STORAGE_KEY,
|
DOUYU_GOLD_AMOUNT_STORAGE_KEY,
|
||||||
DOUYU_GIFT_COUNT_STORAGE_KEY,
|
DOUYU_GIFT_COUNT_STORAGE_KEY,
|
||||||
DOUYU_LAYOUT_MODE_STORAGE_KEY,
|
DOUYU_LAYOUT_MODE_STORAGE_KEY,
|
||||||
|
DOUYU_PAYMENT_SESSIONS_STORAGE_KEY,
|
||||||
|
DOUYU_PAYMENT_TASK_TYPE_SET,
|
||||||
DOUYU_WORKBENCH_IDS_STORAGE_KEY,
|
DOUYU_WORKBENCH_IDS_STORAGE_KEY,
|
||||||
CONFIRM_FAIL_TIP_SECONDS,
|
CONFIRM_FAIL_TIP_SECONDS,
|
||||||
resultText,
|
resultText,
|
||||||
@@ -63,12 +66,25 @@ import {
|
|||||||
} from './config';
|
} from './config';
|
||||||
|
|
||||||
const { Text } = Typography;
|
const { Text } = Typography;
|
||||||
const DOUYU_PAYMENT_TASK_TYPES = [
|
|
||||||
'create_elite_qr',
|
interface DouyuPaySession {
|
||||||
'create_esports_qr',
|
batchId: string;
|
||||||
'create_gold_qr',
|
taskType: string;
|
||||||
] as const;
|
accountIds: number[];
|
||||||
const DOUYU_PAYMENT_TASK_TYPE_SET = new Set<string>(DOUYU_PAYMENT_TASK_TYPES);
|
createdAt: number;
|
||||||
|
ownerUserId: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface DouyuPaySessionView {
|
||||||
|
session: DouyuPaySession;
|
||||||
|
items: PaymentQrQueueItem[];
|
||||||
|
taskByItemKey: Map<string, DouyuTaskItem>;
|
||||||
|
readyCount: number;
|
||||||
|
queuedCount: number;
|
||||||
|
doneCount: number;
|
||||||
|
errorCount: number;
|
||||||
|
active: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
function parseAccountNames(text: string): string[] {
|
function parseAccountNames(text: string): string[] {
|
||||||
const seen = new Set<string>();
|
const seen = new Set<string>();
|
||||||
@@ -94,6 +110,61 @@ function payTaskAccountLabel(task: DouyuTaskItem): string {
|
|||||||
|| `#${task.account_id}`;
|
|| `#${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<number, DouyuTaskItem>();
|
||||||
|
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<string, unknown>;
|
||||||
|
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 {
|
function isLoopbackPaymentUrl(value: string): boolean {
|
||||||
return /^https?:\/\/(localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\])(:|\/|$)/i.test(value);
|
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<number[]>([]);
|
const [qrTaskIds, setQrTaskIds] = useState<number[]>([]);
|
||||||
const [activeQrTaskId, setActiveQrTaskId] = useState<number | null>(null);
|
const [activeQrTaskId, setActiveQrTaskId] = useState<number | null>(null);
|
||||||
const [esportsBindTask, setEsportsBindTask] = useState<DouyuTaskItem | null>(null);
|
const [esportsBindTask, setEsportsBindTask] = useState<DouyuTaskItem | null>(null);
|
||||||
const [payBatchIds, setPayBatchIds] = useState<string[]>([]);
|
const [paySessions, setPaySessions] = useState<DouyuPaySession[]>([]);
|
||||||
|
const [activePayBatchId, setActivePayBatchId] = useState<string | null>(null);
|
||||||
|
const [paySessionTasks, setPaySessionTasks] = useState<Record<string, DouyuTaskItem[]>>({});
|
||||||
|
const [stoppingPayBatchId, setStoppingPayBatchId] = useState<string | null>(null);
|
||||||
const [payOpen, setPayOpen] = useState(false);
|
const [payOpen, setPayOpen] = useState(false);
|
||||||
const [zoomPayTask, setZoomPayTask] = useState<DouyuTaskItem | null>(null);
|
const [zoomPayTask, setZoomPayTask] = useState<DouyuTaskItem | null>(null);
|
||||||
const qrCanvasWrapRef = useRef<HTMLDivElement | null>(null);
|
const qrCanvasWrapRef = useRef<HTMLDivElement | null>(null);
|
||||||
@@ -176,7 +250,6 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
|
|||||||
const payQrCanvasWrapRef = useRef<HTMLDivElement | null>(null);
|
const payQrCanvasWrapRef = useRef<HTMLDivElement | null>(null);
|
||||||
const autoOpenedQrTaskIds = useRef<Set<number>>(new Set());
|
const autoOpenedQrTaskIds = useRef<Set<number>>(new Set());
|
||||||
const autoOpenedEsportsBindTaskIds = useRef<Set<number>>(new Set());
|
const autoOpenedEsportsBindTaskIds = useRef<Set<number>>(new Set());
|
||||||
const autoOpenedPayTaskIds = useRef<Set<number>>(new Set());
|
|
||||||
const autoCopiedExchangeTaskIds = useRef<Set<number>>(new Set());
|
const autoCopiedExchangeTaskIds = useRef<Set<number>>(new Set());
|
||||||
const autoNotifiedConfirmFailedTaskIds = useRef<Set<number>>(new Set());
|
const autoNotifiedConfirmFailedTaskIds = useRef<Set<number>>(new Set());
|
||||||
const [confirmFailTip, setConfirmFailTip] = useState<{ taskId: number; message: string } | null>(null);
|
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<number | null>(null);
|
const [xpdPurchaseRecordsAccountId, setXpdPurchaseRecordsAccountId] = useState<number | null>(null);
|
||||||
const [nowSeconds, setNowSeconds] = useState(0);
|
const [nowSeconds, setNowSeconds] = useState(0);
|
||||||
const locallyStartedBatchIds = useRef<Set<string>>(new Set());
|
const locallyStartedBatchIds = useRef<Set<string>>(new Set());
|
||||||
|
const paySessionsRef = useRef<DouyuPaySession[]>([]);
|
||||||
|
const paySessionsHydratedKeyRef = useRef('');
|
||||||
|
const paySessionsSkipPersistRef = useRef(false);
|
||||||
const autoOpenQrReady = useRef(false);
|
const autoOpenQrReady = useRef(false);
|
||||||
const autoOpenEsportsBindReady = 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 logs = useWebSocketLogs();
|
||||||
const canConfig = can('douyu:config');
|
const canConfig = can('douyu:config');
|
||||||
@@ -197,6 +275,40 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
|
|||||||
const timer = window.setInterval(updateNow, 1000);
|
const timer = window.setInterval(updateNow, 1000);
|
||||||
return () => window.clearInterval(timer);
|
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 latestQueryGameTaskByAccount = useMemo(() => {
|
||||||
const map = new Map<number, DouyuTaskItem>();
|
const map = new Map<number, DouyuTaskItem>();
|
||||||
for (const task of tasks) {
|
for (const task of tasks) {
|
||||||
@@ -390,7 +502,6 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
|
|||||||
}
|
}
|
||||||
autoOpenQrReady.current = true;
|
autoOpenQrReady.current = true;
|
||||||
autoOpenEsportsBindReady.current = true;
|
autoOpenEsportsBindReady.current = true;
|
||||||
autoOpenPayReady.current = true;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (cfgResult.status === 'fulfilled' && cfgResult.value) setConfig(cfgResult.value);
|
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]);
|
}, [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<string, DouyuTaskItem[]> = {};
|
||||||
|
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 () => {
|
const loadTasks = useCallback(async () => {
|
||||||
if (tasksLoadingRef.current) return;
|
if (tasksLoadingRef.current) return;
|
||||||
tasksLoadingRef.current = true;
|
tasksLoadingRef.current = true;
|
||||||
@@ -413,12 +571,15 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
|
|||||||
// 批次已结束时清理 busy 标记,避免 onResult 丢失导致永久锁住
|
// 批次已结束时清理 busy 标记,避免 onResult 丢失导致永久锁住
|
||||||
setRunningBatchIds(new Set());
|
setRunningBatchIds(new Set());
|
||||||
}
|
}
|
||||||
|
void loadPaySessionTasks(
|
||||||
|
paySessionsRef.current.map((session) => session.batchId),
|
||||||
|
);
|
||||||
} catch {
|
} catch {
|
||||||
// 轮询失败不打扰操作
|
// 轮询失败不打扰操作
|
||||||
} finally {
|
} finally {
|
||||||
tasksLoadingRef.current = false;
|
tasksLoadingRef.current = false;
|
||||||
}
|
}
|
||||||
}, [handbook]);
|
}, [handbook, loadPaySessionTasks]);
|
||||||
|
|
||||||
useEffect(() => { loadData(); }, [loadData]);
|
useEffect(() => { loadData(); }, [loadData]);
|
||||||
|
|
||||||
@@ -482,6 +643,14 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
|
|||||||
() => visibleTasks.some((task) => ['pending', 'running', 'planned'].includes(task.status)),
|
() => visibleTasks.some((task) => ['pending', 'running', 'planned'].includes(task.status)),
|
||||||
[visibleTasks],
|
[visibleTasks],
|
||||||
);
|
);
|
||||||
|
const hasActivePayTasks = useMemo(
|
||||||
|
() => paySessions.some((session) => (
|
||||||
|
(paySessionTasks[session.batchId] || []).some(
|
||||||
|
(task) => ['pending', 'running', 'planned'].includes(task.status),
|
||||||
|
)
|
||||||
|
)),
|
||||||
|
[paySessionTasks, paySessions],
|
||||||
|
);
|
||||||
|
|
||||||
// 正在执行任务的账号集合,用于按账号维度禁用,避免同一账号并发跑不同类型任务
|
// 正在执行任务的账号集合,用于按账号维度禁用,避免同一账号并发跑不同类型任务
|
||||||
const runningAccountIds = useMemo(() => {
|
const runningAccountIds = useMemo(() => {
|
||||||
@@ -494,26 +663,35 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
|
|||||||
return set;
|
return set;
|
||||||
}, [visibleTasks]);
|
}, [visibleTasks]);
|
||||||
|
|
||||||
// 从后端任务派生正在运行的批次 ID(刷新页面后仍可恢复,用于显示停止按钮)
|
// 只恢复当前用户自己创建的活跃批次;管理员全量可见不等于可以一键停掉别人。
|
||||||
const activeBatchIds = useMemo(() => {
|
const activeBatchIds = useMemo(() => {
|
||||||
const set = new Set<string>();
|
const set = new Set<string>();
|
||||||
for (const task of visibleTasks) {
|
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);
|
set.add(task.batch_id);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return set;
|
return set;
|
||||||
}, [visibleTasks]);
|
}, [user?.id, visibleTasks]);
|
||||||
|
|
||||||
const selectedHasRunning = selectedIds.some((id) => runningAccountIds.has(id));
|
const selectedHasRunning = selectedIds.some((id) => runningAccountIds.has(id));
|
||||||
|
|
||||||
// 任务状态由 WS(level=task) 即时推送;轮询仅作兜底(多标签页/断线重连),
|
// 任务状态由 WS(level=task) 即时推送;轮询仅作兜底(多标签页/断线重连),
|
||||||
// 有活跃任务或 WS 连接时 5 秒一次,空闲 30 秒轻量刷新
|
// 有活跃任务或 WS 连接时 5 秒一次,空闲 30 秒轻量刷新
|
||||||
useEffect(() => {
|
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);
|
const timer = setInterval(loadTasks, intervalMs);
|
||||||
return () => clearInterval(timer);
|
return () => clearInterval(timer);
|
||||||
}, [hasActiveTasks, loadTasks, logs.connected, runningBatchIds]);
|
}, [hasActivePayTasks, hasActiveTasks, loadTasks, logs.connected, runningBatchIds]);
|
||||||
|
|
||||||
const openQrTask = useCallback((task: DouyuTaskItem, activate = true) => {
|
const openQrTask = useCallback((task: DouyuTaskItem, activate = true) => {
|
||||||
autoOpenedQrTaskIds.current.add(task.id);
|
autoOpenedQrTaskIds.current.add(task.id);
|
||||||
@@ -544,14 +722,89 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
|
|||||||
setEsportsBindTask(task);
|
setEsportsBindTask(task);
|
||||||
}, [closeAllQrTasks]);
|
}, [closeAllQrTasks]);
|
||||||
|
|
||||||
const openPayTasks = useCallback((batchId?: string) => {
|
const addPaySession = useCallback((session: DouyuPaySession) => {
|
||||||
if (batchId) {
|
setPaySessionsSafely((current) => {
|
||||||
setPayBatchIds((prev) => (prev.includes(batchId) ? prev : [...prev, batchId]));
|
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();
|
closeAllQrTasks();
|
||||||
setEsportsBindTask(null);
|
setEsportsBindTask(null);
|
||||||
setPayOpen(true);
|
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 即可);多账号并行,不互斥
|
// 自动弹出最新绑定二维码(running 有 url 即可);多账号并行,不互斥
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -583,27 +836,6 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
|
|||||||
if (nextTask) openEsportsBindTask(nextTask);
|
if (nextTask) openEsportsBindTask(nextTask);
|
||||||
}, [esportsBindTask, openEsportsBindTask, visibleTasks]);
|
}, [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(() => {
|
useEffect(() => {
|
||||||
if (!autoOpenQrReady.current) return;
|
if (!autoOpenQrReady.current) return;
|
||||||
@@ -691,9 +923,12 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!zoomPayTask) return;
|
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);
|
if (latest && latest !== zoomPayTask) setZoomPayTask(latest);
|
||||||
}, [tasks, zoomPayTask]);
|
}, [paySessionTasks, tasks, zoomPayTask]);
|
||||||
|
|
||||||
// 多批次并发:不再用全局 busy 标志阻塞 UI,刷新频率直接用各子条件判断
|
// 多批次并发:不再用全局 busy 标志阻塞 UI,刷新频率直接用各子条件判断
|
||||||
|
|
||||||
@@ -766,10 +1001,13 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
|
|||||||
// 只有本页面创建的批次才允许主动弹二维码,防止其他工作台/浏览器的任务打扰当前操作。
|
// 只有本页面创建的批次才允许主动弹二维码,防止其他工作台/浏览器的任务打扰当前操作。
|
||||||
locallyStartedBatchIds.current.add(result.batch_id);
|
locallyStartedBatchIds.current.add(result.batch_id);
|
||||||
if (DOUYU_PAYMENT_TASK_TYPE_SET.has(taskType)) {
|
if (DOUYU_PAYMENT_TASK_TYPE_SET.has(taskType)) {
|
||||||
setPayBatchIds((prev) => (
|
addPaySession({
|
||||||
prev.includes(result.batch_id) ? prev : [...prev, result.batch_id]
|
batchId: result.batch_id,
|
||||||
));
|
taskType,
|
||||||
setPayOpen(true);
|
accountIds: Array.from(new Set(ids)),
|
||||||
|
createdAt: new Date().getTime(),
|
||||||
|
ownerUserId: user?.id || 0,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
setRunningBatchIds((prev) => new Set(prev).add(result.batch_id));
|
setRunningBatchIds((prev) => new Set(prev).add(result.batch_id));
|
||||||
logs.connectBatch(result.batch_id, `/api/douyu/ws/${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) => {
|
onTask: (rawTask) => {
|
||||||
const task = rawTask as unknown as DouyuTaskItem;
|
const task = rawTask as unknown as DouyuTaskItem;
|
||||||
if (task.handbook_scope !== handbook) return;
|
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 一致)
|
// 已有任务原位更新保持排序;新任务插入头部(与后端 id desc 一致)
|
||||||
setTasks((prev) => {
|
setTasks((prev) => {
|
||||||
if (prev.some((t) => t.id === task.id)) {
|
if (prev.some((t) => t.id === task.id)) {
|
||||||
@@ -801,17 +1064,59 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const stopBatch = async () => {
|
const stopBatchIds = async (batchIds: string[]) => {
|
||||||
const ids = Array.from(new Set([...runningBatchIds, ...activeBatchIds]));
|
const ids = Array.from(new Set(batchIds.filter(Boolean)));
|
||||||
if (ids.length === 0) return;
|
if (ids.length === 0) return;
|
||||||
try {
|
try {
|
||||||
await Promise.all(ids.map((id) => douyuApi.stopBatch(id)));
|
await Promise.all(ids.map((id) => douyuApi.stopBatch(id)));
|
||||||
message.success('已停止');
|
message.success('已停止');
|
||||||
|
await Promise.all([
|
||||||
|
loadTasks(),
|
||||||
|
loadPaySessionTasks(ids),
|
||||||
|
]);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
message.error(getErrorMessage(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) => {
|
const saveConfig = async (values: DouyuConfig) => {
|
||||||
try {
|
try {
|
||||||
const saved = await douyuApi.updateConfig(values);
|
const saved = await douyuApi.updateConfig(values);
|
||||||
@@ -1483,10 +1788,18 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
|
|||||||
// success 收尾(「已生成绑定二维码,未检测到新扫码角色」),二维码必须留着。
|
// success 收尾(「已生成绑定二维码,未检测到新扫码角色」),二维码必须留着。
|
||||||
const url = taskQrUrl(task);
|
const url = taskQrUrl(task);
|
||||||
if (!url) return null;
|
if (!url) return null;
|
||||||
|
if (
|
||||||
|
task
|
||||||
|
&& DOUYU_PAYMENT_TASK_TYPE_SET.has(task.task_type)
|
||||||
|
&& task.created_by !== user?.id
|
||||||
|
&& !isAdmin
|
||||||
|
) {
|
||||||
|
return <Text type="secondary" style={{ fontSize: 12 }}>他人处理中</Text>;
|
||||||
|
}
|
||||||
const openTask = () => {
|
const openTask = () => {
|
||||||
if (!task) return;
|
if (!task) return;
|
||||||
if (hasBindQrcode(task)) openQrTask(task);
|
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 if (task.task_type === 'get_xpd_bind_qr') openQrTask(task);
|
||||||
else openEsportsBindTask(task);
|
else openEsportsBindTask(task);
|
||||||
};
|
};
|
||||||
@@ -1571,73 +1884,173 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
|
|||||||
if (configOpen && config) setConfigFormValues({ ...config });
|
if (configOpen && config) setConfigFormValues({ ...config });
|
||||||
}, [configOpen, config]);
|
}, [configOpen, config]);
|
||||||
|
|
||||||
const payBatchIdSet = useMemo(() => new Set(payBatchIds), [payBatchIds]);
|
const accountById = useMemo(
|
||||||
const payTasks = useMemo(
|
() => new Map(accounts.map((account) => [account.id, account])),
|
||||||
() => tasks.filter(
|
[accounts],
|
||||||
(task) => DOUYU_PAYMENT_TASK_TYPE_SET.has(task.task_type)
|
|
||||||
&& payBatchIdSet.has(task.batch_id),
|
|
||||||
),
|
|
||||||
[payBatchIdSet, tasks],
|
|
||||||
);
|
);
|
||||||
const payFailedTasks = useMemo(
|
const paySessionViews = useMemo<DouyuPaySessionView[]>(() => (
|
||||||
() => payTasks.filter(
|
paySessions.map((session) => {
|
||||||
(task) => !hasPaymentQrcode(task)
|
const batchTasks = mergeTaskRows(
|
||||||
&& ['failed', 'error', 'stopped'].includes(task.status),
|
tasks.filter((task) => (
|
||||||
),
|
task.batch_id === session.batchId
|
||||||
[payTasks],
|
&& DOUYU_PAYMENT_TASK_TYPE_SET.has(task.task_type)
|
||||||
);
|
)),
|
||||||
const payQueuedTasks = useMemo(
|
paySessionTasks[session.batchId] || [],
|
||||||
() => payTasks.filter(
|
);
|
||||||
(task) => !hasPaymentQrcode(task)
|
const taskByAccount = new Map<number, DouyuTaskItem>();
|
||||||
&& ['planned', 'pending', 'running'].includes(task.status),
|
for (const task of batchTasks.sort((a, b) => a.id - b.id)) {
|
||||||
),
|
taskByAccount.set(task.account_id, task);
|
||||||
[payTasks],
|
}
|
||||||
);
|
const accountIds = [
|
||||||
const payReadyTasks = useMemo(
|
...session.accountIds,
|
||||||
() => payTasks.filter(
|
...Array.from(taskByAccount.keys()).filter(
|
||||||
(task) => hasPaymentQrcode(task)
|
(accountId) => !session.accountIds.includes(accountId),
|
||||||
&& !paymentArrived(task)
|
),
|
||||||
&& !['failed', 'error', 'stopped'].includes(task.status),
|
];
|
||||||
),
|
const items: PaymentQrQueueItem[] = [];
|
||||||
[payTasks],
|
const taskByItemKey = new Map<string, DouyuTaskItem>();
|
||||||
);
|
let readyCount = 0;
|
||||||
const payDoneCount = payTasks.length - payReadyTasks.length - payQueuedTasks.length - payFailedTasks.length;
|
let queuedCount = 0;
|
||||||
const payTaskById = useMemo(() => new Map(payTasks.map((task) => [task.id, task])), [payTasks]);
|
let doneCount = 0;
|
||||||
const payQueueItems = useMemo<PaymentQrQueueItem[]>(() => {
|
let errorCount = 0;
|
||||||
const ready = payReadyTasks.map((task) => {
|
let active = runningBatchIds.has(session.batchId);
|
||||||
const qrValue = taskQrUrl(task);
|
|
||||||
|
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 {
|
return {
|
||||||
key: task.id,
|
session,
|
||||||
title: payTaskAccountLabel(task),
|
items,
|
||||||
subtitle: `${payTaskTypeLabel(task)} · UID ${task.account_uid || '-'}`,
|
taskByItemKey,
|
||||||
description: task.message || '',
|
readyCount,
|
||||||
phase: 'ready' as const,
|
queuedCount,
|
||||||
qrValue,
|
doneCount,
|
||||||
copyValue: qrValue,
|
errorCount,
|
||||||
statusLabel: resultText(task.result, 'payment_status_label')
|
active,
|
||||||
|| TASK_STATUS_LABELS[task.status]
|
|
||||||
|| task.status,
|
|
||||||
statusColor: TASK_STATUS_COLORS[task.status] || 'default',
|
|
||||||
warning: isLoopbackPaymentUrl(qrValue)
|
|
||||||
? '二维码是本机地址(localhost),手机无法扫码'
|
|
||||||
: '',
|
|
||||||
};
|
};
|
||||||
});
|
})
|
||||||
const queued = payQueuedTasks.map((task) => ({
|
), [
|
||||||
key: `queued-${task.id}`,
|
accountById,
|
||||||
title: payTaskAccountLabel(task),
|
nowSeconds,
|
||||||
subtitle: `${payTaskTypeLabel(task)} · UID ${task.account_uid || '-'}`,
|
paySessionTasks,
|
||||||
phase: task.status === 'running' ? 'generating' as const : 'queued' as const,
|
paySessions,
|
||||||
}));
|
runningBatchIds,
|
||||||
const failed = payFailedTasks.map((task) => ({
|
tasks,
|
||||||
key: `failed-${task.id}`,
|
]);
|
||||||
title: payTaskAccountLabel(task),
|
const activePaySessionView = paySessionViews.find(
|
||||||
subtitle: `${payTaskTypeLabel(task)} · UID ${task.account_uid || '-'}`,
|
(view) => view.session.batchId === activePayBatchId,
|
||||||
phase: 'error' as const,
|
) || paySessionViews[0];
|
||||||
error: task.message || '支付码生成失败',
|
const payReadyCount = activePaySessionView?.readyCount || 0;
|
||||||
}));
|
const payQueuedCount = activePaySessionView?.queuedCount || 0;
|
||||||
return [...ready, ...queued, ...failed];
|
const payDoneCount = activePaySessionView?.doneCount || 0;
|
||||||
}, [payFailedTasks, payQueuedTasks, payReadyTasks]);
|
const payErrorCount = activePaySessionView?.errorCount || 0;
|
||||||
|
const activePaySessionOwned = Boolean(
|
||||||
|
activePaySessionView
|
||||||
|
&& activePaySessionView.session.ownerUserId === user?.id,
|
||||||
|
);
|
||||||
const zoomPayUrl = taskQrUrl(zoomPayTask);
|
const zoomPayUrl = taskQrUrl(zoomPayTask);
|
||||||
const copyPaymentLink = async (value: string) => {
|
const copyPaymentLink = async (value: string) => {
|
||||||
if (!value) {
|
if (!value) {
|
||||||
@@ -2098,7 +2511,19 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
|
|||||||
</Tooltip>
|
</Tooltip>
|
||||||
<Button icon={<ReloadOutlined />} onClick={loadData} loading={loading}>刷新</Button>
|
<Button icon={<ReloadOutlined />} onClick={loadData} loading={loading}>刷新</Button>
|
||||||
{canConfig && <Button icon={<SettingOutlined />} onClick={() => setConfigOpen(true)}>配置</Button>}
|
{canConfig && <Button icon={<SettingOutlined />} onClick={() => setConfigOpen(true)}>配置</Button>}
|
||||||
{(activeBatchIds.size > 0 || runningBatchIds.size > 0) && <Button danger icon={<StopOutlined />} onClick={stopBatch}>停止</Button>}
|
{(activeBatchIds.size > 0 || runningBatchIds.size > 0) && (
|
||||||
|
<Popconfirm
|
||||||
|
title="停止我的全部活跃任务?"
|
||||||
|
description="只会停止当前账号创建的批次,不影响其他用户。"
|
||||||
|
okText="停止"
|
||||||
|
cancelText="取消"
|
||||||
|
onConfirm={stopBatch}
|
||||||
|
>
|
||||||
|
<Button danger icon={<StopOutlined />}>
|
||||||
|
停止我的任务
|
||||||
|
</Button>
|
||||||
|
</Popconfirm>
|
||||||
|
)}
|
||||||
</Space>
|
</Space>
|
||||||
</Space>
|
</Space>
|
||||||
|
|
||||||
@@ -2567,10 +2992,11 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
|
|||||||
<CreditCardOutlined />
|
<CreditCardOutlined />
|
||||||
<span>
|
<span>
|
||||||
支付码
|
支付码
|
||||||
{payQueueItems.length > 0
|
{activePaySessionView
|
||||||
? `(${payReadyTasks.length} 个待扫码`
|
? `(${payReadyCount} 个可扫码`
|
||||||
+ `${payQueuedTasks.length ? ` · ${payQueuedTasks.length} 个排队中` : ''}`
|
+ `${payQueuedCount ? ` · ${payQueuedCount} 个生成中` : ''}`
|
||||||
+ `${payDoneCount ? ` · ${payDoneCount} 个已完成` : ''})`
|
+ `${payErrorCount ? ` · ${payErrorCount} 个失败` : ''}`
|
||||||
|
+ `${payDoneCount ? ` · ${payDoneCount} 个已到账` : ''})`
|
||||||
: ''}
|
: ''}
|
||||||
</span>
|
</span>
|
||||||
</Space>
|
</Space>
|
||||||
@@ -2579,35 +3005,75 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
|
|||||||
onCancel={() => setPayOpen(false)}
|
onCancel={() => setPayOpen(false)}
|
||||||
footer={(
|
footer={(
|
||||||
<Space wrap>
|
<Space wrap>
|
||||||
<Text type="secondary">
|
|
||||||
多选账号会并行生成多个码;支付到账后自动从待扫码队列移除
|
|
||||||
</Text>
|
|
||||||
<Button onClick={() => setPayOpen(false)}>关闭</Button>
|
<Button onClick={() => setPayOpen(false)}>关闭</Button>
|
||||||
<Button
|
{activePaySessionView && activePaySessionOwned && (
|
||||||
onClick={() => {
|
<Popconfirm
|
||||||
setPayBatchIds([]);
|
title="停止当前充值批次?"
|
||||||
setPayOpen(false);
|
description="只停止当前 Tab 的批次,不会影响其他批次。"
|
||||||
}}
|
okText="停止"
|
||||||
>
|
cancelText="取消"
|
||||||
清空列表
|
onConfirm={() => void stopActivePaySession()}
|
||||||
|
>
|
||||||
|
<Button
|
||||||
|
danger
|
||||||
|
icon={<StopOutlined />}
|
||||||
|
loading={stoppingPayBatchId === activePaySessionView.session.batchId}
|
||||||
|
disabled={!activePaySessionView.active}
|
||||||
|
>
|
||||||
|
停止当前批次
|
||||||
|
</Button>
|
||||||
|
</Popconfirm>
|
||||||
|
)}
|
||||||
|
<Button onClick={closeActivePaySession} disabled={!activePaySessionView}>
|
||||||
|
关闭当前会话
|
||||||
</Button>
|
</Button>
|
||||||
</Space>
|
</Space>
|
||||||
)}
|
)}
|
||||||
centered
|
centered
|
||||||
width={920}
|
width={920}
|
||||||
>
|
>
|
||||||
<PaymentQrQueue
|
{paySessionViews.length > 0 ? (
|
||||||
items={payQueueItems}
|
<Tabs
|
||||||
emptyText={payDoneCount > 0
|
activeKey={activePaySessionView?.session.batchId}
|
||||||
? '待扫码队列已清空,支付完成的账号已自动移除'
|
onChange={(batchId) => {
|
||||||
: '当前没有待扫码支付码'}
|
setActivePayBatchId(batchId);
|
||||||
queuedText="正在排队生成斗鱼支付码"
|
void loadPaySessionTasks([batchId]);
|
||||||
onZoom={(item) => {
|
}}
|
||||||
const task = payTaskById.get(Number(item.key));
|
items={paySessionViews.map((view) => ({
|
||||||
if (task) setZoomPayTask(task);
|
key: view.session.batchId,
|
||||||
}}
|
label: (
|
||||||
onCopy={(item) => void copyPaymentLink(item.copyValue || item.qrValue || '')}
|
<Space size={4}>
|
||||||
/>
|
<span>
|
||||||
|
{paySessionTypeLabel(view.session.taskType)}
|
||||||
|
{' · '}
|
||||||
|
{paySessionTime(view.session.createdAt)}
|
||||||
|
</span>
|
||||||
|
<Tag color={view.active ? 'processing' : 'default'}>
|
||||||
|
{view.doneCount}/{view.session.accountIds.length}
|
||||||
|
</Tag>
|
||||||
|
</Space>
|
||||||
|
),
|
||||||
|
children: (
|
||||||
|
<PaymentQrQueue
|
||||||
|
items={view.items}
|
||||||
|
emptyText={view.doneCount > 0
|
||||||
|
? '当前批次已到账,支付完成的账号已原位移除'
|
||||||
|
: '当前批次没有待扫码支付码'}
|
||||||
|
queuedText="正在并行生成斗鱼支付码"
|
||||||
|
onZoom={(item) => {
|
||||||
|
const task = view.taskByItemKey.get(String(item.key));
|
||||||
|
if (task) setZoomPayTask(task);
|
||||||
|
}}
|
||||||
|
onCopy={(item) => void copyPaymentLink(
|
||||||
|
item.copyValue || item.qrValue || '',
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
),
|
||||||
|
}))}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<Text type="secondary">当前没有充值会话</Text>
|
||||||
|
)}
|
||||||
</Modal>
|
</Modal>
|
||||||
|
|
||||||
<Modal
|
<Modal
|
||||||
@@ -2627,15 +3093,18 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
|
|||||||
message={payTaskTypeLabel(zoomPayTask) + '已完成'}
|
message={payTaskTypeLabel(zoomPayTask) + '已完成'}
|
||||||
description={zoomPayTask.message || ''}
|
description={zoomPayTask.message || ''}
|
||||||
/>
|
/>
|
||||||
) : ['failed', 'error', 'stopped'].includes(zoomPayTask.status) ? (
|
|
||||||
<Alert
|
|
||||||
type={zoomPayTask.status === 'stopped' ? 'warning' : 'error'}
|
|
||||||
showIcon
|
|
||||||
message={zoomPayTask.status === 'stopped' ? '任务已停止' : '支付码任务未完成'}
|
|
||||||
description={zoomPayTask.message || ''}
|
|
||||||
/>
|
|
||||||
) : zoomPayUrl ? (
|
) : zoomPayUrl ? (
|
||||||
<Space direction="vertical" size={10} style={{ width: '100%' }}>
|
<Space direction="vertical" size={10} style={{ width: '100%' }}>
|
||||||
|
{['failed', 'error', 'stopped'].includes(zoomPayTask.status) && (
|
||||||
|
<Alert
|
||||||
|
type={zoomPayTask.status === 'stopped' ? 'warning' : 'error'}
|
||||||
|
showIcon
|
||||||
|
message={zoomPayTask.status === 'stopped'
|
||||||
|
? '任务已停止,二维码仍保留'
|
||||||
|
: '任务异常,二维码仍保留'}
|
||||||
|
description="请确认是否已经扫码支付;到账状态尚未确认。"
|
||||||
|
/>
|
||||||
|
)}
|
||||||
<div
|
<div
|
||||||
ref={payQrCanvasWrapRef}
|
ref={payQrCanvasWrapRef}
|
||||||
style={{ display: 'inline-block', background: '#fff', padding: 12, lineHeight: 0 }}
|
style={{ display: 'inline-block', background: '#fff', padding: 12, lineHeight: 0 }}
|
||||||
@@ -2644,6 +3113,13 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
|
|||||||
</div>
|
</div>
|
||||||
<QrActions wrapRef={payQrCanvasWrapRef} url={zoomPayUrl} disabled={!zoomPayUrl} />
|
<QrActions wrapRef={payQrCanvasWrapRef} url={zoomPayUrl} disabled={!zoomPayUrl} />
|
||||||
</Space>
|
</Space>
|
||||||
|
) : ['failed', 'error', 'stopped'].includes(zoomPayTask.status) ? (
|
||||||
|
<Alert
|
||||||
|
type={zoomPayTask.status === 'stopped' ? 'warning' : 'error'}
|
||||||
|
showIcon
|
||||||
|
message={zoomPayTask.status === 'stopped' ? '任务已停止' : '支付码任务未完成'}
|
||||||
|
description={zoomPayTask.message || ''}
|
||||||
|
/>
|
||||||
) : (
|
) : (
|
||||||
<Text type="secondary">支付码生成中...</Text>
|
<Text type="secondary">支付码生成中...</Text>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -8,6 +8,15 @@ export { eliteIsExpired, eliteStatusText } from '../../utils/douyuElite';
|
|||||||
|
|
||||||
export type HandbookKind = 'elite' | 'esports' | 'peace';
|
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<string>(
|
||||||
|
DOUYU_PAYMENT_TASK_TYPES,
|
||||||
|
);
|
||||||
|
|
||||||
export const TASK_STATUS_COLORS: Record<string, string> = {
|
export const TASK_STATUS_COLORS: Record<string, string> = {
|
||||||
planned: 'default',
|
planned: 'default',
|
||||||
pending: '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_GOLD_AMOUNT_STORAGE_KEY = 'douyu_task_gold_amount';
|
||||||
export const DOUYU_GIFT_COUNT_STORAGE_KEY = 'douyu_task_gift_count';
|
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_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 避开旧版页面切换时写入其他工作台的共享账号列表。
|
// v2 避开旧版页面切换时写入其他工作台的共享账号列表。
|
||||||
export const DOUYU_WORKBENCH_IDS_STORAGE_KEY = (kind: HandbookKind) => `douyu_task_workbench_ids_v2_${kind}`;
|
export const DOUYU_WORKBENCH_IDS_STORAGE_KEY = (kind: HandbookKind) => `douyu_task_workbench_ids_v2_${kind}`;
|
||||||
export const CONFIRM_FAIL_TIP_SECONDS = 6;
|
export const CONFIRM_FAIL_TIP_SECONDS = 6;
|
||||||
@@ -151,7 +164,7 @@ export function taskQrUrl(task: DouyuTaskItem | null | undefined): string {
|
|||||||
if (!task) return '';
|
if (!task) return '';
|
||||||
if (task.task_type === 'get_bind_qr') return resultText(task.result, 'url');
|
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 (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');
|
return resultText(task.result, 'pay_url');
|
||||||
}
|
}
|
||||||
if (['prepare_esports_bind', 'get_esports_bind_qr'].includes(task.task_type)) {
|
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 {
|
export function hasPaymentQrcode(task: DouyuTaskItem | null | undefined): boolean {
|
||||||
return Boolean(
|
return Boolean(
|
||||||
task
|
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'),
|
&& resultText(task.result, 'pay_url'),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function paymentArrived(task: DouyuTaskItem | null | undefined): boolean {
|
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;
|
if (task.status !== 'success') return false;
|
||||||
return task.result?.gold_recharged === true
|
return task.result?.gold_recharged === true
|
||||||
|| task.result?.elite_opened === true
|
|| task.result?.elite_opened === true
|
||||||
|
|||||||
Reference in New Issue
Block a user