fix(account): 一键查询按反馈收敛 —— 只在账号管理展示、结果落账号、修 1970 显示

按用户反馈改了四处。

## ① 结果只在账号管理展示(不再出现在精英宝典/电竞手册页)

移除了工作台页的结果弹窗与导入。**类型集合保留**(三个工作台都有)——
因为账号页批量建任务要用 `handbook_scope` 过 `DOUYU_HANDBOOK_TASK_TYPES` 校验,
去掉会被「该任务不属于当前工作台」拦掉;去掉的只是**快捷操作按钮**。

## ② 不再每次弹出

原来任务跑完就自动弹面板,而且任务会被反复轮询到。现在整个弹窗机制去掉了:
结果落在账号上,打开账号就能看。

## ③ 结果写进账号(新增迁移 0047)

新增 `accounts.overview_snapshot`(JSON)+ `overview_queried_at`,覆盖式只留最新一份。
详情页直接读账号上的快照,不再轮询任务。

**为什么放账号而不是只留任务里**:任务会被保留策略清掉(长保留档 90 天),
而「这个账号现在什么情况」是**账号的信息**,不该依赖一条日志的寿命。

## ④ 修 1970/1/1 08:00:00(真 bug)

斗鱼用 `0` / `"0"` / 空串表示「没有这个时间」。原实现直接透传,
前端 `new Date(0)` → **1970/1/1 08:00:00** —— 运营会以为"到期时间是 1970 年"。

两端都修了:
- 后端新增 `_ts()`,把 `0`/`"0"`/空/负数 归成 `None`(积分到期、宝典到期、
  电竞到期、商品活动时间四处都过一遍)
- 前端 `formatTime` 也把 `0`/负数显示成 `-`(上游再出错也不至于显示 1970)

## 测试(+14 条,共 36)

- `TestTimestampNormalisation`:`0`/`"0"`/空/负数 → `None`;真实时间戳透传
- `TestSnapshotIsWrittenToAccount`:快照与时间落到账号上、
  **`willExpireTime="0"` 不能落库成 0**(1970 的回归用例)、覆盖式不追加

## 验证

`TZ=Asia/Shanghai` **588 passed / 6 skipped**;`TZ=UTC` 41 passed;
ruff 全绿;前端 build 通过、lint 0 errors。
This commit is contained in:
yml2213
2026-10-04 19:12:51 +08:00
parent d285196287
commit 3866b49087
11 changed files with 252 additions and 74 deletions
+122
View File
@@ -8,6 +8,8 @@ from __future__ import annotations
from datetime import UTC, datetime
import pytest
from tests.support.db import get_test_engine, make_test_session
from web.backend.models import Account, AccountEvent, DouyuTask, User
from web.backend.services.douyu_runner_overview import (
@@ -384,3 +386,123 @@ def test_queried_at_is_utc_isoformat():
assert got and isinstance(got, list)
# 顺手确认 UTC 约定没被破坏
assert datetime.now(UTC).tzinfo is not None
class TestTimestampNormalisation:
"""斗鱼用 `0` / `"0"` / 空串表示「没有这个时间」。
直接透传的后果:前端把 `0` 当 Unix 时间戳 → 显示 **1970/1/1 08:00:00**,
运营会以为"到期时间是 1970 年"。(这个 bug 真出现过,用户报的。)
"""
@pytest.mark.parametrize("bad", [0, "0", "", " ", None, -1, "-1", False])
def test_no_value_becomes_none(self, bad):
from web.backend.services.douyu_runner_overview import _ts
assert _ts(bad) is None, f"{bad!r} 应归成 None,否则会显示成 1970"
@pytest.mark.parametrize("good", [1795967999, "1795967999", 1795967999000])
def test_real_timestamps_pass_through(self, good):
from web.backend.services.douyu_runner_overview import _ts
assert _ts(good) == good
class TestSnapshotIsWrittenToAccount:
"""结果要落到**账号**上,不是只留在任务里。
任务会被保留策略清掉,而「这个账号现在什么情况」是账号的信息 ——
应该在账号管理里看,不该依赖一条日志的寿命。
"""
def setup_method(self):
self.engine = get_test_engine()
self.session = make_test_session(self.engine)
self.user = User(username="snap-admin", password_hash="h", role="super_admin")
self.session.add(self.user)
self.session.flush()
self.account = Account(
username="snap-acc", password="p", email="s@e.com", email_password="ep"
)
self.session.add(self.account)
self.session.commit()
def teardown_method(self):
self.session.close()
def _run(self, client=None):
from web.backend.services.douyu_runner_overview import OverviewMixin
class _H(OverviewMixin):
def _client(self, cookie):
return client or _FakeClient()
def _mark_task(self, *a, **k):
pass
def _push_log(self, *a, **k):
pass
def _refresh_account_gold_balance(self, c, a):
return {"gold_balance": 7, "exchange_balance": 1}
def _refresh_account_points(self, c, a, cookie, *, ctn=None):
# 斗鱼返回 0 表示没有到期时间 —— 这里模拟它
return {
"points": 5,
"points_query": {"raw": {"data": {"willExpireTime": "0"}}},
}
def _refresh_elite_handbook(self, c, a, *, manual_id, rid=""):
return {
"elite_opened": False,
"elite_expire_time": 0,
"elite_manual_score": 0,
}
def _refresh_esports_handbook(self, c, a, *, manual_id):
return {"esports_manual_type": 0, "esports_manual_score": 0}
task = DouyuTask(
batch_id="snap",
account_id=self.account.id,
task_type="query_account_overview",
handbook_scope="elite",
status="running",
message="",
created_by=self.user.id,
)
self.session.add(task)
self.session.commit()
_H()._execute_query_account_overview(
self.session,
task,
self.account,
"c",
{"manual_id": "M", "esports_manual_id": "E", "rid": "R"},
)
self.session.commit()
self.session.refresh(self.account)
return task
def test_snapshot_and_time_are_stored_on_account(self):
self._run()
assert self.account.overview_snapshot is not None
assert self.account.overview_queried_at is not None
assert self.account.overview_snapshot["assets"]["gold_balance"] == 7
def test_no_expiry_is_stored_as_none_not_zero(self):
"""回归:`willExpireTime = "0"` 不能原样落库成 0(会显示 1970)。"""
self._run()
snap = self.account.overview_snapshot
assert snap["assets"]["points_expire_at"] is None
assert snap["elite"]["expire_time"] is None
def test_snapshot_is_overwritten_not_appended(self):
self._run()
first = dict(self.account.overview_snapshot)
self._run()
self.session.refresh(self.account)
assert self.account.overview_snapshot["assets"]["gold_balance"] == 7
assert self.account.overview_snapshot is not None
assert first["assets"]["gold_balance"] == 7
+1 -1
View File
@@ -26,7 +26,7 @@ TESTS_DIR = Path(__file__).resolve().parent
PROJECT_ROOT = TESTS_DIR.parent
VERSIONS_DIR = PROJECT_ROOT / "web" / "backend" / "migrations" / "versions"
HEAD_REVISION = "20261004_0046"
HEAD_REVISION = "20261004_0047"
# 迁移新增、但不声明在模型里的复合查询索引。
EXTRA_INDEXES = (
@@ -0,0 +1,47 @@
"""账号上存「一键查询」快照:`overview_snapshot` / `overview_queried_at`
一键查询的结果以前只写在 `douyu_tasks.result` 里。那样有两个问题:
1. 任务会被保留策略清掉(`query_account_overview` 属长保留档,90 天),
而运营关心的是「**这个账号现在什么情况**」,不该依赖一条日志的寿命;
2. 想看结果得去斗鱼工作台翻任务 —— 但它本质是**账号的信息**,
应该在账号管理里。
所以把最近一次快照落到账号上(覆盖式,只留最新一份)。
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
revision: str = "20261004_0047"
down_revision: str | None = "20261004_0046"
branch_labels: str | None = None
depends_on: str | None = None
def upgrade() -> None:
op.add_column(
"accounts",
sa.Column(
"overview_snapshot",
sa.JSON(),
nullable=True,
comment="最近一次一键查询的结构化结果",
),
)
op.add_column(
"accounts",
sa.Column(
"overview_queried_at",
sa.DateTime(),
nullable=True,
comment="最近一次一键查询的时间",
),
)
def downgrade() -> None:
op.drop_column("accounts", "overview_queried_at")
op.drop_column("accounts", "overview_snapshot")
+6
View File
@@ -104,6 +104,12 @@ class Account(Base):
role_bind_status: Mapped[str] = mapped_column(
String(16), default="unknown", server_default="unknown"
)
# 最近一次「一键查询」的快照(结构化结果)。存在账号上而不是只留在任务里:
# 任务会被保留策略清掉,而运营看的是"这个账号现在什么情况"。
overview_snapshot: Mapped[dict | None] = mapped_column(JSON, nullable=True)
overview_queried_at: Mapped[datetime | None] = mapped_column(
UTCDateTime, nullable=True
)
# 积分**到期时刻**(斗鱼在积分查询里给 `willExpireTime`,只有送礼后的那次查询才有)。
# 积分到期是账号资产的真实减少,但斗鱼不会「通知」你 —— 所以这里记下到期时刻,
# 由作业在到期后补记一条 `points_expire` 事件(否则这个减少在时间线上是空白)。
+3
View File
@@ -306,6 +306,9 @@ def list_accounts(
last_exchange_at=exchange_stats.get(acc.id, (0, None, ""))[1],
last_exchange_name=exchange_stats.get(acc.id, (0, None, ""))[2],
**bind_payload(acc),
# 最近一次「一键查询」快照:存在账号上,不依赖任务日志的寿命
overview_snapshot=acc.overview_snapshot,
overview_queried_at=acc.overview_queried_at,
)
# 只有管理员可看完整字段(密码、邮箱等)
if can_include_sensitive:
+31 -5
View File
@@ -123,8 +123,8 @@ def extract_high_value_goods(
"score": hit.get("score") if hit else None,
"count": hit.get("count") if hit else None,
"count_limited": hit.get("countLimited") if hit else None,
"start_time": hit.get("startTime") if hit else None,
"end_time": hit.get("endTime") if hit else None,
"start_time": _ts(hit.get("startTime")) if hit else None,
"end_time": _ts(hit.get("endTime")) if hit else None,
"pic": str(hit.get("pic") or "") if hit else "",
"in_goods_list": hit is not None,
"missing": hit is None and not got,
@@ -153,6 +153,27 @@ def _goods_config(config: dict) -> list[str]:
return list(DEFAULT_HIGH_VALUE_GOODS)
def _ts(value: Any) -> Any:
"""斗鱼用 `0` / `"0"` / 空串表示「没有这个时间」。
直接透传的后果:前端把 `0` 当 Unix 时间戳 → 显示成 **1970/1/1 08:00:00**,
运营看到会以为"到期时间是 1970 年"。所以在这里就归成 `None`,
让「没有」和「有一个很早的时间」区分得开。
"""
if value is None:
return None
if isinstance(value, bool):
return None
if isinstance(value, (int, float)):
return None if int(value) <= 0 else value
text = str(value).strip()
if not text:
return None
if text.lstrip("-").isdigit() and int(text) <= 0:
return None
return value
class OverviewMixin:
"""一键查询域:只读聚合,不写状态、不发事件。"""
@@ -225,7 +246,7 @@ class OverviewMixin:
overview["assets"]["points"] = points.get("points")
# `_refresh_account_points` 只回 {"points", "points_query"},
# 到期时间得从 points_query 里取 —— 复用已有具名函数,不自己扒结构。
overview["assets"]["points_expire_at"] = _points_expire_at(points)
overview["assets"]["points_expire_at"] = _ts(_points_expire_at(points))
except Exception as exc: # noqa: BLE001
errors["points"] = _err(exc)
@@ -239,7 +260,7 @@ class OverviewMixin:
)
overview["elite"] = {
"opened": elite.get("elite_opened"),
"expire_time": elite.get("elite_expire_time"),
"expire_time": _ts(elite.get("elite_expire_time")),
"points": elite.get("elite_manual_score"),
}
except Exception as exc: # noqa: BLE001
@@ -265,7 +286,7 @@ class OverviewMixin:
"opened": opened,
"manual_type": manual_type,
"points": esports.get("esports_points"),
"expire_time": esports.get("esports_expire_time"),
"expire_time": _ts(esports.get("esports_expire_time")),
}
except Exception as exc: # noqa: BLE001
errors["esports"] = _err(exc)
@@ -324,5 +345,10 @@ class OverviewMixin:
if errors:
message += f"({len(errors)} 项未取到)"
# 落到账号上:任务会被保留策略清掉,而「这个账号现在什么情况」是账号的信息,
# 应该在账号管理里看,不该依赖一条日志的寿命。
account.overview_snapshot = overview
account.overview_queried_at = datetime.now(UTC)
logger.info(f"[douyu] 一键查询账号 {account.id}: {message}")
self._mark_task(db, task, "success", message, overview)
+3
View File
@@ -172,6 +172,9 @@ export interface AccountOverview {
esports_game_name: string;
esports_can_change_time: number | null;
stats: AccountOverviewStats;
/** 最近一次「一键查询」的快照(结构与后端 query_account_overview 的 result 一致) */
overview_snapshot: import('../pages/douyu-tasks/AccountOverviewPanel').AccountOverviewResult | null;
overview_queried_at: string | null;
/** 开通时间来自事件表(上线后才开始记录,更早的不显示) */
opened_at: { elite: string | null; esports: string | null };
}
+22 -26
View File
@@ -8,9 +8,7 @@ import {
ArrowLeftOutlined, EditOutlined, ReloadOutlined, ThunderboltOutlined,
} from '@ant-design/icons';
import { accountApi, douyuApi, userApi, type AccountEventItem, type AccountOverview, type UserInfo } from '../api/modules';
import AccountOverviewPanel, {
type AccountOverviewResult,
} from './douyu-tasks/AccountOverviewPanel';
import AccountOverviewPanel from './douyu-tasks/AccountOverviewPanel';
import { getErrorMessage } from '../utils/error';
import { message } from '../utils/antdMessage';
import { formatTime } from '../utils/time';
@@ -118,7 +116,6 @@ export default function AccountDetailPage() {
const [tagDraft, setTagDraft] = useState('');
// 一键查询:向斗鱼实时查一次该账号的全部关键信息(异步任务 + 轮询结果)
const [ovLoading, setOvLoading] = useState(false);
const [ovResult, setOvResult] = useState<AccountOverviewResult | null>(null);
const [ovError, setOvError] = useState('');
const [tagEditing, setTagEditing] = useState(false);
const [supportUsers, setSupportUsers] = useState<UserInfo[]>([]);
@@ -140,43 +137,39 @@ export default function AccountDetailPage() {
}, []);
// 一键查询:建一个只读聚合任务 → 轮询到出结果 → 渲染面板。
// 之所以用异步任务而不是同步接口:它要串好几个斗鱼请求(可能十几秒),
// 异步能复用现成的执行器与进度推送,也不受 HTTP 请求超时限制。
// 一键查询:建一个只读聚合任务 → 轮询**账号自身**直到快照更新。
//
// 结果写在账号上(`overview_snapshot`),不是只留在任务里 ——
// 所以轮询账号就够了,也不依赖任务日志的寿命。
const runOverview = useCallback(async () => {
if (!id) return;
const accountId = Number(id);
const before = overview?.overview_queried_at ?? '';
setOvLoading(true);
setOvError('');
try {
const created = await douyuApi.createTasks({
account_ids: [Number(id)],
await douyuApi.createTasks({
account_ids: [accountId],
task_type: 'query_account_overview',
handbook_scope: 'elite',
});
const batchId = created.batch_id;
const deadline = Date.now() + 90_000; // 最多等 90 秒
const deadline = Date.now() + 120_000; // 要串好几个斗鱼请求,给足时间
while (Date.now() < deadline) {
await new Promise((resolve) => setTimeout(resolve, 2000));
const rows = await douyuApi.listTasks('elite', batchId);
const done = rows.find(
(x) => x.status === 'success' || x.status === 'failed',
);
if (done) {
if (done.status === 'failed') {
setOvError(done.message || '查询失败');
} else {
setOvResult((done.result ?? null) as AccountOverviewResult | null);
}
const fresh = await accountApi.overview(accountId);
if ((fresh.overview_queried_at ?? '') !== before) {
setOverview(fresh);
message.success('查询完成');
return;
}
}
setOvError('查询超时(90 秒未出结果),可到斗鱼工作台看这个任务的进度');
setOvError('查询超时(120 秒未出结果),稍后刷新页面看看');
} catch (error) {
setOvError(getErrorMessage(error));
} finally {
setOvLoading(false);
}
}, [id]);
}, [id, overview?.overview_queried_at]);
const loadOverview = useCallback(async () => {
if (!accountId) return;
@@ -394,12 +387,15 @@ export default function AccountDetailPage() {
{ovError}
</Text>
)}
{ovResult ? (
<AccountOverviewPanel result={ovResult} />
{overview?.overview_snapshot ? (
<AccountOverviewPanel
result={overview.overview_snapshot}
queriedAt={overview.overview_queried_at}
/>
) : (
<Text type="secondary">
实时向斗鱼查询:鱼翅 / 积分(含到期时间)/ 精英宝典 / 电竞手册 / 官方兑换记录,
并重点标出「兔兔白日梦」「狂战萌兔」是否已拥有。
并重点标出「兔兔白日梦」「狂战萌兔」是否已获得。结果会**存在这个账号上**。
</Text>
)}
</Card>
@@ -57,10 +57,17 @@ const ERROR_LABELS: Record<string, string> = {
exchange_records: '兑换记录',
};
/** 时间戳(秒/毫秒/字符串)→ 可读文本;认不出来就原样显示。 */
/** 时间戳(秒/毫秒/字符串)→ 可读文本;认不出来就原样显示。
*
* ⚠️ `0` / `"0"` / 空 必须显示成 `-`:斗鱼用 0 表示「没有这个时间」,
* 而 `new Date(0)` 是 **1970/1/1 08:00:00** —— 直接格式化会让运营
* 以为"到期时间是 1970 年"(这个 bug 真出现过)。
*/
function formatTime(value: string | number | null | undefined): string {
if (value === null || value === undefined || value === '') return '-';
if (typeof value === 'number' && value <= 0) return '-';
const text = String(value).trim();
if (/^-?\d+$/.test(text) && Number(text) <= 0) return '-';
let seconds: number | null = null;
if (/^\d+$/.test(text)) {
seconds = Number(text);
@@ -138,7 +145,14 @@ function HighValueCard({ goods }: { goods: HighValueGoods }) {
);
}
export default function AccountOverviewPanel({ result }: { result: AccountOverviewResult }) {
export default function AccountOverviewPanel({
result,
queriedAt,
}: {
result: AccountOverviewResult;
/** 查询时间(优先用账号上记录的,回落到结果里的) */
queriedAt?: string | null;
}) {
if (!result) return <Empty description="暂无结果" />;
const assets = result.assets || {};
const errors = result.errors || {};
@@ -247,7 +261,7 @@ export default function AccountOverviewPanel({ result }: { result: AccountOvervi
</Card>
<Text type="secondary" style={{ fontSize: 12 }}>
查询时间:{formatTime(result.queried_at)}
查询时间:{formatTime(queriedAt ?? result.queried_at)}
</Text>
</Space>
);
@@ -7,7 +7,6 @@ import {
CheckCircleOutlined, ColumnWidthOutlined, CopyOutlined, CreditCardOutlined, ExclamationCircleOutlined, FieldTimeOutlined, FilterOutlined, GiftOutlined,
ImportOutlined, QrcodeOutlined, ReloadOutlined,
SearchOutlined, SettingOutlined, ShoppingOutlined, StopOutlined,
ThunderboltOutlined,
} from '@ant-design/icons';
import {
accountApi,
@@ -19,9 +18,6 @@ import {
} from '../../api/modules';
import ExchangeResultImage from '../../components/ExchangeResultImage';
import QrActions from '../../components/QrActions';
import AccountOverviewPanel, {
type AccountOverviewResult,
} from './AccountOverviewPanel';
import { usePermissions } from '../../hooks/usePermissions';
import { useWebSocketLogs } from '../../hooks/useWebSocketLogs';
import {
@@ -153,9 +149,6 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
const autoOpenedPayTaskIds = useRef<Set<number>>(new Set());
const autoCopiedExchangeTaskIds = useRef<Set<number>>(new Set());
const autoNotifiedConfirmFailedTaskIds = useRef<Set<number>>(new Set());
// 一键查询:任务跑完后自动把结果面板弹出来(去重,同一个任务只弹一次)
const [ovPanelTask, setOvPanelTask] = useState<DouyuTaskItem | null>(null);
const shownOvTaskIds = useRef<Set<number>>(new Set());
const [confirmFailTip, setConfirmFailTip] = useState<{ taskId: number; message: string } | null>(null);
const [confirmFailCountdown, setConfirmFailCountdown] = useState(0);
const [exchangePreview, setExchangePreview] = useState<{ task: DouyuTaskItem; url: string } | null>(null);
@@ -649,22 +642,6 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
}
};
useEffect(() => {
// 一键查询的结果是一大块结构化信息,不适合塞进列表单元格 ——
// 跑完就弹面板,弹过就不再弹(任务会被反复轮询到,不去重会一直弹)。
const finished = tasks.filter(
(task) =>
task.task_type === 'query_account_overview'
&& task.status === 'success'
&& task.result,
);
const fresh = finished.find((task) => !shownOvTaskIds.current.has(task.id));
if (fresh) {
shownOvTaskIds.current.add(fresh.id);
setOvPanelTask(fresh);
}
}, [tasks]);
// qrTask 已由 useMemo 从 tasks 派生,切换 Tab / 后端 progress 写入后自动更新,无需手动跟随
useEffect(() => {
@@ -2561,18 +2538,6 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
</div>
</Modal>
<Modal
title={<Space><ThunderboltOutlined /><span>一键查询结果</span></Space>}
open={Boolean(ovPanelTask)}
onCancel={() => setOvPanelTask(null)}
footer={<Button onClick={() => setOvPanelTask(null)}>关闭</Button>}
width={780}
styles={{ body: { maxHeight: '70vh', overflowY: 'auto' } }}
>
{ovPanelTask?.result ? (
<AccountOverviewPanel result={ovPanelTask.result as AccountOverviewResult} />
) : null}
</Modal>
</div>
);
}
@@ -1,7 +1,6 @@
import type { ReactNode } from 'react';
import {
CheckCircleOutlined, CreditCardOutlined, FieldTimeOutlined, GiftOutlined,
ProfileOutlined,
QrcodeOutlined, ReloadOutlined, SearchOutlined, ShoppingOutlined,
} from '@ant-design/icons';
import type { DouyuGoodsItem, DouyuTaskItem } from '../../api/modules';
@@ -39,7 +38,6 @@ export const ELITE_QUICK_ACTIONS = [
{ key: 'query_limited_goods', icon: <SearchOutlined /> },
{ key: 'query_gold_balance', icon: <SearchOutlined /> },
{ key: 'lock_goods', icon: <ShoppingOutlined /> },
{ key: 'query_account_overview', icon: <ProfileOutlined /> },
{ key: 'exchange_goods', icon: <ShoppingOutlined /> },
{ key: 'create_gold_qr', icon: <CreditCardOutlined /> },
{ key: 'donate_elite_gift', icon: <GiftOutlined /> },
@@ -54,7 +52,6 @@ export const ESPORTS_QUICK_ACTIONS = [
{ key: 'query_limited_goods', icon: <SearchOutlined /> },
{ key: 'query_gold_balance', icon: <SearchOutlined /> },
{ key: 'refresh_esports_goods', icon: <ReloadOutlined /> },
{ key: 'query_account_overview', icon: <ProfileOutlined /> },
{ key: 'exchange_esports_goods', icon: <ShoppingOutlined /> },
{ key: 'create_gold_qr', icon: <CreditCardOutlined /> },
{ key: 'donate_esports_chicken_gift', icon: <GiftOutlined /> },
@@ -69,7 +66,6 @@ export const PEACE_QUICK_ACTIONS = [
{ key: 'query_xpd_balance', icon: <SearchOutlined /> },
{ key: 'query_xpd_fragments', icon: <SearchOutlined /> },
{ key: 'query_xpd_purchase_records', icon: <FieldTimeOutlined /> },
{ key: 'query_account_overview', icon: <ProfileOutlined /> },
{ key: 'refresh_xpd_goods', icon: <ReloadOutlined /> },
{ key: 'exchange_xpd_goods', icon: <ShoppingOutlined /> },
];