Compare commits
7
Commits
aea05952af
...
b199428619
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b199428619 | ||
|
|
6b5271c983 | ||
|
|
85a6186993 | ||
|
|
6865b916ba | ||
|
|
f416397cc8 | ||
|
|
62d9053e8a | ||
|
|
93d972d3fb |
@@ -0,0 +1,60 @@
|
||||
# 协作约定(给 AI 助手 / 协作者)
|
||||
|
||||
> 这些是用户明确表达过的偏好。**每次在这个仓库里干活前先读一遍。**
|
||||
|
||||
## 提交与推送
|
||||
|
||||
- **不要改一点就提交、推送。**
|
||||
小改动先攒着,**攒够一批**再提交;只有用户明确说「提交 / 推送」,
|
||||
或者到了一个自然的里程碑(一个完整功能做完、一轮反馈全部改完)才 commit / push。
|
||||
- 一次提交要**整合**相关改动,不要拆成一堆碎提交。
|
||||
- 推送时 `main` 与 `dev` 一起同步(`dev` 是工作分支):
|
||||
`git push gitea main` → `git checkout dev && git merge --ff-only main && git push gitea dev`。
|
||||
|
||||
## 功能改动
|
||||
|
||||
- **新功能是「增加」,不是「替换」。** 旧路径要完整保留(例:账号检测保留了
|
||||
手动粘贴,新增「按账号选择」;旧的手动输入逻辑一行未动)。
|
||||
- 改动要**务实、克制**:不做没人要的重构,不加用不上的抽象。
|
||||
- **不要重复展示同一份数据。** 数据库里已有的字段(如 `accounts.points` /
|
||||
`gold_balance` / `elite_opened`)就让已有界面显示,查询去**刷新**它们,
|
||||
不要另开一份副本 —— 同一屏出现两份会让人分不清哪份是准的。
|
||||
- **单项外部调用失败不要让整个流程失败**,但要**如实暴露**(错误写进 `errors`
|
||||
并在 UI 展示),别让「没查到」被读成「没有」。
|
||||
|
||||
## 报表 / 汇报
|
||||
|
||||
- **如实报告,包括自己的错误、误判和局限。** 不确定就说不确定,别猜。
|
||||
- **结论要有验证**:能实测就实测(本仓库有生产镜像库可用),
|
||||
能反向验证(把 bug 注入回去看用例是否变红)就反向验证。
|
||||
- 用中文回答。
|
||||
|
||||
## 一次踩过的坑(值得记住)
|
||||
|
||||
- **别拿不同时刻的快照做对比。** 曾经把相隔两个月的两条记录对比,
|
||||
把「时间差异」当成了「账号差异」,得出错误规则并写进设计文档。
|
||||
对比必须在**同一时刻**。
|
||||
- **Pydantic 会静默丢字段 —— 本仓库已经踩过三次**,每次表现都不同:
|
||||
1. 构造函数传了、模型上没声明 → `extra='ignore'` 丢掉;
|
||||
2. 模型上声明了、但**手写的 `@model_serializer` 里没列** → 属性有值、JSON 里没有;
|
||||
3. 字段名与 schema 声明的不一致(如 `elite_bind_status` vs `role_bind_status`)。
|
||||
**应对**:断言要看 **`model_dump()`(序列化结果)**,只看属性会假绿;
|
||||
改完接口先在 Python 里打一遍 `model_dump()` 确认字段真在里面。
|
||||
- **别信"测试通过" —— 用例可能是假绿的(缺 `session.commit()` 时,
|
||||
MySQL REPEATABLE READ 会让它看不到别的会话刚提交的行)。
|
||||
关键用例要做反向验证。
|
||||
- **删代码块时用"从 A 到 B"的区间删除很危险**,容易连带删掉中间的行
|
||||
(曾把 `**bind_payload(acc),` 一起删掉)。改完要**读回来确认**。
|
||||
- **`docker compose run` 默认读 stdin**:脚本用 `ssh 'bash -s' < 脚本` 喂进去时,
|
||||
它会把脚本剩下的行吃掉。要用 `docker compose run -T --rm ... </dev/null`。
|
||||
|
||||
## 仓库事实
|
||||
|
||||
| | |
|
||||
| --- | --- |
|
||||
| 工作分支 | `dev`(本地开发);`main` = 已发布;远端是 `gitea` |
|
||||
| 生产 | SSH 别名 `order+douyu_huya`(47.114.114.225),部署目录 `/root/live-hub-py` |
|
||||
| 本地生产镜像 | `douyu_login_prod`(`scripts/refresh_local_prod_mirror.sh` 同步) |
|
||||
| 测试库 | `douyu_login_test`(独立库,**不要**拿镜像库跑测试套件) |
|
||||
| 迁移 | 编号按落地顺序取,**不预留**;已应用的迁移不能改名 |
|
||||
| 前端 | `tsc -b` 开了 `noUnusedLocals`,死代码/未用导入会直接报 TS6133 |
|
||||
@@ -902,7 +902,10 @@ class TestExchangeRecordColumn(_Base):
|
||||
def _exchange(self, account_id: int, name: str, *, days_ago: int = 0):
|
||||
from datetime import timedelta
|
||||
|
||||
from web.backend.services.account_events_service import emit
|
||||
from web.backend.services.account_events_service import (
|
||||
OFFICIAL_SYNC_SOURCE,
|
||||
emit,
|
||||
)
|
||||
|
||||
emit(
|
||||
self.session,
|
||||
@@ -912,6 +915,9 @@ class TestExchangeRecordColumn(_Base):
|
||||
category="business",
|
||||
subject_key=name,
|
||||
occurred_at=NOW - timedelta(days=days_ago),
|
||||
# 列表的「兑换记录」列**只聚合斗鱼官方记录**(source=official_sync),
|
||||
# 我们当场记的那些留给详情页时间线 —— 这是刻意的口径划分。
|
||||
source=OFFICIAL_SYNC_SOURCE,
|
||||
)
|
||||
self.session.commit()
|
||||
|
||||
@@ -930,9 +936,23 @@ class TestExchangeRecordColumn(_Base):
|
||||
|
||||
item = self._item("hasex")
|
||||
assert item.exchange_count == 3
|
||||
# 「最近」按**事件 id** 取(同一天多次兑换时时间戳可能相同,靠 id 定序)
|
||||
# 「最近一次」按**事件时间**取:三条分别是 3 天前 / 1 天前 / 2 天前,
|
||||
# 所以最近的是「冠军鸡腿」(1 天前)。
|
||||
#
|
||||
# ⚠️ 这里原来断言的是「烟花」(**最后插入**的那条)—— 那是错的,
|
||||
# 因为当时后端按事件 **id** 排序,于是「最近一次」实际是"最后插入的一次"。
|
||||
# 一键查询把斗鱼官方的**历史**兑换补成事件后这个 bug 才暴露:
|
||||
# 补录的事件 id 最大、时间却最老,会把几个月前的老兑换显示成"最近一次"。
|
||||
# 现在排序是 `occurred_at DESC, id DESC`(时间相同才用 id 兜底)。
|
||||
# 后端返回事件原始 title;剥掉「兑换 」前缀是前端展示层的事。
|
||||
assert item.last_exchange_name == "兑换 烟花"
|
||||
assert item.last_exchange_name == "兑换 冠军鸡腿"
|
||||
|
||||
def test_latest_uses_id_only_to_break_ties(self):
|
||||
"""时间相同时再用 id 定序(同一天多次兑换时间戳可能一样)。"""
|
||||
account = self.make_account("tie")
|
||||
self._exchange(account.id, "先插入", days_ago=1)
|
||||
self._exchange(account.id, "后插入", days_ago=1)
|
||||
assert self._item("tie").last_exchange_name == "兑换 后插入"
|
||||
|
||||
def test_only_exchange_events_count(self):
|
||||
"""别的类型(充值 / 登录 / 状态)不能混进兑换次数。"""
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -218,6 +219,20 @@ class _Harness(OverviewMixin):
|
||||
raise RuntimeError("模拟电竞查询失败(账号没绑电竞手册)")
|
||||
return {"esports_manual_type": 1, "esports_manual_score": 10}
|
||||
|
||||
# handler 按作用域抓官方记录(三套接口),测试里给最小实现
|
||||
def _fetch_bind_info(self, client, scope, alias):
|
||||
# 测试里统一给"已绑定"(有角色名),避免依赖具体假客户端
|
||||
return {"is_bound_role": True, "is_bound_act": True, "role_name": "某角色"}
|
||||
|
||||
def _fetch_elite_records(self, client, config, manual_id, esports_manual_id):
|
||||
return client.exchange_records(manual_id=manual_id).get("records") or []
|
||||
|
||||
def _fetch_esports_records(self, client, config, manual_id, esports_manual_id):
|
||||
return []
|
||||
|
||||
def _fetch_xpd_records(self, client, config, manual_id, esports_manual_id):
|
||||
return []
|
||||
|
||||
|
||||
class TestOverviewAggregation:
|
||||
def setup_method(self):
|
||||
@@ -253,7 +268,16 @@ class TestOverviewAggregation:
|
||||
self.task,
|
||||
self.account,
|
||||
"cookie",
|
||||
{"manual_id": "M1", "esports_manual_id": "M2", "rid": "R1"},
|
||||
{
|
||||
"manual_id": "M1",
|
||||
"esports_manual_id": "M2",
|
||||
"rid": "R1",
|
||||
"xpd_act_alias": "A",
|
||||
"xpd_rid": "R",
|
||||
"xpd_act_id": "1",
|
||||
"bind_act_alias": "B",
|
||||
"esports_act_alias": "E",
|
||||
},
|
||||
)
|
||||
return h
|
||||
|
||||
@@ -463,6 +487,22 @@ class TestSnapshotIsWrittenToAccount:
|
||||
def _refresh_esports_handbook(self, c, a, *, manual_id):
|
||||
return {"esports_manual_type": 0, "esports_manual_score": 0}
|
||||
|
||||
def _fetch_bind_info(self, c, scope, alias):
|
||||
return {
|
||||
"is_bound_role": True,
|
||||
"is_bound_act": True,
|
||||
"role_name": "某角色",
|
||||
}
|
||||
|
||||
def _fetch_elite_records(self, c, cfg, mid, emid):
|
||||
return c.exchange_records(manual_id=mid).get("records") or []
|
||||
|
||||
def _fetch_esports_records(self, c, cfg, mid, emid):
|
||||
return []
|
||||
|
||||
def _fetch_xpd_records(self, c, cfg, mid, emid):
|
||||
return []
|
||||
|
||||
task = DouyuTask(
|
||||
batch_id="snap",
|
||||
account_id=self.account.id,
|
||||
@@ -479,7 +519,16 @@ class TestSnapshotIsWrittenToAccount:
|
||||
task,
|
||||
self.account,
|
||||
"c",
|
||||
{"manual_id": "M", "esports_manual_id": "E", "rid": "R"},
|
||||
{
|
||||
"manual_id": "M",
|
||||
"esports_manual_id": "E",
|
||||
"rid": "R",
|
||||
"xpd_act_alias": "A",
|
||||
"xpd_rid": "R",
|
||||
"xpd_act_id": "1",
|
||||
"bind_act_alias": "B",
|
||||
"esports_act_alias": "E",
|
||||
},
|
||||
)
|
||||
self.session.commit()
|
||||
self.session.refresh(self.account)
|
||||
@@ -641,6 +690,22 @@ class TestOverviewRefreshesAccountFields:
|
||||
a.esports_opened = True
|
||||
return {"esports_manual_type": 1, "esports_manual_score": 3}
|
||||
|
||||
def _fetch_bind_info(self, c, scope, alias):
|
||||
return {
|
||||
"is_bound_role": True,
|
||||
"is_bound_act": True,
|
||||
"role_name": "某角色",
|
||||
}
|
||||
|
||||
def _fetch_elite_records(self, c, cfg, mid, emid):
|
||||
return c.exchange_records(manual_id=mid).get("records") or []
|
||||
|
||||
def _fetch_esports_records(self, c, cfg, mid, emid):
|
||||
return []
|
||||
|
||||
def _fetch_xpd_records(self, c, cfg, mid, emid):
|
||||
return []
|
||||
|
||||
task = DouyuTask(
|
||||
batch_id="rf",
|
||||
account_id=self.account.id,
|
||||
@@ -657,7 +722,16 @@ class TestOverviewRefreshesAccountFields:
|
||||
task,
|
||||
self.account,
|
||||
"c",
|
||||
{"manual_id": "M", "esports_manual_id": "E", "rid": "R"},
|
||||
{
|
||||
"manual_id": "M",
|
||||
"esports_manual_id": "E",
|
||||
"rid": "R",
|
||||
"xpd_act_alias": "A",
|
||||
"xpd_rid": "R",
|
||||
"xpd_act_id": "1",
|
||||
"bind_act_alias": "B",
|
||||
"esports_act_alias": "E",
|
||||
},
|
||||
)
|
||||
self.session.commit()
|
||||
self.session.refresh(self.account)
|
||||
@@ -681,3 +755,619 @@ class TestOverviewRefreshesAccountFields:
|
||||
self._run(expire_at="0")
|
||||
assert self.account.points_expire_at is None
|
||||
assert self.account.overview_snapshot["assets"]["points_expire_at"] is None
|
||||
|
||||
|
||||
class TestSummaryFeedsAccountList:
|
||||
"""一键查询的结果要能反映到**账号列表**上。
|
||||
|
||||
用户报的原始问题:账号 6966677706 明明有官方兑换记录,列表却显示「未兑换」。
|
||||
|
||||
根因是**两个口径**:
|
||||
- 列表的「兑换记录」列来自我们自己的 `account_events`,而事件是**上线后**
|
||||
才开始记的 → 上线前的兑换在列表里就是空的,看着像"从没兑换过";
|
||||
- 一键查询拉的是**斗鱼官方**记录,本来能查到,但那份 JSON 有 1~2KB,
|
||||
不能塞进列表(15000 个账号会把响应放大到几十 MB)。
|
||||
|
||||
所以加了这个**极小**汇总字段 `high_value_owned`:`{"owned": [...], "exchanges": N}`。
|
||||
"""
|
||||
|
||||
def setup_method(self):
|
||||
self.engine = get_test_engine()
|
||||
self.session = make_test_session(self.engine)
|
||||
self.admin = User(username="sum-admin", password_hash="h", role="super_admin")
|
||||
self.session.add(self.admin)
|
||||
self.session.flush()
|
||||
self.account = Account(
|
||||
username="sum-acc",
|
||||
password="p",
|
||||
email="s@e.com",
|
||||
email_password="ep",
|
||||
cookie="acf_uid=1; acf_ccn=c",
|
||||
high_value_owned=["套装-兔兔白日梦"],
|
||||
overview_queried_at=datetime.now(UTC),
|
||||
overview_snapshot={"high_value_goods": []},
|
||||
)
|
||||
self.session.add(self.account)
|
||||
self.session.commit()
|
||||
|
||||
def teardown_method(self):
|
||||
self.session.close()
|
||||
|
||||
def _list(self):
|
||||
from web.backend.routers.accounts import list_accounts
|
||||
|
||||
return list_accounts(
|
||||
assigned_only=False,
|
||||
has_cookie=False,
|
||||
search="sum-acc",
|
||||
page=1,
|
||||
page_size=5,
|
||||
db=self.session,
|
||||
current=self.admin,
|
||||
)["items"]
|
||||
|
||||
def test_list_serializes_owned_suits(self):
|
||||
"""断言**序列化结果**,不是属性。
|
||||
|
||||
⚠️ `AccountOut` 有一个**手写**的 `@model_serializer`,它逐个列出要输出的字段。
|
||||
只在模型上声明字段、不写进那个列表 → **属性有值、JSON 里没有**。
|
||||
只断言属性的测试会**假绿**(踩过),所以这里一律看 `model_dump()`。
|
||||
"""
|
||||
dumped = self._list()[0].model_dump()
|
||||
assert dumped["high_value_owned"] == ["套装-兔兔白日梦"], (
|
||||
"字段没出现在序列化结果里 —— 前端拿到的 JSON 就没有它"
|
||||
)
|
||||
|
||||
def test_list_serializes_queried_marker(self):
|
||||
"""要能区分「查过但没兑换」和「还没查过」—— 否则列表会把未知当高价值。"""
|
||||
dumped = self._list()[0].model_dump()
|
||||
assert dumped["overview_queried_at"] is not None
|
||||
|
||||
def test_list_still_does_not_carry_the_full_snapshot(self):
|
||||
"""给列表加信息**不能**把 1~2KB 的整份快照带回去。"""
|
||||
dumped = self._list()[0].model_dump()
|
||||
assert "overview_snapshot" not in dumped, (
|
||||
"列表带整份快照会让 15000 个账号的响应体积爆炸"
|
||||
)
|
||||
|
||||
def test_handler_writes_the_summary(self):
|
||||
"""查询跑完必须写汇总,否则列表永远显示「未查询」。"""
|
||||
from web.backend.services.douyu_runner_overview import OverviewMixin
|
||||
|
||||
class _H(OverviewMixin):
|
||||
def _client(self, cookie):
|
||||
return _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": 1, "exchange_balance": 1}
|
||||
|
||||
def _refresh_account_points(self, c, a, cookie, *, ctn=None):
|
||||
return {
|
||||
"points": 1,
|
||||
"points_query": {"raw": {"data": {"willExpireTime": "0"}}},
|
||||
}
|
||||
|
||||
def _refresh_elite_handbook(self, c, a, *, manual_id, rid=""):
|
||||
return {
|
||||
"elite_opened": True,
|
||||
"elite_expire_time": 0,
|
||||
"elite_manual_score": 0,
|
||||
}
|
||||
|
||||
def _refresh_esports_handbook(self, c, a, *, manual_id):
|
||||
return {"esports_manual_type": 1, "esports_manual_score": 0}
|
||||
|
||||
def _fetch_elite_records(self, c, cfg, mid, emid):
|
||||
# 精英恰好 1 条(与断言一致)
|
||||
return [
|
||||
{
|
||||
"commodityName": "套装-兔兔白日梦",
|
||||
"commodityId": "C1",
|
||||
"score": "1280",
|
||||
}
|
||||
]
|
||||
|
||||
def _fetch_esports_records(self, c, cfg, mid, emid):
|
||||
return []
|
||||
|
||||
def _fetch_xpd_records(self, c, cfg, mid, emid):
|
||||
return []
|
||||
|
||||
task = DouyuTask(
|
||||
batch_id="sum",
|
||||
account_id=self.account.id,
|
||||
task_type="query_account_overview",
|
||||
handbook_scope="elite",
|
||||
status="running",
|
||||
message="",
|
||||
created_by=self.admin.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",
|
||||
"xpd_act_alias": "A",
|
||||
"xpd_rid": "R",
|
||||
"xpd_act_id": "1",
|
||||
"bind_act_alias": "B",
|
||||
"esports_act_alias": "E",
|
||||
},
|
||||
)
|
||||
self.session.commit()
|
||||
self.session.refresh(self.account)
|
||||
owned = self.account.high_value_owned
|
||||
assert owned is not None, "查询跑完必须写「已兑换过的高价值套装」"
|
||||
# _FakeClient 的兑换记录里有一条「破片手榴弹-兔兔白日梦」
|
||||
assert "兔兔白日梦" in "".join(owned)
|
||||
|
||||
|
||||
class TestOverviewSummaryMigrationIsSafeToRerun:
|
||||
"""迁移必须**可安全重跑** —— 应用启动时会自动跑它。
|
||||
|
||||
踩过的坑:回填时用了 `op.get_bind().commit()`,
|
||||
打乱了 alembic 自己的版本记账。后果很隐蔽:
|
||||
|
||||
- MySQL 的 DDL(ALTER TABLE)是**自动提交**的 → 列加上了
|
||||
- 但版本号**没更新** → 下次启动又去 ADD COLUMN
|
||||
- → `Duplicate column name 'high_value_owned'`,**服务直接起不来**
|
||||
|
||||
仓库里正常工作的老迁移(0042 的 S1 回填)用的是
|
||||
`op.get_bind().execute(...)` 且**不 commit**,提交由 alembic 负责。
|
||||
"""
|
||||
|
||||
MIGRATION = (
|
||||
Path(__file__).resolve().parents[1]
|
||||
/ "web/backend/migrations/versions/20261004_0048_high_value_owned.py"
|
||||
)
|
||||
|
||||
def _src(self) -> str:
|
||||
return self.MIGRATION.read_text(encoding="utf-8")
|
||||
|
||||
def _code(self) -> str:
|
||||
"""去掉注释后的源码。
|
||||
|
||||
必须去注释:本迁移的注释里**正解释着**「不要 conn.commit()」,
|
||||
直接子串检查会命中注释里的那句话,用例就假红了。
|
||||
"""
|
||||
lines = []
|
||||
for line in self._src().splitlines():
|
||||
stripped = line.lstrip()
|
||||
if stripped.startswith("#"):
|
||||
continue
|
||||
# 去掉行尾注释(这些迁移里没有字符串里带 # 的情况)
|
||||
if "#" in line:
|
||||
line = line[: line.index("#")]
|
||||
lines.append(line)
|
||||
return "\n".join(lines)
|
||||
|
||||
def test_does_not_commit_the_alembic_bind(self):
|
||||
"""在迁移里 commit 会破坏版本记账(本迁移踩过)。"""
|
||||
code = self._code()
|
||||
assert "conn.commit()" not in code, (
|
||||
"迁移里不要 commit op.get_bind() —— 会让版本号不更新,"
|
||||
"下次启动重复 ADD COLUMN 而把服务起不来"
|
||||
)
|
||||
|
||||
def test_guards_add_column_with_existence_check(self):
|
||||
"""加列前必须检查列是否已存在,否则不可重入。"""
|
||||
src = self._src()
|
||||
assert "_column_exists" in src, "缺少列存在性检查"
|
||||
upgrade_body = src[src.index("def upgrade()") : src.index("def downgrade()")]
|
||||
assert "_column_exists" in upgrade_body, "upgrade 里没有用存在性检查守卫"
|
||||
|
||||
def test_column_exists_helper_probes_information_schema(self):
|
||||
src = self._src()
|
||||
assert "information_schema.columns" in src, (
|
||||
"存在性检查要查 information_schema,别用 try/except 猜"
|
||||
)
|
||||
|
||||
|
||||
class TestOfficialExchangeBecomesAccountEvent:
|
||||
"""斗鱼官方兑换记录要**补成账号事件**。
|
||||
|
||||
这是「账号全生命周期 + 兑换记录」的关键一步:官方记录**带真实兑换时间**
|
||||
(`time` 字段),补成事件后时间线才是完整的,列表的兑换记录聚合也自动准确 ——
|
||||
不再需要单独维护一套"官方条数"的旁路。
|
||||
"""
|
||||
|
||||
def setup_method(self):
|
||||
self.engine = get_test_engine()
|
||||
self.session = make_test_session(self.engine)
|
||||
self.user = User(username="oe-admin", password_hash="h", role="super_admin")
|
||||
self.session.add(self.user)
|
||||
self.session.flush()
|
||||
self.account = Account(
|
||||
username="oe-acc", password="p", email="o@e.com", email_password="ep"
|
||||
)
|
||||
self.session.add(self.account)
|
||||
self.session.commit()
|
||||
|
||||
def teardown_method(self):
|
||||
self.session.close()
|
||||
|
||||
def _record(self, *, commodity_id="C1", name="套装-兔兔白日梦", when=1788054985):
|
||||
from datetime import UTC
|
||||
from datetime import datetime as _dt
|
||||
|
||||
from web.backend.services.business_events import record_official_exchange
|
||||
|
||||
return record_official_exchange(
|
||||
self.session,
|
||||
self.account,
|
||||
commodity_id=commodity_id,
|
||||
commodity_name=name,
|
||||
score=1280,
|
||||
occurred_at=_dt.fromtimestamp(when, tz=UTC),
|
||||
show_name="某昵称(安卓-微信)",
|
||||
)
|
||||
|
||||
def test_writes_event_with_real_exchange_time(self):
|
||||
"""时间必须是**真实兑换时刻**,不是"发现它的时刻"。"""
|
||||
from web.backend.services import account_events_service as svc
|
||||
|
||||
assert self._record() is True
|
||||
self.session.commit()
|
||||
event = (
|
||||
self.session.query(AccountEvent)
|
||||
.filter(AccountEvent.event_type == svc.EVENT_EXCHANGE)
|
||||
.one()
|
||||
)
|
||||
assert event.occurred_at.year == 2026
|
||||
assert event.occurred_at.month == 8 # 1788054985 → 2026-08-30 前后
|
||||
assert event.amount == -1280
|
||||
assert event.detail["source"] == "official_sync"
|
||||
assert event.source == "official_sync"
|
||||
|
||||
def test_is_idempotent(self):
|
||||
"""一键查询会被反复执行,同一条官方记录只能落一条事件。"""
|
||||
from web.backend.services import account_events_service as svc
|
||||
|
||||
assert self._record() is True
|
||||
self.session.commit()
|
||||
assert self._record() is False, "同一条记录不该重复落"
|
||||
self.session.commit()
|
||||
assert (
|
||||
self.session.query(AccountEvent)
|
||||
.filter(AccountEvent.event_type == svc.EVENT_EXCHANGE)
|
||||
.count()
|
||||
== 1
|
||||
)
|
||||
|
||||
def test_different_commodity_is_a_new_event(self):
|
||||
assert self._record(commodity_id="C1") is True
|
||||
assert self._record(commodity_id="C2", name="套装-激萌罗小黑") is True
|
||||
self.session.commit()
|
||||
|
||||
def test_missing_commodity_id_is_skipped(self):
|
||||
assert self._record(commodity_id="") is False
|
||||
|
||||
|
||||
class TestLatestExchangeFollowsEventTime:
|
||||
"""「最近一次兑换」要按**事件时间**排,不能按插入 id。
|
||||
|
||||
踩过的坑:官方历史记录被补成事件时 `id` 是新的(最大),
|
||||
但 `occurred_at` 是几个月前的。按 id 排会把一条**老**兑换显示成"最近一次" ——
|
||||
实测把 08-30 的兔兔白日梦错报成了 10-01(那是另一次兑换)。
|
||||
"""
|
||||
|
||||
def setup_method(self):
|
||||
self.engine = get_test_engine()
|
||||
self.session = make_test_session(self.engine)
|
||||
self.admin = User(username="ord-admin", password_hash="h", role="super_admin")
|
||||
self.session.add(self.admin)
|
||||
self.session.flush()
|
||||
self.account = Account(
|
||||
username="ord-acc",
|
||||
password="p",
|
||||
email="d@e.com",
|
||||
email_password="ep",
|
||||
cookie="acf_uid=1; acf_ccn=c",
|
||||
)
|
||||
self.session.add(self.account)
|
||||
self.session.commit()
|
||||
|
||||
def teardown_method(self):
|
||||
self.session.close()
|
||||
|
||||
def _add_exchange(self, title: str, when: datetime):
|
||||
from web.backend.services.account_events_service import (
|
||||
CATEGORY_BUSINESS,
|
||||
EVENT_EXCHANGE,
|
||||
OFFICIAL_SYNC_SOURCE,
|
||||
emit,
|
||||
)
|
||||
|
||||
emit(
|
||||
self.session,
|
||||
account_id=self.account.id,
|
||||
event_type=EVENT_EXCHANGE,
|
||||
title=title,
|
||||
category=CATEGORY_BUSINESS,
|
||||
occurred_at=when,
|
||||
# 列表只聚合**官方**记录,所以要标成 official_sync 才会被算进去
|
||||
source=OFFICIAL_SYNC_SOURCE,
|
||||
)
|
||||
|
||||
def _latest(self) -> str:
|
||||
from web.backend.routers.accounts import list_accounts
|
||||
|
||||
item = list_accounts(
|
||||
assigned_only=False,
|
||||
has_cookie=False,
|
||||
search="ord-acc",
|
||||
page=1,
|
||||
page_size=5,
|
||||
db=self.session,
|
||||
current=self.admin,
|
||||
)["items"][0]
|
||||
return item.model_dump()["last_exchange_name"]
|
||||
|
||||
def test_newer_event_inserted_first_still_wins(self):
|
||||
# 先插**新**的,再插**老**的:按 id 排会错,按时间排才对
|
||||
self._add_exchange("兑换 新商品", datetime(2026, 10, 1, tzinfo=UTC))
|
||||
self.session.commit()
|
||||
self._add_exchange("兑换 老商品", datetime(2026, 8, 30, tzinfo=UTC))
|
||||
self.session.commit()
|
||||
assert "新商品" in self._latest(), (
|
||||
"「最近一次」按 id 排了 —— 补录的历史事件 id 更大,会被错当成最近一次"
|
||||
)
|
||||
|
||||
|
||||
class TestEsportsExpireTimePersisted:
|
||||
"""电竞手册到期时间要**落库**(与精英对称)。
|
||||
|
||||
以前它只在 `_refresh_esports_handbook` 的返回值里带着、没写进账号,
|
||||
所以界面上电竞手册只能显示「已开通」、看不到什么时候到期(用户反馈)。
|
||||
"""
|
||||
|
||||
def setup_method(self):
|
||||
self.engine = get_test_engine()
|
||||
self.session = make_test_session(self.engine)
|
||||
self.user = User(username="exp-admin", password_hash="h", role="super_admin")
|
||||
self.session.add(self.user)
|
||||
self.session.flush()
|
||||
self.account = Account(
|
||||
username="exp-acc", password="p", email="e@e.com", email_password="ep"
|
||||
)
|
||||
self.session.add(self.account)
|
||||
self.session.commit()
|
||||
|
||||
def teardown_method(self):
|
||||
self.session.close()
|
||||
|
||||
def _refresh(self, expire_time):
|
||||
from web.backend.services.douyu_runner_manual import ManualMixin
|
||||
|
||||
class _H(ManualMixin):
|
||||
def _client(self, cookie):
|
||||
return None
|
||||
|
||||
def _push_log(self, *a, **k):
|
||||
pass
|
||||
|
||||
def _to_int(self, value):
|
||||
try:
|
||||
return int(value)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
class _Client:
|
||||
@staticmethod
|
||||
def esports_user_info(*, manual_id):
|
||||
return {"manual_type": 1, "manual_score": 7, "expire_time": expire_time}
|
||||
|
||||
_H()._refresh_esports_handbook(_Client(), self.account, manual_id="E")
|
||||
self.session.commit()
|
||||
self.session.refresh(self.account)
|
||||
|
||||
def test_expire_time_is_written(self):
|
||||
self._refresh("1795967999")
|
||||
assert self.account.esports_expire_time == 1795967999
|
||||
|
||||
def test_no_expiry_stores_none_not_zero(self):
|
||||
"""斗鱼用 0 / 空表示没有到期时间 —— 不能存成 0(界面会显示 1970/1/1)。"""
|
||||
self._refresh("0")
|
||||
assert self.account.esports_expire_time is None
|
||||
self._refresh("")
|
||||
assert self.account.esports_expire_time is None
|
||||
|
||||
|
||||
class TestDeriveFromBindInfo:
|
||||
"""从斗鱼 `bind_info` 推导绑定状态。
|
||||
|
||||
**实测校准过**(开发库 4 个账号):`is_bound_role` 为真时账号确实有角色名,
|
||||
而它们的列值全是 `unknown` —— 4 个里 3 个其实已绑定,被 unknown 盖住了。
|
||||
|
||||
⚠️ `need_bind_role` **不是**"未绑定"的信号:实测**已绑定**的账号上它也是 1。
|
||||
用它会把这 3 个已绑定的判成未绑 —— 幸好没拿它当判据。
|
||||
"""
|
||||
|
||||
def test_bound_when_role_flag_true(self):
|
||||
from web.backend.services.account_binding import (
|
||||
BIND_BOUND,
|
||||
derive_from_bind_info,
|
||||
)
|
||||
|
||||
assert (
|
||||
derive_from_bind_info({"is_bound_role": True, "role_name": "x"})
|
||||
== BIND_BOUND
|
||||
)
|
||||
|
||||
def test_bound_when_act_flag_true(self):
|
||||
"""只有 act 标志为真时也算已绑 —— 避免把"已绑但没回角色名"误报成未绑。"""
|
||||
from web.backend.services.account_binding import (
|
||||
BIND_BOUND,
|
||||
derive_from_bind_info,
|
||||
)
|
||||
|
||||
assert derive_from_bind_info({"is_bound_act": True}) == BIND_BOUND
|
||||
|
||||
def test_unbound_when_flags_explicitly_false(self):
|
||||
from web.backend.services.account_binding import (
|
||||
BIND_UNBOUND,
|
||||
derive_from_bind_info,
|
||||
)
|
||||
|
||||
assert derive_from_bind_info({"is_bound_role": False}) == BIND_UNBOUND
|
||||
assert derive_from_bind_info({"is_bound_act": "0"}) == BIND_UNBOUND
|
||||
|
||||
def test_none_when_no_conclusion(self):
|
||||
"""标志缺失 → None(推不出来),**绝不能**当成 unbound。
|
||||
|
||||
这是"没查到"和"没绑定"的分界:写 unbound 就是编造结论。
|
||||
小店未开通时实测就是这种情况(返回里没有这两个标志)。
|
||||
"""
|
||||
from web.backend.services.account_binding import derive_from_bind_info
|
||||
|
||||
assert derive_from_bind_info({}) is None
|
||||
assert derive_from_bind_info({"role_name": "x"}) is None
|
||||
assert derive_from_bind_info(None) is None
|
||||
|
||||
def test_need_bind_role_is_not_a_signal(self):
|
||||
"""回归:`need_bind_role` 在**已绑定**账号上也是 1,不能拿它判未绑。"""
|
||||
from web.backend.services.account_binding import (
|
||||
BIND_BOUND,
|
||||
derive_from_bind_info,
|
||||
)
|
||||
|
||||
info = {"is_bound_role": True, "is_bound_act": True, "need_bind_role": 1}
|
||||
assert derive_from_bind_info(info) == BIND_BOUND
|
||||
|
||||
|
||||
class TestOverviewWritesBindStatus:
|
||||
"""一键查询要把三个作用域的绑定状态**查出来并写回**。
|
||||
|
||||
这三个值以前从来没人查过,只是 S6 迁移时从旧的垃圾场列能推的推、
|
||||
推不出的留 unknown —— 于是界面上 97% 显示"未知",对运营没用。
|
||||
"""
|
||||
|
||||
def setup_method(self):
|
||||
self.engine = get_test_engine()
|
||||
self.session = make_test_session(self.engine)
|
||||
self.user = User(username="bind-admin", password_hash="h", role="super_admin")
|
||||
self.session.add(self.user)
|
||||
self.session.flush()
|
||||
self.account = Account(
|
||||
username="bind-acc",
|
||||
password="p",
|
||||
email="b@e.com",
|
||||
email_password="ep",
|
||||
role_bind_status="unknown",
|
||||
esports_bind_status="unknown",
|
||||
xpd_bind_status="unknown",
|
||||
)
|
||||
self.session.add(self.account)
|
||||
self.session.commit()
|
||||
|
||||
def teardown_method(self):
|
||||
self.session.close()
|
||||
|
||||
def _run(self, *, info_by_scope):
|
||||
from web.backend.services.douyu_runner_overview import OverviewMixin
|
||||
|
||||
class _H(OverviewMixin):
|
||||
def _client(self, c):
|
||||
return _FakeClient()
|
||||
|
||||
def _mark_task(self, *a, **k):
|
||||
pass
|
||||
|
||||
def _push_log(self, *a, **k):
|
||||
pass
|
||||
|
||||
def _fetch_bind_info(self, client, scope, alias):
|
||||
return info_by_scope[scope]
|
||||
|
||||
def _refresh_account_gold_balance(self, c, a):
|
||||
return {"gold_balance": 1, "exchange_balance": 1}
|
||||
|
||||
def _refresh_account_points(self, c, a, cookie, *, ctn=None):
|
||||
return {"points": 1, "points_query": {"raw": {"data": {}}}}
|
||||
|
||||
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}
|
||||
|
||||
def _fetch_elite_records(self, c, cfg, mid, emid):
|
||||
return []
|
||||
|
||||
def _fetch_esports_records(self, c, cfg, mid, emid):
|
||||
return []
|
||||
|
||||
def _fetch_xpd_records(self, c, cfg, mid, emid):
|
||||
return []
|
||||
|
||||
task = DouyuTask(
|
||||
batch_id="bind",
|
||||
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",
|
||||
"bind_act_alias": "B",
|
||||
"esports_act_alias": "S",
|
||||
"xpd_act_alias": "X",
|
||||
"xpd_rid": "R",
|
||||
"xpd_act_id": "1",
|
||||
},
|
||||
)
|
||||
self.session.commit()
|
||||
self.session.refresh(self.account)
|
||||
return task
|
||||
|
||||
def test_writes_derived_status(self):
|
||||
self._run(
|
||||
info_by_scope={
|
||||
"elite": {"is_bound_role": True, "role_name": "有角色"},
|
||||
"esports": {"is_bound_role": False},
|
||||
"peace": {"is_bound_role": False},
|
||||
}
|
||||
)
|
||||
assert self.account.role_bind_status == "bound"
|
||||
assert self.account.esports_bind_status == "unbound"
|
||||
assert self.account.xpd_bind_status == "unbound"
|
||||
|
||||
def test_none_derivation_keeps_original_value(self):
|
||||
"""推不出来时**不动原值** —— 不能把"没查到"写成"没绑定"。"""
|
||||
self._run(
|
||||
info_by_scope={
|
||||
"elite": {"is_bound_role": True},
|
||||
"esports": {}, # 标志缺失 → 推不出来
|
||||
"peace": {},
|
||||
}
|
||||
)
|
||||
assert self.account.role_bind_status == "bound"
|
||||
assert self.account.esports_bind_status == "unknown", "推不出来应保持原值"
|
||||
assert self.account.xpd_bind_status == "unknown"
|
||||
|
||||
@@ -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_0047"
|
||||
HEAD_REVISION = "20261004_0049"
|
||||
|
||||
# 迁移新增、但不声明在模型里的复合查询索引。
|
||||
EXTRA_INDEXES = (
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
"""账号列表要显示一键查询的结果:加一个**极小**的字段
|
||||
|
||||
账号列表的「兑换记录」列一直来自我们自己的 `account_events`,
|
||||
而事件是**上线后才开始记**的 —— 更早的兑换在列表里就是空的,
|
||||
看起来像"从没兑换过"(用户报的正是这个:账号 6966677706 明明有官方兑换记录,
|
||||
列表却显示未兑换)。
|
||||
|
||||
一键查询能查到官方兑换记录,但那份 JSON 有 1~2KB。
|
||||
账号列表是全站最热的接口之一,15000 个账号各带一份会把响应放大到几十 MB,
|
||||
所以**不能**直接把 `overview_snapshot` 返回给列表。
|
||||
|
||||
这里加一个只含列表所需两项的小字段:
|
||||
`{"owned": ["兔兔白日梦"], "exchanges": 2}`
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision: str = "20261004_0048"
|
||||
down_revision: str | None = "20261004_0047"
|
||||
branch_labels: str | None = None
|
||||
depends_on: str | None = None
|
||||
|
||||
|
||||
def _backfill_from_snapshot() -> None:
|
||||
"""从已有的 `overview_snapshot` 回填。
|
||||
|
||||
必须回填:加这个字段之前已经查过的账号,快照里**早就有**这两项信息,
|
||||
不回填的话列表会对它们显示「未查询」—— 明明查过,界面却在骗人。
|
||||
"""
|
||||
conn = op.get_bind()
|
||||
rows = conn.execute(
|
||||
sa.text(
|
||||
"SELECT id, overview_snapshot FROM accounts "
|
||||
"WHERE overview_snapshot IS NOT NULL"
|
||||
)
|
||||
).fetchall()
|
||||
updated = 0
|
||||
for account_id, snapshot in rows:
|
||||
data = snapshot
|
||||
if isinstance(data, (str, bytes)):
|
||||
try:
|
||||
data = json.loads(data)
|
||||
except ValueError:
|
||||
continue
|
||||
if not isinstance(data, dict):
|
||||
continue
|
||||
goods = data.get("high_value_goods")
|
||||
owned = [
|
||||
g.get("name")
|
||||
for g in (goods if isinstance(goods, list) else [])
|
||||
if isinstance(g, dict) and g.get("owned") and g.get("name")
|
||||
]
|
||||
# 只留「已兑换过哪些高价值套装」。
|
||||
# 兑换条数不再存这里 —— 列表改成从**官方事件**聚合(口径更准,
|
||||
# 而且不用维护两套计数)。
|
||||
owned_value = owned
|
||||
conn.execute(
|
||||
sa.text("UPDATE accounts SET high_value_owned = :owned WHERE id = :id"),
|
||||
{"owned": json.dumps(owned_value, ensure_ascii=False), "id": account_id},
|
||||
)
|
||||
updated += 1
|
||||
# ⚠️ **不要**在这里 `conn.commit()`。
|
||||
# 曾经加过,后果很隐蔽:DDL(ALTER TABLE)在 MySQL 上是自动提交的,
|
||||
# 但 commit 会打乱 alembic 自己的版本记账 —— 表现为
|
||||
# **列加上了、版本号却没更新**,下次启动升级时又去 ADD COLUMN,
|
||||
# 直接 `Duplicate column name` 把服务起不来(生产上就是启动即挂)。
|
||||
# 数据改动用 `op.get_bind().execute(...)` 写即可,提交由 alembic 负责
|
||||
# (仓库里 0042 的 S1 回填就是这么写的,一直正常)。
|
||||
if updated:
|
||||
print(f"[0048] 已从快照回填 {updated} 个账号的 high_value_owned")
|
||||
|
||||
|
||||
def _column_exists(name: str) -> bool:
|
||||
"""列是否已存在。
|
||||
|
||||
应用启动时会自动跑迁移,所以迁移必须**可安全重跑** ——
|
||||
万一出现「列已在、版本号没更新」的状态(本迁移就踩过),
|
||||
无脑 ADD COLUMN 会直接 `Duplicate column name` 让服务起不来。
|
||||
"""
|
||||
conn = op.get_bind()
|
||||
count = conn.execute(
|
||||
sa.text(
|
||||
"SELECT COUNT(*) FROM information_schema.columns "
|
||||
"WHERE table_schema = DATABASE() "
|
||||
"AND table_name = 'accounts' AND column_name = :name"
|
||||
),
|
||||
{"name": name},
|
||||
).scalar()
|
||||
return bool(count)
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
if not _column_exists("high_value_owned"):
|
||||
op.add_column(
|
||||
"accounts",
|
||||
sa.Column(
|
||||
"high_value_owned",
|
||||
sa.JSON(),
|
||||
nullable=True,
|
||||
comment="一键查询得到的「已兑换过的高价值套装名」列表(列表用,极小)",
|
||||
),
|
||||
)
|
||||
# 无论列是不是这一步加的,都跑回填(幂等:覆盖式写入)
|
||||
_backfill_from_snapshot()
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_column("accounts", "high_value_owned")
|
||||
@@ -0,0 +1,52 @@
|
||||
"""电竞手册到期时间:新增 `accounts.esports_expire_time`
|
||||
|
||||
与 `elite_expire_time` 对称。以前这个值只在 `_refresh_esports_handbook`
|
||||
的返回值里带着、没落库,所以界面上电竞手册只能显示「已开通」,
|
||||
看不到什么时候到期(用户反馈要"开通时间和过期时间")。
|
||||
|
||||
历史值拿不回来(官方兑换记录里**只有商品兑换、没有开通记录**),
|
||||
所以这一列从今往后才有数据 —— 已开通的账号会在下次刷新时补上。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision: str = "20261004_0049"
|
||||
down_revision: str | None = "20261004_0048"
|
||||
branch_labels: str | None = None
|
||||
depends_on: str | None = None
|
||||
|
||||
COLUMN = "esports_expire_time"
|
||||
|
||||
|
||||
def _column_exists(name: str) -> bool:
|
||||
"""可安全重跑(应用启动时会自动跑迁移)。"""
|
||||
conn = op.get_bind()
|
||||
count = conn.execute(
|
||||
sa.text(
|
||||
"SELECT COUNT(*) FROM information_schema.columns "
|
||||
"WHERE table_schema = DATABASE() "
|
||||
"AND table_name = 'accounts' AND column_name = :name"
|
||||
),
|
||||
{"name": name},
|
||||
).scalar()
|
||||
return bool(count)
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
if not _column_exists(COLUMN):
|
||||
op.add_column(
|
||||
"accounts",
|
||||
sa.Column(
|
||||
COLUMN,
|
||||
sa.Integer(),
|
||||
nullable=True,
|
||||
comment="电竞手册到期时间(Unix 秒,与 elite_expire_time 对称)",
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_column("accounts", COLUMN)
|
||||
@@ -104,6 +104,14 @@ class Account(Base):
|
||||
role_bind_status: Mapped[str] = mapped_column(
|
||||
String(16), default="unknown", server_default="unknown"
|
||||
)
|
||||
# 一键查询得到的「该账号已兑换过的高价值套装名」列表(如 ["套装-兔兔白日梦"])。
|
||||
#
|
||||
# 为什么单开一列、而不是让列表读 `overview_snapshot`:那份 JSON 有 1~2KB,
|
||||
# 账号列表是全站最热的接口之一,15000 个账号各带一份会把响应放大到几十 MB。
|
||||
# 这里只有几个短字符串。
|
||||
#
|
||||
# 兑换**条数**不存这里 —— 列表直接从官方事件聚合,不维护第二套计数。
|
||||
high_value_owned: Mapped[list | None] = mapped_column(JSON, nullable=True)
|
||||
# 最近一次「一键查询」的快照(结构化结果)。存在账号上而不是只留在任务里:
|
||||
# 任务会被保留策略清掉,而运营看的是"这个账号现在什么情况"。
|
||||
overview_snapshot: Mapped[dict | None] = mapped_column(JSON, nullable=True)
|
||||
@@ -135,6 +143,10 @@ class Account(Base):
|
||||
esports_change_role_wait_time: Mapped[int | None] = mapped_column(
|
||||
Integer, nullable=True
|
||||
)
|
||||
# 电竞手册**到期时间**(与 `elite_expire_time` 对称)。
|
||||
# 以前只在 `_refresh_esports_handbook` 的返回值里带着,没落库 ——
|
||||
# 于是界面上电竞只能显示"已开通"、看不到到期时间。
|
||||
esports_expire_time: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||
esports_can_change_time: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||
xpd_game_name: Mapped[str] = mapped_column(String(128), default="")
|
||||
xpd_openid: Mapped[str] = mapped_column(String(128), default="")
|
||||
|
||||
@@ -41,6 +41,7 @@ from ..services.account_events_service import (
|
||||
EVENT_RECHARGE,
|
||||
EVENT_REMARK_CHANGED,
|
||||
EVENT_TAG_CHANGED,
|
||||
OFFICIAL_SYNC_SOURCE,
|
||||
emit_bulk,
|
||||
)
|
||||
from ..services.account_lifecycle import (
|
||||
@@ -251,12 +252,20 @@ def list_accounts(
|
||||
.filter(
|
||||
AccountEvent.account_id.in_(ids),
|
||||
AccountEvent.event_type == EVENT_EXCHANGE,
|
||||
# 列表的「兑换记录」只反映**斗鱼官方记录**(口径权威且完整)。
|
||||
# 我们当场记的那些留给详情页时间线 —— 用户明确要求这么分。
|
||||
AccountEvent.source == OFFICIAL_SYNC_SOURCE,
|
||||
)
|
||||
.group_by(AccountEvent.account_id)
|
||||
.all()
|
||||
):
|
||||
exchange_stats[int(account_id)] = (int(count or 0), last_at, "")
|
||||
# ② 最近一次兑换的商品名(窗口函数取每个账号的最新一条)
|
||||
#
|
||||
# ⚠️ 按 **`occurred_at`** 排,不能按 `id`:
|
||||
# 一键查询会把斗鱼官方的**历史**兑换记录补成事件,它们的 `id` 是刚插进去的
|
||||
# (最新),但 `occurred_at` 是几年前的。按 id 排会把一条老兑换显示成"最近一次"
|
||||
# —— 实测就把 08-30 的兔兔白日梦错报成了 10-01(那是另一次兑换)。
|
||||
ranked = (
|
||||
db.query(
|
||||
AccountEvent.account_id.label("account_id"),
|
||||
@@ -264,13 +273,17 @@ def list_accounts(
|
||||
func.row_number()
|
||||
.over(
|
||||
partition_by=AccountEvent.account_id,
|
||||
order_by=AccountEvent.id.desc(),
|
||||
order_by=(
|
||||
AccountEvent.occurred_at.desc(),
|
||||
AccountEvent.id.desc(),
|
||||
),
|
||||
)
|
||||
.label("rn"),
|
||||
)
|
||||
.filter(
|
||||
AccountEvent.account_id.in_(ids),
|
||||
AccountEvent.event_type == EVENT_EXCHANGE,
|
||||
AccountEvent.source == OFFICIAL_SYNC_SOURCE,
|
||||
)
|
||||
.subquery()
|
||||
)
|
||||
@@ -306,6 +319,12 @@ 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),
|
||||
# 一键查询得到的「已兑换过的高价值套装」(不是整份快照 ——
|
||||
# 列表带不起 1~2KB/账号 的 JSON)。兑换条数不在这里:
|
||||
# 上面的 exchange_count 已经是**官方事件**聚合的结果。
|
||||
high_value_owned=acc.high_value_owned or [],
|
||||
# 「有没有查过」靠它判断 —— 否则"查过但没兑换"和"没查过"都是空,分不开
|
||||
overview_queried_at=acc.overview_queried_at,
|
||||
)
|
||||
# 只有管理员可看完整字段(密码、邮箱等)
|
||||
if can_include_sensitive:
|
||||
@@ -909,6 +928,63 @@ def batch_delete_accounts_selection(
|
||||
return {"message": f"已删除 {deleted} 个账号", "deleted": deleted, "success": True}
|
||||
|
||||
|
||||
@router.get("/{account_id}/exchange-records")
|
||||
def account_exchange_records(
|
||||
account_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current: User = Depends(get_current_user),
|
||||
):
|
||||
"""该账号在三个作用域下的**斗鱼官方兑换记录**(按作用域分组)。
|
||||
|
||||
列表的「兑换记录」格点开就用这个 —— **按需拉取**,不把记录塞进列表响应
|
||||
(15000 个账号各带一堆记录会把响应撑爆)。
|
||||
|
||||
数据源是 `source=official_sync` 的事件,也就是一键查询从官方补录的那些,
|
||||
它们带**真实兑换时间**。
|
||||
"""
|
||||
if (
|
||||
not _visible_accounts_query(db, current)
|
||||
.filter(Account.id == account_id)
|
||||
.first()
|
||||
):
|
||||
raise HTTPException(status_code=404, detail="账号不存在或无权查看")
|
||||
|
||||
rows = (
|
||||
db.query(AccountEvent)
|
||||
.filter(
|
||||
AccountEvent.account_id == account_id,
|
||||
AccountEvent.event_type == EVENT_EXCHANGE,
|
||||
AccountEvent.source == OFFICIAL_SYNC_SOURCE,
|
||||
)
|
||||
.order_by(AccountEvent.occurred_at.desc(), AccountEvent.id.desc())
|
||||
.all()
|
||||
)
|
||||
grouped: dict[str, list[dict[str, object]]] = {
|
||||
"elite": [],
|
||||
"esports": [],
|
||||
"peace": [],
|
||||
}
|
||||
for row in rows:
|
||||
detail = row.detail or {}
|
||||
scope = str(detail.get("scope") or "elite")
|
||||
grouped.setdefault(scope, []).append(
|
||||
{
|
||||
"title": row.title or "",
|
||||
"commodity_id": detail.get("commodity_id") or "",
|
||||
"commodity_name": detail.get("commodity_name") or "",
|
||||
"score": detail.get("score"),
|
||||
"show_name": detail.get("show_name") or "",
|
||||
"exchange_num": detail.get("exchange_num"),
|
||||
"occurred_at": row.occurred_at.isoformat() if row.occurred_at else None,
|
||||
}
|
||||
)
|
||||
return {
|
||||
"groups": grouped,
|
||||
"total": sum(len(v) for v in grouped.values()),
|
||||
"queried_at": None,
|
||||
}
|
||||
|
||||
|
||||
@router.get("/{account_id}/overview")
|
||||
def account_overview(
|
||||
account_id: int,
|
||||
@@ -1003,8 +1079,10 @@ def account_overview(
|
||||
"points_expire_at": acc.points_expire_at,
|
||||
"overview_snapshot": acc.overview_snapshot,
|
||||
"overview_queried_at": acc.overview_queried_at,
|
||||
"high_value_owned": acc.high_value_owned or [],
|
||||
"elite_opened": acc.elite_opened,
|
||||
"elite_expire_time": acc.elite_expire_time,
|
||||
"esports_expire_time": acc.esports_expire_time,
|
||||
"esports_points": acc.esports_points,
|
||||
"esports_bind_status": acc.esports_bind_status,
|
||||
"esports_game_name": acc.esports_game_name,
|
||||
|
||||
@@ -202,6 +202,12 @@ class AccountOut(BaseModel):
|
||||
exchange_count: int = 0
|
||||
last_exchange_at: datetime | None = None
|
||||
last_exchange_name: str = ""
|
||||
# 一键查询得到的(账号表里本来没有的)信息,供列表展示。
|
||||
# ⚠️ 必须在这里声明:Pydantic 默认 `extra='ignore'`,
|
||||
# 没声明的字段会被**静默丢掉** —— 路由明明返回了,接口却看不到。
|
||||
high_value_owned: list[str] = Field(default_factory=list)
|
||||
# 「有没有做过一键查询」靠它判断(列表不返回整份快照)
|
||||
overview_queried_at: datetime | None = None
|
||||
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
@@ -236,6 +242,12 @@ class AccountOut(BaseModel):
|
||||
"exchange_count": self.exchange_count,
|
||||
"last_exchange_at": _isoformat(self.last_exchange_at),
|
||||
"last_exchange_name": self.last_exchange_name,
|
||||
# ⚠️ 这个 `_serialize` 是**手写**的:字段只声明在模型上**不够**,
|
||||
# 不在这里列出来就会被丢掉。踩过 —— 路由返回的对象属性明明有值,
|
||||
# 前端拿到的 JSON 里却没有(属性访问能过、序列化后没有,
|
||||
# 只断言属性的测试因此假绿)。
|
||||
"high_value_owned": self.high_value_owned,
|
||||
"overview_queried_at": _isoformat(self.overview_queried_at),
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -184,3 +184,48 @@ def bind_payload(account: Account) -> dict[str, str]:
|
||||
payload[f"{prefix}_bind_status"] = state
|
||||
payload[f"{prefix}_bind_label"] = BIND_LABELS[state]
|
||||
return payload
|
||||
|
||||
|
||||
def derive_from_bind_info(info: dict | None) -> str | None:
|
||||
"""从斗鱼 `bind_info` 的返回推导绑定状态;**推导不出来时返回 None**。
|
||||
|
||||
返回 None 表示「这次查询没能得出可靠结论」—— 调用方应当**保持原值或写
|
||||
unknown**,绝不要把它当成 `unbound`。"没查到"和"没绑定"必须分开。
|
||||
|
||||
判定依据(字段含义见 `core/douyu/activity_client.py:_parse_bind_info`):
|
||||
|
||||
- `is_bound_role` 为真 → **bound**(已经绑了角色,这是"角色绑定"的正主)
|
||||
- 否则若 `is_bound_act` 为真 → **bound**(活动维度已绑;两个都真才更稳,
|
||||
但只给 act 时也算已绑,避免把"已绑但没回角色名"误报成未绑)
|
||||
- 两个标志都在、且都为假 → **unbound**(明确说了没绑)
|
||||
- 两个标志**都缺失**(接口没给 / 解析失败)→ **None**(推不出来,别猜)
|
||||
|
||||
⚠️ 这里刻意**不产出 pending**:`pending` 描述的是"正在绑定/待确认"这种
|
||||
**进行中的动作**(例如刚生成过绑定二维码),那是一次查询的**副作用**,
|
||||
不是查询能观测到的状态。硬用查询结果去推 pending 就是编造。
|
||||
"""
|
||||
if not isinstance(info, dict):
|
||||
return None
|
||||
|
||||
def flag(key: str) -> bool | None:
|
||||
value = info.get(key)
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, bool):
|
||||
return value
|
||||
text = str(value).strip().lower()
|
||||
if text in {"1", "true", "yes", "y"}:
|
||||
return True
|
||||
if text in {"0", "false", "no", "n", ""}:
|
||||
return False
|
||||
return None
|
||||
|
||||
bound_role = flag("is_bound_role")
|
||||
bound_act = flag("is_bound_act")
|
||||
if bound_role is True or bound_act is True:
|
||||
return BIND_BOUND
|
||||
if bound_role is False or bound_act is False:
|
||||
# 至少有一个标志明确为假 —— 接口给了结论,可以判"未绑定"
|
||||
return BIND_UNBOUND
|
||||
# 两个标志都缺失:接口没给结论,保持 unknown,别把"没查到"写成"没绑定"
|
||||
return None
|
||||
|
||||
@@ -48,6 +48,9 @@ EVENT_RELOGIN_OK = "relogin_ok" # 自动重登成功
|
||||
EVENT_RELOGIN_FAILED = "relogin_failed" # 自动重登失败(转人工/退避)
|
||||
EVENT_BIND_OK = "bind_ok" # 绑定/换绑
|
||||
EVENT_RECHARGE = "recharge" # 充值到账
|
||||
#: 事件来源:从斗鱼**官方兑换记录**补录(区别于任务执行时当场记的)
|
||||
OFFICIAL_SYNC_SOURCE = "official_sync"
|
||||
|
||||
EVENT_EXCHANGE = "exchange" # 兑换(含消耗积分)
|
||||
EVENT_POINTS_CREDIT = "points_credit" # 积分到账(含到期时间)
|
||||
EVENT_POINTS_EXPIRE = "points_expire" # 积分到期(资产减少)
|
||||
|
||||
@@ -44,7 +44,9 @@ from .account_events_service import (
|
||||
EVENT_POINTS_CREDIT,
|
||||
EVENT_POINTS_EXPIRE,
|
||||
EVENT_RECHARGE,
|
||||
OFFICIAL_SYNC_SOURCE,
|
||||
emit,
|
||||
to_naive_utc,
|
||||
)
|
||||
|
||||
|
||||
@@ -331,3 +333,66 @@ def record_bind(
|
||||
subject_key=role_name or "",
|
||||
source_ref=task_ref(task_id),
|
||||
)
|
||||
|
||||
|
||||
def record_official_exchange(
|
||||
db: Session,
|
||||
account: Account,
|
||||
*,
|
||||
commodity_id: str,
|
||||
commodity_name: str,
|
||||
score: int | None,
|
||||
occurred_at: datetime | None,
|
||||
show_name: str = "",
|
||||
exchange_num: int | None = None,
|
||||
scope: str = "elite",
|
||||
) -> bool:
|
||||
"""把斗鱼官方兑换记录写成账号事件。
|
||||
|
||||
## 为什么要写进事件流
|
||||
|
||||
列表的「兑换记录」列一直来自我们自己的 `account_events`,而事件是**上线后**
|
||||
才开始记的 —— 上线前的兑换在界面上就是空白,看着像"从没兑换过"
|
||||
(用户报过:账号明明有官方兑换记录,列表却显示「未兑换」)。
|
||||
|
||||
官方记录**带真实兑换时间**(`time` 字段),所以可以直接补成正常的历史事件,
|
||||
时间线因此变完整(这就是"账号全生命周期"该有的样子),
|
||||
列表的聚合也随之自动准确 —— 不需要再单独维护一套"官方条数"的旁路。
|
||||
|
||||
## 幂等
|
||||
|
||||
`source_ref` 用 `官方:账号:商品:时刻`,同一条记录查多少次都只落一条。
|
||||
这也是必须的:一键查询会被反复执行。
|
||||
"""
|
||||
if not commodity_id:
|
||||
return False
|
||||
return emit(
|
||||
db,
|
||||
account_id=account.id,
|
||||
event_type=EVENT_EXCHANGE,
|
||||
title=f"兑换 {commodity_name}" if commodity_name else "兑换",
|
||||
category=CATEGORY_BUSINESS,
|
||||
occurred_at=occurred_at,
|
||||
amount=-int(score) if score else None,
|
||||
detail={
|
||||
"commodity_id": commodity_id,
|
||||
"commodity_name": commodity_name,
|
||||
"score": score,
|
||||
"exchange_num": exchange_num,
|
||||
"show_name": show_name,
|
||||
# 标明来源:这条是**从官方记录补录**的,不是我们亲眼看着兑换的
|
||||
"source": OFFICIAL_SYNC_SOURCE,
|
||||
# 哪个作用域的官方记录(精英宝典 / 电竞手册 / 和平小店)
|
||||
"scope": scope,
|
||||
},
|
||||
source=OFFICIAL_SYNC_SOURCE,
|
||||
subject_type="goods",
|
||||
source_ref=(
|
||||
f"official_exchange:{scope}:{account.id}:{commodity_id}:{_stamp(occurred_at)}"
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _stamp(value: datetime | None) -> str:
|
||||
"""幂等键里的时间部分;没有时间就用固定标记(同一商品仍只落一条)。"""
|
||||
return to_naive_utc(value).strftime("%Y%m%d%H%M%S") if value else "unknown"
|
||||
|
||||
@@ -203,6 +203,16 @@ class ManualMixin:
|
||||
manual_type = self._to_int(result.get("manual_type"))
|
||||
manual_score = self._to_int(result.get("manual_score"))
|
||||
account.esports_points = manual_score
|
||||
# 到期时间也落库 —— 否则界面只能显示"已开通",看不到什么时候到期
|
||||
expire_raw = result.get("expire_time")
|
||||
expire_int = (
|
||||
int(expire_raw) if str(expire_raw or "").strip().isdigit() else None
|
||||
)
|
||||
# ⚠️ 斗鱼用 0 表示「没有到期时间」。直接存 0 的话界面会显示 1970/1/1
|
||||
# (这个坑在积分到期上踩过一次,这里别再踩)。
|
||||
account.esports_expire_time = (
|
||||
expire_int if expire_int and expire_int > 0 else None
|
||||
)
|
||||
account.updated_at = datetime.now(UTC)
|
||||
return {
|
||||
"esports_manual_type": manual_type,
|
||||
|
||||
@@ -33,6 +33,8 @@ from sqlalchemy.orm import Session
|
||||
from core.douyu import DouyuActivityClient
|
||||
|
||||
from ..models import Account, DouyuTask
|
||||
from .account_binding import derive_from_bind_info, set_bind_status
|
||||
from .business_events import record_official_exchange
|
||||
from .douyu_runner_donate import _parse_expire_at, _points_expire_at
|
||||
|
||||
#: 默认关注的高价值商品。按**商品名包含**匹配 —— 官方列表里的名字带前缀
|
||||
@@ -138,6 +140,52 @@ def extract_high_value_goods(
|
||||
return out
|
||||
|
||||
|
||||
def _group_by_scope(
|
||||
pairs: list[tuple[str, dict[str, Any]]],
|
||||
) -> dict[str, list[dict[str, Any]]]:
|
||||
"""把 (作用域, 记录) 扁平列表按作用域分组。"""
|
||||
grouped: dict[str, list[dict[str, Any]]] = {}
|
||||
for scope, rec in pairs:
|
||||
grouped.setdefault(scope, []).append(rec)
|
||||
return grouped
|
||||
|
||||
|
||||
def _record_official_exchanges(
|
||||
db: Session, account: Account, pairs: list[tuple[str, dict[str, Any]]]
|
||||
) -> int:
|
||||
"""把官方兑换记录补成账号事件,返回**新写入**的条数。
|
||||
|
||||
幂等由 `record_official_exchange` 的 `source_ref` 保证(含作用域),
|
||||
所以一键查询反复执行不会重复落事件。
|
||||
"""
|
||||
added = 0
|
||||
for scope, rec in pairs:
|
||||
if not isinstance(rec, dict):
|
||||
continue
|
||||
when = _ts(rec.get("time"))
|
||||
occurred = _parse_expire_at(when) if when is not None else None
|
||||
score_raw = rec.get("score")
|
||||
try:
|
||||
score = int(str(score_raw)) if score_raw not in (None, "") else None
|
||||
except (TypeError, ValueError):
|
||||
score = None
|
||||
if record_official_exchange(
|
||||
db,
|
||||
account,
|
||||
commodity_id=str(rec.get("commodityId") or rec.get("commodity_id") or ""),
|
||||
commodity_name=str(
|
||||
rec.get("commodityName") or rec.get("commodity_name") or ""
|
||||
),
|
||||
score=score,
|
||||
occurred_at=occurred,
|
||||
show_name=str(rec.get("showName") or rec.get("show_name") or ""),
|
||||
exchange_num=rec.get("exchangeNum") or rec.get("count"),
|
||||
scope=scope,
|
||||
):
|
||||
added += 1
|
||||
return added
|
||||
|
||||
|
||||
def _goods_config(config: dict) -> list[str]:
|
||||
"""高价值商品名单:优先用配置,非法/为空则回落默认。"""
|
||||
raw = config.get("high_value_goods")
|
||||
@@ -205,6 +253,82 @@ class OverviewMixin:
|
||||
self, client: DouyuActivityClient, account: Account, *, manual_id: str
|
||||
) -> dict: ...
|
||||
|
||||
# ---- 三个作用域的官方兑换记录抓取 ----
|
||||
#
|
||||
# 精英宝典 / 电竞手册 共用 `exchange_records`(只有 manual_id 不同);
|
||||
# 和平小店是另一套(道聚城短时授权 + 购买记录)。
|
||||
|
||||
@staticmethod
|
||||
def _scope_configured(
|
||||
scope: str, manual_id: str, esports_manual_id: str, config: dict
|
||||
) -> bool:
|
||||
if scope == "elite":
|
||||
return bool(manual_id)
|
||||
if scope == "esports":
|
||||
return bool(esports_manual_id)
|
||||
return all(
|
||||
str(config.get(k) or "").strip()
|
||||
for k in ("xpd_act_alias", "xpd_rid", "xpd_act_id")
|
||||
)
|
||||
|
||||
def _fetch_bind_info(
|
||||
self, client: DouyuActivityClient, scope: str, alias: str
|
||||
) -> dict[str, Any]:
|
||||
"""按作用域查绑定信息(三个接口不同,收敛在一处)。"""
|
||||
if scope == "elite":
|
||||
return client.bind_info(alias)
|
||||
if scope == "esports":
|
||||
return client.esports_bind_info(alias)
|
||||
return client.xpd_bind_info(act_alias=alias)
|
||||
|
||||
def _fetch_elite_records(
|
||||
self,
|
||||
client: DouyuActivityClient,
|
||||
config: dict,
|
||||
manual_id: str,
|
||||
esports_manual_id: str,
|
||||
) -> list[dict[str, Any]]:
|
||||
return (
|
||||
client.exchange_records(
|
||||
manual_id=manual_id, limit=EXCHANGE_RECORD_LIMIT
|
||||
).get("records")
|
||||
or []
|
||||
)
|
||||
|
||||
def _fetch_esports_records(
|
||||
self,
|
||||
client: DouyuActivityClient,
|
||||
config: dict,
|
||||
manual_id: str,
|
||||
esports_manual_id: str,
|
||||
) -> list[dict[str, Any]]:
|
||||
return (
|
||||
client.exchange_records(
|
||||
manual_id=esports_manual_id, limit=EXCHANGE_RECORD_LIMIT
|
||||
).get("records")
|
||||
or []
|
||||
)
|
||||
|
||||
def _fetch_xpd_records(
|
||||
self,
|
||||
client: DouyuActivityClient,
|
||||
config: dict,
|
||||
manual_id: str,
|
||||
esports_manual_id: str,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""和平小店:先要一次性短时授权,再查购买记录。"""
|
||||
embed = client.xpd_embed_query(
|
||||
act_alias=str(config["xpd_act_alias"]),
|
||||
rid=str(config["xpd_rid"]),
|
||||
)
|
||||
return (
|
||||
client.xpd_purchase_records(
|
||||
embed_query=embed["query"],
|
||||
act_id=str(config["xpd_act_id"]),
|
||||
).get("records")
|
||||
or []
|
||||
)
|
||||
|
||||
def _execute_query_account_overview(
|
||||
self, db: Session, task: DouyuTask, account: Account, cookie: str, config: dict
|
||||
):
|
||||
@@ -224,11 +348,12 @@ class OverviewMixin:
|
||||
"elite": {},
|
||||
"esports": {},
|
||||
"high_value_goods": [],
|
||||
"exchange_records": [],
|
||||
"exchange_records": {},
|
||||
"errors": {},
|
||||
}
|
||||
errors: dict[str, str] = overview["errors"]
|
||||
all_records: list[dict[str, Any]] = []
|
||||
# (作用域, 官方记录) 扁平列表,便于补事件
|
||||
all_records: list[tuple[str, dict[str, Any]]] = []
|
||||
pending_goods: list[dict[str, Any]] = []
|
||||
|
||||
# ---- 鱼翅 + 钱包兑换余额 ----
|
||||
@@ -308,29 +433,88 @@ class OverviewMixin:
|
||||
# 所以这里放在兑换记录**之后**才能判定 —— 见下面的顺序。
|
||||
pending_goods = goods_items
|
||||
|
||||
# ---- 官方兑换记录 ----
|
||||
if not manual_id:
|
||||
errors["exchange_records"] = "未配置精英宝典 manualID"
|
||||
else:
|
||||
# ---- 角色绑定状态(三个作用域都查)----
|
||||
#
|
||||
# 这三个值以前**从来没人查过** —— 只是 S6 迁移时从旧的垃圾场列
|
||||
# `bind_status` 能推的推、推不出的留 `unknown`,于是界面上 97% 显示"未知"。
|
||||
# 实测校准:开发库 4 个账号里 3 个其实**已绑定**(`is_bound_role=True` 且有角色名),
|
||||
# 全被 unknown 盖住了。
|
||||
overview["bind"] = {}
|
||||
for scope, label, alias_key in (
|
||||
("elite", "精英宝典", "bind_act_alias"),
|
||||
("esports", "电竞手册", "esports_act_alias"),
|
||||
("peace", "和平小店", "xpd_act_alias"),
|
||||
):
|
||||
alias = str(config.get(alias_key) or "").strip()
|
||||
if not alias:
|
||||
errors[f"bind_{scope}"] = f"未配置{label}活动别名"
|
||||
continue
|
||||
try:
|
||||
records = client.exchange_records(
|
||||
manual_id=manual_id, limit=EXCHANGE_RECORD_LIMIT
|
||||
)
|
||||
rows = records.get("records") or []
|
||||
all_records = rows
|
||||
overview["exchange_records"] = rows[:EXCHANGE_RECORD_LIMIT]
|
||||
overview["exchange_record_count"] = len(rows)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
errors["exchange_records"] = _err(exc)
|
||||
all_records = []
|
||||
info = self._fetch_bind_info(client, scope, alias)
|
||||
derived = derive_from_bind_info(info)
|
||||
# 把**明细**也带上:运营要看的是"绑的哪个角色、哪个区服、
|
||||
# 什么时候能换绑",不是一个"已绑定"就完事。
|
||||
overview["bind"][scope] = {
|
||||
"derived": derived,
|
||||
"role_name": str(info.get("role_name") or info.get("role") or ""),
|
||||
"area_name": str(info.get("area_name") or ""),
|
||||
"plat_name": str(info.get("plat_name") or ""),
|
||||
"nickname": str(info.get("nickname") or ""),
|
||||
"change_role_wait_time": _ts(info.get("change_role_wait_time")),
|
||||
"can_change_time": _ts(info.get("can_change_time")),
|
||||
}
|
||||
if derived is not None:
|
||||
# 唯一写入者;推不出来(None)时**不动原值** —— 宁可留 unknown,
|
||||
# 也不要把"没查到"写成"没绑定"
|
||||
set_bind_status(account, scope, derived)
|
||||
except Exception as exc: # noqa: BLE001 外部接口边界需要宽泛兜底
|
||||
errors[f"bind_{scope}"] = _err(exc)
|
||||
|
||||
# ---- 官方兑换记录(**三个作用域都拉**)----
|
||||
#
|
||||
# 精英宝典 / 电竞手册 用的是同一个接口,只是 manual_id 不同;
|
||||
# 和平小店是另一套(先拿道聚城短时授权 query,再查购买记录)。
|
||||
# 任一作用域失败只记进 errors,不影响其余两个。
|
||||
for scope, label, fetcher in (
|
||||
("elite", "精英宝典", self._fetch_elite_records),
|
||||
("esports", "电竞手册", self._fetch_esports_records),
|
||||
("peace", "和平小店", self._fetch_xpd_records),
|
||||
):
|
||||
key = f"exchange_records_{scope}"
|
||||
if not self._scope_configured(scope, manual_id, esports_manual_id, config):
|
||||
errors[key] = f"未配置{label}活动参数,跳过"
|
||||
continue
|
||||
try:
|
||||
rows = fetcher(client, config, manual_id, esports_manual_id)
|
||||
except Exception as exc: # noqa: BLE001 外部接口边界需要宽泛兜底
|
||||
errors[key] = _err(exc)
|
||||
continue
|
||||
overview["exchange_records"][scope] = rows[:EXCHANGE_RECORD_LIMIT]
|
||||
all_records.extend((scope, r) for r in rows)
|
||||
overview[f"exchange_record_count_{scope}"] = len(rows)
|
||||
|
||||
overview["exchange_record_count"] = len(all_records)
|
||||
# 把官方记录**补成账号事件**(带真实兑换时间、按作用域去重)。
|
||||
overview["exchange_events_added"] = _record_official_exchanges(
|
||||
db, account, all_records
|
||||
)
|
||||
overview["exchange_records"] = {
|
||||
scope: rows[:EXCHANGE_RECORD_LIMIT]
|
||||
for scope, rows in _group_by_scope(all_records).items()
|
||||
}
|
||||
|
||||
# ---- 🎯 高价值套装判定(依赖兑换记录,必须放在它之后)----
|
||||
if not manual_id:
|
||||
errors["high_value_goods"] = "未配置精英宝典 manualID"
|
||||
else:
|
||||
try:
|
||||
# ⚠️ 必须传**摊平后的记录**:`all_records` 是 (作用域, 记录) 元组列表,
|
||||
# 直接传进去会被 `isinstance(r, dict)` 全过滤掉 —— 表现为
|
||||
# "所有高价值套装都判定为未获得"(踩过)。
|
||||
overview["high_value_goods"] = extract_high_value_goods(
|
||||
pending_goods, _goods_config(config), all_records
|
||||
pending_goods,
|
||||
_goods_config(config),
|
||||
[rec for _scope, rec in all_records],
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
errors["high_value_goods"] = _err(exc)
|
||||
@@ -354,6 +538,10 @@ class OverviewMixin:
|
||||
# 应该在账号管理里看,不该依赖一条日志的寿命。
|
||||
account.overview_snapshot = overview
|
||||
account.overview_queried_at = datetime.now(UTC)
|
||||
# 再落「已兑换过的高价值套装名」给列表用(列表不能带整份快照)
|
||||
account.high_value_owned = [
|
||||
g["name"] for g in overview.get("high_value_goods", []) if g.get("owned")
|
||||
]
|
||||
|
||||
logger.info(f"[douyu] 一键查询账号 {account.id}: {message}")
|
||||
self._mark_task(db, task, "success", message, overview)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import api from './client';
|
||||
import type {
|
||||
AccountExchangeRecords,
|
||||
AccountEventPage,
|
||||
AccountItem,
|
||||
AccountBulkSelection,
|
||||
@@ -50,6 +51,9 @@ export const accountApi = {
|
||||
api.put<MessageResponse, MessageResponse>(`/accounts/${id}/automation`, { auto_managed }),
|
||||
// 详情页:状态卡 + 统计
|
||||
overview: (id: number) => api.get<AccountOverview, AccountOverview>(`/accounts/${id}/overview`),
|
||||
// 三个作用域的**官方**兑换记录(点列表那一格时按需拉取,不进列表响应)
|
||||
exchangeRecords: (id: number) =>
|
||||
api.get<AccountExchangeRecords, AccountExchangeRecords>(`/accounts/${id}/exchange-records`),
|
||||
// 时间线(倒序分页),event_type 为空表示全部
|
||||
events: (
|
||||
id: number,
|
||||
|
||||
@@ -169,6 +169,8 @@ export interface AccountOverview {
|
||||
esports_bind_label: string;
|
||||
/** 电竞手册是否已开通(与 elite_opened 对称,S6 从垃圾场列里救出来的) */
|
||||
esports_opened: boolean | null;
|
||||
/** 电竞手册到期时间(Unix 秒,与 elite_expire_time 对称) */
|
||||
esports_expire_time: number | null;
|
||||
xpd_bind_status: BindStatus;
|
||||
xpd_bind_label: string;
|
||||
esports_game_name: string;
|
||||
@@ -176,6 +178,8 @@ export interface AccountOverview {
|
||||
stats: AccountOverviewStats;
|
||||
/** 最近一次「一键查询」的快照(结构与后端 query_account_overview 的 result 一致) */
|
||||
overview_snapshot: import('../pages/douyu-tasks/AccountOverviewPanel').AccountOverviewResult | null;
|
||||
/** 一键查询得到的已兑换高价值套装 */
|
||||
high_value_owned: string[];
|
||||
overview_queried_at: string | null;
|
||||
/** 开通时间来自事件表(上线后才开始记录,更早的不显示) */
|
||||
opened_at: { elite: string | null; esports: string | null };
|
||||
@@ -278,6 +282,10 @@ export interface AccountItem {
|
||||
exchange_count: number;
|
||||
last_exchange_at: string | null;
|
||||
last_exchange_name: string;
|
||||
/** 一键查询得到的「已兑换过的高价值套装」(账号表里没有,来自官方兑换记录) */
|
||||
high_value_owned: string[];
|
||||
/** 最近一次一键查询时间 —— 用来区分「查过但没兑换」和「还没查过」 */
|
||||
overview_queried_at: string | null;
|
||||
}
|
||||
|
||||
export interface AssignmentsSummary {
|
||||
@@ -1094,3 +1102,20 @@ export interface AutomationManualQueue {
|
||||
total: number;
|
||||
groups: AutomationManualGroup[];
|
||||
}
|
||||
|
||||
/** 官方兑换记录(按作用域分组) */
|
||||
export interface AccountExchangeRecord {
|
||||
title: string;
|
||||
commodity_id: string;
|
||||
commodity_name: string;
|
||||
score: number | string | null;
|
||||
show_name: string;
|
||||
exchange_num: number | null;
|
||||
occurred_at: string | null;
|
||||
}
|
||||
|
||||
export interface AccountExchangeRecords {
|
||||
groups: Record<string, AccountExchangeRecord[]>;
|
||||
total: number;
|
||||
queried_at: string | null;
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import {
|
||||
Button, Card, Descriptions, Empty, Input, Popconfirm, Select, Space, Spin, Statistic, Table, Tag, Tooltip, Typography,
|
||||
Button, Card, Col, Descriptions, Divider, Empty, Input, Popconfirm, Row, Select, Space, Spin, Statistic, Table, Tag, Tooltip, Typography,
|
||||
} from 'antd';
|
||||
import type { TableProps } from 'antd';
|
||||
import {
|
||||
@@ -11,7 +11,7 @@ import { accountApi, douyuApi, userApi, type AccountEventItem, type AccountOverv
|
||||
import AccountOverviewPanel from './douyu-tasks/AccountOverviewPanel';
|
||||
import { getErrorMessage } from '../utils/error';
|
||||
import { message } from '../utils/antdMessage';
|
||||
import { formatTime } from '../utils/time';
|
||||
import { formatTime, formatUnixSeconds } from '../utils/time';
|
||||
|
||||
const { Text, Title } = Typography;
|
||||
|
||||
@@ -56,19 +56,6 @@ const STATUS_TONES: Record<string, string> = {
|
||||
archived: 'default',
|
||||
};
|
||||
|
||||
/** 单个作用域的绑定小标签:精/电/店。 */
|
||||
function BindChip({ scope, status }: { scope: string; status?: string }) {
|
||||
const tone = status === 'bound' ? 'green'
|
||||
: status === 'pending' ? 'orange'
|
||||
: status === 'unbound' ? 'red'
|
||||
: 'default';
|
||||
const mark = status === 'bound' ? '✓'
|
||||
: status === 'pending' ? '…'
|
||||
: status === 'unbound' ? '✗'
|
||||
: '?';
|
||||
return <Tag color={tone} style={{ marginInlineEnd: 0 }}>{scope}{mark}</Tag>;
|
||||
}
|
||||
|
||||
/** 绑定状态 → 展示色(与后端 account_binding 的四个枚举对应)。 */
|
||||
const BIND_TONES: Record<string, string> = {
|
||||
bound: 'green',
|
||||
@@ -369,136 +356,19 @@ export default function AccountDetailPage() {
|
||||
</Space>
|
||||
|
||||
<Spin spinning={loading}>
|
||||
{/* ── 生命周期状态卡 ────────────────────────────────
|
||||
这一屏要回答客服最关心的三个问题:
|
||||
1. 这账号现在能不能用?(状态 + CK)
|
||||
2. 要不要我处理?(原因 + 变更时间 + 自动化是否在管)
|
||||
3. 账上还有多少?(积分 / 鱼翅 / 兑换余额) */}
|
||||
{/* ── 卡片 1:账号信息 ──────────────────────────────
|
||||
身份 + 状态 + 归属,一张表看完。**不重复展示资产**(见卡片 2)。 */}
|
||||
<Card
|
||||
size="small"
|
||||
style={{ marginBottom: 12 }}
|
||||
title={
|
||||
<Space>
|
||||
<ThunderboltOutlined />
|
||||
<span>高价值套装与兑换记录(一键查询)</span>
|
||||
</Space>
|
||||
}
|
||||
extra={
|
||||
<Button
|
||||
type="primary"
|
||||
icon={<ThunderboltOutlined />}
|
||||
loading={ovLoading}
|
||||
onClick={runOverview}
|
||||
>
|
||||
查询该账号全部信息
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
{ovError && (
|
||||
<Text type="danger" style={{ display: 'block', marginBottom: 8 }}>
|
||||
{ovError}
|
||||
</Text>
|
||||
)}
|
||||
{overview?.overview_snapshot ? (
|
||||
<AccountOverviewPanel
|
||||
result={overview.overview_snapshot}
|
||||
queriedAt={overview.overview_queried_at}
|
||||
/>
|
||||
) : (
|
||||
<Text type="secondary">
|
||||
实时向斗鱼查一次这个账号:鱼翅 / 积分 / 开通状态会**就地刷新到下面的账号信息**,
|
||||
这里只单独展示账号表里没有的两项 —— 「兔兔白日梦」「狂战萌兔」是否已获得,
|
||||
以及官方兑换记录。
|
||||
</Text>
|
||||
)}
|
||||
</Card>
|
||||
<Card size="small" style={{ marginBottom: 12 }}>
|
||||
<Space size={24} wrap align="start">
|
||||
<Space direction="vertical" size={4}>
|
||||
<Text type="secondary">生命周期状态</Text>
|
||||
<Space size={6}>
|
||||
<Tag color={STATUS_TONES[status] ?? 'default'} style={{ fontSize: 14, padding: '2px 8px' }}>
|
||||
{overview?.status_label || '—'}
|
||||
</Tag>
|
||||
{overview?.auto_managed === false && <Tag color="orange">不参与自动化</Tag>}
|
||||
</Space>
|
||||
<Space wrap>
|
||||
<Title level={5} style={{ margin: 0 }}>
|
||||
{overview?.nickname || overview?.username || '—'}
|
||||
</Title>
|
||||
<Text type="secondary" style={{ fontSize: 12 }}>
|
||||
{formatTime(overview?.status_changed_at)}
|
||||
{overview?.status_reason ? `(${overview.status_reason})` : ''}
|
||||
#{overview?.id ?? '-'} · {overview?.username || '—'}
|
||||
</Text>
|
||||
</Space>
|
||||
|
||||
<Space direction="vertical" size={4}>
|
||||
<Text type="secondary">CK</Text>
|
||||
{overview?.has_cookie === false
|
||||
? <Tag>无 CK</Tag>
|
||||
: <Tag color={overview?.ck_check_status === 'invalid' ? 'red' : 'green'}>
|
||||
{overview?.ck_check_status === 'invalid' ? '已失效'
|
||||
: overview?.ck_check_status === 'valid' ? '正常' : '未检测'}
|
||||
</Tag>}
|
||||
<Text type="secondary" style={{ fontSize: 12 }}>
|
||||
最近检测 {formatTime(overview?.stats?.last_ck_check_at)}
|
||||
</Text>
|
||||
</Space>
|
||||
|
||||
<Space direction="vertical" size={4}>
|
||||
<Text type="secondary">角色绑定</Text>
|
||||
<Space size={2} wrap>
|
||||
<BindChip scope="精" status={overview?.role_bind_status} />
|
||||
<BindChip scope="电" status={overview?.esports_bind_status} />
|
||||
<BindChip scope="店" status={overview?.xpd_bind_status} />
|
||||
</Space>
|
||||
</Space>
|
||||
|
||||
<Statistic title="积分" value={overview?.points ?? '-'} />
|
||||
<Statistic title="鱼翅" value={overview?.gold_balance ?? '-'} />
|
||||
<Statistic title="兑换余额" value={overview?.exchange_balance ?? '-'} />
|
||||
|
||||
{/* 人工操作:与工具栏的生命周期动作分开 —— 那些是「账号可用性」,
|
||||
这些是「归属与标注」。 */}
|
||||
<Space direction="vertical" size={4}>
|
||||
<Text type="secondary">归属与标注</Text>
|
||||
<Space size={6} wrap>
|
||||
<Select
|
||||
size="small"
|
||||
style={{ width: 140 }}
|
||||
placeholder="未分配"
|
||||
value={overview?.assigned_to ?? undefined}
|
||||
allowClear
|
||||
onChange={(val) => void handleAssign(val ?? null)}
|
||||
options={supportUsers.map((u) => ({ value: u.id, label: u.username }))}
|
||||
/>
|
||||
{tagEditing ? (
|
||||
<Space.Compact>
|
||||
<Input
|
||||
size="small"
|
||||
style={{ width: 120 }}
|
||||
maxLength={32}
|
||||
value={tagDraft}
|
||||
onChange={(e) => setTagDraft(e.target.value)}
|
||||
onPressEnter={() => void handleSaveTag()}
|
||||
/>
|
||||
<Button size="small" type="primary" onClick={() => void handleSaveTag()}>保存</Button>
|
||||
<Button size="small" onClick={() => setTagEditing(false)}>取消</Button>
|
||||
</Space.Compact>
|
||||
) : (
|
||||
<Button
|
||||
size="small"
|
||||
icon={<EditOutlined />}
|
||||
onClick={() => { setTagDraft(overview?.tag || ''); setTagEditing(true); }}
|
||||
>
|
||||
{overview?.tag || '设置标签'}
|
||||
</Button>
|
||||
)}
|
||||
</Space>
|
||||
</Space>
|
||||
</Space>
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
title={
|
||||
<Space>
|
||||
<Title level={5} style={{ margin: 0 }}>{overview?.username || '—'}</Title>
|
||||
<Tag color={STATUS_TONES[status] ?? 'default'}>
|
||||
{overview?.status_label || '—'}
|
||||
</Tag>
|
||||
@@ -506,29 +376,135 @@ export default function AccountDetailPage() {
|
||||
{overview?.auto_managed === false && <Tag color="orange">不参与自动化</Tag>}
|
||||
</Space>
|
||||
}
|
||||
style={{ marginBottom: 12 }}
|
||||
>
|
||||
<Descriptions column={3} size="small" bordered>
|
||||
<Descriptions.Item label="斗鱼昵称">{overview?.nickname || '-'}</Descriptions.Item>
|
||||
<Descriptions.Item label="斗鱼 UID">{overview?.uid || '-'}</Descriptions.Item>
|
||||
<Descriptions.Item label="导入时间">{formatTime(overview?.created_at)}</Descriptions.Item>
|
||||
<Descriptions.Item label="游戏角色">
|
||||
{overview?.game_name || '-'}
|
||||
{overview?.game_channel ? <Text type="secondary"> ({overview.game_channel})</Text> : null}
|
||||
{overview?.game_channel ? (
|
||||
<Text type="secondary">({overview.game_channel})</Text>
|
||||
) : null}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="导入时间">
|
||||
{formatTime(overview?.created_at)}
|
||||
</Descriptions.Item>
|
||||
|
||||
<Descriptions.Item label="生命周期">
|
||||
<Space direction="vertical" size={0}>
|
||||
<Text>
|
||||
{formatTime(overview?.status_changed_at)}
|
||||
{overview?.status_reason ? (
|
||||
<Text type="secondary">({overview.status_reason})</Text>
|
||||
) : null}
|
||||
</Text>
|
||||
</Space>
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="CK">
|
||||
<Space size={6} wrap>
|
||||
{overview?.has_cookie === false ? (
|
||||
<Tag>无 CK</Tag>
|
||||
) : (
|
||||
<Tag color={overview?.ck_check_status === 'invalid' ? 'red' : 'green'}>
|
||||
{overview?.ck_check_status === 'invalid'
|
||||
? '已失效'
|
||||
: overview?.ck_check_status === 'valid'
|
||||
? '正常'
|
||||
: '未检测'}
|
||||
</Tag>
|
||||
)}
|
||||
<Text type="secondary" style={{ fontSize: 12 }}>
|
||||
{formatTime(stats?.last_ck_check_at)}
|
||||
</Text>
|
||||
</Space>
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="角色绑定">
|
||||
{/* 三列各管一个作用域,取值 unknown/unbound/pending/bound */}
|
||||
<Space size={6} wrap>
|
||||
<Tag color={BIND_TONES[overview?.role_bind_status ?? 'unknown']}>
|
||||
精英:{overview?.role_bind_label || '未知'}
|
||||
</Tag>
|
||||
<Tag color={BIND_TONES[overview?.esports_bind_status ?? 'unknown']}>
|
||||
电竞:{overview?.esports_bind_label || '未知'}
|
||||
</Tag>
|
||||
<Tag color={BIND_TONES[overview?.xpd_bind_status ?? 'unknown']}>
|
||||
小店:{overview?.xpd_bind_label || '未知'}
|
||||
</Tag>
|
||||
</Space>
|
||||
{/* 三个作用域各一列,取值 unknown/unbound/pending/bound。
|
||||
全 unknown 时把「没查过」和「查了推不出」分开说 ——
|
||||
混成一个"未知"会让人不知道下一步该干什么。 */}
|
||||
{[
|
||||
overview?.role_bind_status,
|
||||
overview?.esports_bind_status,
|
||||
overview?.xpd_bind_status,
|
||||
].every((s) => !s || s === 'unknown') ? (
|
||||
<Text type="secondary">
|
||||
{overview?.overview_queried_at ? (
|
||||
<>
|
||||
未能判定
|
||||
<br />
|
||||
<Text type="secondary" style={{ fontSize: 12 }}>
|
||||
已查询过,但斗鱼这次没给出绑定结论
|
||||
</Text>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
未查询
|
||||
<br />
|
||||
<Text type="secondary" style={{ fontSize: 12 }}>
|
||||
点上方「一键查询」即可查出来
|
||||
</Text>
|
||||
</>
|
||||
)}
|
||||
</Text>
|
||||
) : (
|
||||
<Space size={4} wrap>
|
||||
<Tag color={BIND_TONES[overview?.role_bind_status ?? 'unknown']}>
|
||||
精英:{overview?.role_bind_label || '未知'}
|
||||
</Tag>
|
||||
<Tag color={BIND_TONES[overview?.esports_bind_status ?? 'unknown']}>
|
||||
电竞:{overview?.esports_bind_label || '未知'}
|
||||
</Tag>
|
||||
<Tag color={BIND_TONES[overview?.xpd_bind_status ?? 'unknown']}>
|
||||
小店:{overview?.xpd_bind_label || '未知'}
|
||||
</Tag>
|
||||
</Space>
|
||||
)}
|
||||
</Descriptions.Item>
|
||||
|
||||
<Descriptions.Item label="归属">
|
||||
<Select
|
||||
size="small"
|
||||
style={{ width: 140 }}
|
||||
placeholder="未分配"
|
||||
value={overview?.assigned_to ?? undefined}
|
||||
allowClear
|
||||
onChange={(val) => void handleAssign(val ?? null)}
|
||||
options={supportUsers.map((u) => ({ value: u.id, label: u.username }))}
|
||||
/>
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="标签">
|
||||
{tagEditing ? (
|
||||
<Space.Compact>
|
||||
<Input
|
||||
size="small"
|
||||
style={{ width: 120 }}
|
||||
maxLength={32}
|
||||
value={tagDraft}
|
||||
onChange={(e) => setTagDraft(e.target.value)}
|
||||
onPressEnter={() => void handleSaveTag()}
|
||||
/>
|
||||
<Button size="small" type="primary" onClick={() => void handleSaveTag()}>
|
||||
保存
|
||||
</Button>
|
||||
<Button size="small" onClick={() => setTagEditing(false)}>
|
||||
取消
|
||||
</Button>
|
||||
</Space.Compact>
|
||||
) : (
|
||||
<Space size={4}>
|
||||
<span>{overview?.tag || '-'}</span>
|
||||
<Tooltip title="编辑标签">
|
||||
<Button
|
||||
type="text"
|
||||
size="small"
|
||||
icon={<EditOutlined />}
|
||||
onClick={() => {
|
||||
setTagDraft(overview?.tag || '');
|
||||
setTagEditing(true);
|
||||
}}
|
||||
/>
|
||||
</Tooltip>
|
||||
</Space>
|
||||
)}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="备注">
|
||||
{remarkEditing ? (
|
||||
@@ -565,65 +541,143 @@ export default function AccountDetailPage() {
|
||||
</Space>
|
||||
)}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="状态变更">
|
||||
{formatTime(overview?.status_changed_at)}
|
||||
{overview?.status_reason ? (
|
||||
<Text type="secondary">({overview.status_reason})</Text>
|
||||
) : null}
|
||||
</Descriptions.Item>
|
||||
</Descriptions>
|
||||
</Card>
|
||||
|
||||
<div style={{ display: 'flex', gap: 32, marginTop: 16, flexWrap: 'wrap' }}>
|
||||
<Statistic title="当前积分" value={overview?.points ?? '-'} />
|
||||
<Statistic
|
||||
title="积分到期"
|
||||
// 斗鱼用 0 表示「没有到期时间」;不处理会显示成 1970/1/1
|
||||
value={overview?.points_expire_at ? formatTime(overview.points_expire_at) : '-'}
|
||||
valueStyle={{ fontSize: 20 }}
|
||||
/>
|
||||
<Statistic title="鱼翅余额" value={overview?.gold_balance ?? '-'} />
|
||||
<Statistic title="兑换余额" value={overview?.exchange_balance ?? '-'} />
|
||||
<Statistic
|
||||
title="精英宝典"
|
||||
value={overview?.elite_opened ? '已开通' : '未开通'}
|
||||
valueStyle={{ color: overview?.elite_opened ? '#3f8600' : undefined, fontSize: 20 }}
|
||||
/>
|
||||
<Statistic
|
||||
title="电竞手册"
|
||||
value={overview?.esports_opened ? '已开通' : '未开通'}
|
||||
valueStyle={{ fontSize: 20 }}
|
||||
/>
|
||||
</div>
|
||||
{/* ── 卡片 2:资产与统计 ────────────────────────────
|
||||
资产就**只在这里**展示一次(之前状态条里还重复了一遍)。
|
||||
两组分开:上面是「现在有多少」,下面是「历史累计」。 */}
|
||||
<Card size="small" style={{ marginBottom: 12 }} title="资产与统计">
|
||||
<Row gutter={[24, 16]}>
|
||||
<Col span={4}>
|
||||
<Statistic title="当前积分" value={overview?.points ?? '-'} />
|
||||
</Col>
|
||||
<Col span={4}>
|
||||
<Statistic
|
||||
title="积分到期"
|
||||
value={
|
||||
// 斗鱼用 0 表示「没有到期时间」;不处理会显示成 1970/1/1
|
||||
overview?.points_expire_at ? formatTime(overview.points_expire_at) : '-'
|
||||
}
|
||||
valueStyle={{ fontSize: 18 }}
|
||||
/>
|
||||
</Col>
|
||||
<Col span={4}>
|
||||
<Statistic title="鱼翅余额" value={overview?.gold_balance ?? '-'} />
|
||||
</Col>
|
||||
<Col span={4}>
|
||||
<Statistic title="兑换余额" value={overview?.exchange_balance ?? '-'} />
|
||||
</Col>
|
||||
<Col span={4}>
|
||||
<Statistic
|
||||
title="精英宝典"
|
||||
value={overview?.elite_opened ? '已开通' : '未开通'}
|
||||
valueStyle={{
|
||||
fontSize: 18,
|
||||
color: overview?.elite_opened ? '#3f8600' : undefined,
|
||||
}}
|
||||
/>
|
||||
{/* 已开通才显示时间。开通时间来自事件(**上线后才有**);
|
||||
更早的历史查不到 —— 官方兑换记录里只有商品兑换,没有开通记录。 */}
|
||||
{overview?.elite_opened && (
|
||||
<Text type="secondary" style={{ fontSize: 12 }}>
|
||||
开通 {formatTime(overview?.opened_at?.elite)}
|
||||
<br />
|
||||
到期 {formatUnixSeconds(overview?.elite_expire_time)}
|
||||
</Text>
|
||||
)}
|
||||
</Col>
|
||||
<Col span={4}>
|
||||
<Statistic
|
||||
title="电竞手册"
|
||||
value={overview?.esports_opened ? '已开通' : '未开通'}
|
||||
valueStyle={{ fontSize: 18 }}
|
||||
/>
|
||||
{overview?.esports_opened && (
|
||||
<Text type="secondary" style={{ fontSize: 12 }}>
|
||||
开通 {formatTime(overview?.opened_at?.esports)}
|
||||
<br />
|
||||
到期 {formatUnixSeconds(overview?.esports_expire_time)}
|
||||
</Text>
|
||||
)}
|
||||
</Col>
|
||||
</Row>
|
||||
|
||||
<Descriptions column={3} size="small" style={{ marginTop: 16 }}>
|
||||
<Descriptions.Item label="精英宝典开通时间">
|
||||
{formatTime(overview?.opened_at?.elite)}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="电竞手册开通时间">
|
||||
{formatTime(overview?.opened_at?.esports)}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="最近 CK 检测">
|
||||
{formatTime(stats?.last_ck_check_at)}
|
||||
</Descriptions.Item>
|
||||
</Descriptions>
|
||||
<Divider style={{ margin: '16px 0 12px' }} />
|
||||
|
||||
<div style={{ display: 'flex', gap: 32, marginTop: 12, flexWrap: 'wrap' }}>
|
||||
<Statistic title="累计充值" value={stats?.recharge_total ?? 0} prefix="¥" />
|
||||
<Statistic title="兑换次数" value={stats?.exchange_count ?? 0} />
|
||||
<Statistic title="累计消耗积分" value={stats?.points_spent ?? 0} />
|
||||
<Statistic title="CK 失效次数" value={stats?.ck_invalid_count ?? 0} />
|
||||
<Statistic title="登录成功次数" value={stats?.login_count ?? 0} />
|
||||
<Statistic title="最近登录" value={formatTime(stats?.last_login_at)} />
|
||||
<Statistic title="事件总数" value={stats?.event_count ?? 0} />
|
||||
</div>
|
||||
<Row gutter={[24, 16]}>
|
||||
<Col span={4}>
|
||||
<Statistic title="累计充值" value={stats?.recharge_total ?? 0} prefix="¥" />
|
||||
</Col>
|
||||
<Col span={4}>
|
||||
<Statistic title="兑换次数" value={stats?.exchange_count ?? 0} />
|
||||
</Col>
|
||||
<Col span={4}>
|
||||
<Statistic title="累计消耗积分" value={stats?.points_spent ?? 0} />
|
||||
</Col>
|
||||
<Col span={4}>
|
||||
<Statistic title="CK 失效次数" value={stats?.ck_invalid_count ?? 0} />
|
||||
</Col>
|
||||
<Col span={4}>
|
||||
<Statistic title="登录成功次数" value={stats?.login_count ?? 0} />
|
||||
</Col>
|
||||
<Col span={4}>
|
||||
<Statistic title="事件总数" value={stats?.event_count ?? 0} />
|
||||
</Col>
|
||||
</Row>
|
||||
|
||||
<Text type="secondary" style={{ display: 'block', marginTop: 12, fontSize: 12 }}>
|
||||
开通时间与累计统计来自「账号事件」,从该功能上线起开始记录;
|
||||
更早的历史请到「登录任务 / 精英宝典 / 电竞手册 / 和平小店」页查看。
|
||||
最近登录 {formatTime(stats?.last_login_at)}。
|
||||
开通时间与累计统计来自「账号事件」,从该功能上线起记录;
|
||||
更早的开通历史**查不到**(官方兑换记录里只有商品兑换,没有开通记录)。
|
||||
</Text>
|
||||
</Card>
|
||||
|
||||
{/* ── 卡片 3:一键查询结果 ──────────────────────────
|
||||
放在账号信息**下面** —— 它是补充信息(账号表里没有的两项),
|
||||
不该压在最上面抢主视觉。 */}
|
||||
<Card
|
||||
size="small"
|
||||
style={{ marginBottom: 12 }}
|
||||
title={
|
||||
<Space>
|
||||
<ThunderboltOutlined />
|
||||
<span>高价值套装与兑换记录</span>
|
||||
{overview?.overview_queried_at && (
|
||||
<Text type="secondary" style={{ fontSize: 12, fontWeight: 'normal' }}>
|
||||
查询于 {formatTime(overview.overview_queried_at)}
|
||||
</Text>
|
||||
)}
|
||||
</Space>
|
||||
}
|
||||
extra={
|
||||
<Button
|
||||
icon={<ThunderboltOutlined />}
|
||||
loading={ovLoading}
|
||||
onClick={runOverview}
|
||||
>
|
||||
一键查询
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
{ovError && (
|
||||
<Text type="danger" style={{ display: 'block', marginBottom: 8 }}>
|
||||
{ovError}
|
||||
</Text>
|
||||
)}
|
||||
{overview?.overview_snapshot ? (
|
||||
<AccountOverviewPanel result={overview.overview_snapshot} />
|
||||
) : (
|
||||
<Text type="secondary">
|
||||
点右上角「一键查询」实时向斗鱼查一次:鱼翅 / 积分 / 开通状态会就地刷新到上面的
|
||||
「资产与统计」,这里只展示账号表里没有的两项 ——
|
||||
高价值套装是否已获得,以及官方兑换记录。
|
||||
</Text>
|
||||
)}
|
||||
</Card>
|
||||
</Spin>
|
||||
|
||||
|
||||
<Card
|
||||
title="账号时间线"
|
||||
extra={
|
||||
|
||||
@@ -1,15 +1,30 @@
|
||||
import { useEffect, useState, useMemo, useCallback } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import {
|
||||
Alert, Table, Button, Modal, Input, Select, Popconfirm, Typography, Tag, Space,
|
||||
Row, Col, Card, Statistic, App, Tooltip,
|
||||
Alert,
|
||||
Table,
|
||||
Button,
|
||||
Modal,
|
||||
Input,
|
||||
Select,
|
||||
Popconfirm,
|
||||
Typography,
|
||||
Tag,
|
||||
Space,
|
||||
Row,
|
||||
Col,
|
||||
Card,
|
||||
Statistic,
|
||||
App,
|
||||
Tooltip,
|
||||
Spin,
|
||||
} from 'antd';
|
||||
import { message } from '../utils/antdMessage';
|
||||
import type { TableProps } from 'antd';
|
||||
import { ImportOutlined, DeleteOutlined, TagOutlined, FilterOutlined, EyeOutlined, EyeInvisibleOutlined, ThunderboltOutlined } from '@ant-design/icons';
|
||||
import { accountApi, douyuApi, type AccountItem, type BasicSummary } from '../api/modules';
|
||||
import { accountApi, douyuApi, type AccountExchangeRecord, type AccountExchangeRecords, type AccountItem, type BasicSummary } from '../api/modules';
|
||||
import { usePermissions } from '../hooks/usePermissions';
|
||||
import { formatTimeShort } from '../utils/time';
|
||||
import { formatTime, formatTimeShort } from '../utils/time';
|
||||
import { getErrorMessage } from '../utils/error';
|
||||
|
||||
const TAG_COLORS = [
|
||||
@@ -72,6 +87,44 @@ function BindChip({ scope, status }: { scope: string; status?: string }) {
|
||||
return <Tag color={tone} style={{ marginInlineEnd: 0 }}>{scope}{mark}</Tag>;
|
||||
}
|
||||
|
||||
/** 三个作用域的展示顺序与中文名(后端按 scope 分组返回)。 */
|
||||
const EXCHANGE_SCOPES: Array<{ key: string; label: string }> = [
|
||||
{ key: 'elite', label: '精英宝典' },
|
||||
{ key: 'esports', label: '电竞手册' },
|
||||
{ key: 'peace', label: '和平小店' },
|
||||
];
|
||||
|
||||
const EXCHANGE_COLUMNS: TableProps<AccountExchangeRecord>['columns'] = [
|
||||
{
|
||||
title: '商品',
|
||||
dataIndex: 'commodity_name',
|
||||
key: 'commodity_name',
|
||||
render: (value: string) => value || '-',
|
||||
},
|
||||
{
|
||||
title: '积分',
|
||||
dataIndex: 'score',
|
||||
key: 'score',
|
||||
width: 90,
|
||||
render: (value: number | string | null) => value ?? '-',
|
||||
},
|
||||
{
|
||||
// 官方记录带**真实兑换时间**
|
||||
title: '兑换时间',
|
||||
dataIndex: 'occurred_at',
|
||||
key: 'occurred_at',
|
||||
width: 170,
|
||||
render: (value: string | null) => formatTime(value),
|
||||
},
|
||||
{
|
||||
// 当时用的斗鱼昵称 + 平台/支付渠道,排查时有用
|
||||
title: '使用昵称',
|
||||
dataIndex: 'show_name',
|
||||
key: 'show_name',
|
||||
render: (value: string) => value || '-',
|
||||
},
|
||||
];
|
||||
|
||||
export default function AccountsPage() {
|
||||
const navigate = useNavigate();
|
||||
// App.useApp() 的 modal 实例继承主题,静态 Modal.confirm 在暗色模式下是白底
|
||||
@@ -88,6 +141,23 @@ export default function AccountsPage() {
|
||||
const [ckFilter, setCkFilter] = useState<string>('');
|
||||
const [bindFilter, setBindFilter] = useState<string>('');
|
||||
const [searchText, setSearchText] = useState('');
|
||||
// 兑换记录预览:点列表那一格**按需拉取**(不进列表响应),弹窗按作用域分组
|
||||
const [exRecords, setExRecords] = useState<AccountExchangeRecords | null>(null);
|
||||
const [exLoading, setExLoading] = useState(false);
|
||||
const [exAccount, setExAccount] = useState<AccountItem | null>(null);
|
||||
const openExchangeRecords = async (record: AccountItem) => {
|
||||
setExAccount(record);
|
||||
setExRecords(null);
|
||||
setExLoading(true);
|
||||
try {
|
||||
setExRecords(await accountApi.exchangeRecords(record.id));
|
||||
} catch (error) {
|
||||
message.error(getErrorMessage(error));
|
||||
} finally {
|
||||
setExLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
|
||||
const [selectedAllMatching, setSelectedAllMatching] = useState(false);
|
||||
const [batchTagInput, setBatchTagInput] = useState('');
|
||||
@@ -377,12 +447,29 @@ export default function AccountsPage() {
|
||||
dataIndex: 'role_bind_status',
|
||||
width: 150,
|
||||
render: (_, record: AccountItem) => {
|
||||
// 三个作用域全都没查过时,显示「—」而不是「精? 电? 店?」——
|
||||
// 满屏问号只是噪声,不如一眼看出「这账号还没查过绑定」。
|
||||
const allUnknown = [record.role_bind_status, record.esports_bind_status, record.xpd_bind_status]
|
||||
.every((s) => !s || s === 'unknown');
|
||||
// 三个作用域全都 unknown 时不再显示「精? 电? 店?」(满屏问号只是噪声),
|
||||
// 但要把两种情况**分开**:
|
||||
// 没查过 → 「未查询」(有救,点一键查询就有了)
|
||||
// 查过但推不出 → 「未能判定」(接口没给结论)
|
||||
// 混成一个词会让人不知道下一步该干什么。
|
||||
const allUnknown = [
|
||||
record.role_bind_status,
|
||||
record.esports_bind_status,
|
||||
record.xpd_bind_status,
|
||||
].every((s) => !s || s === 'unknown');
|
||||
if (allUnknown) {
|
||||
return <Tooltip title="还没有查询过绑定"><Text type="secondary">—</Text></Tooltip>;
|
||||
const queried = Boolean(record.overview_queried_at);
|
||||
return (
|
||||
<Tooltip
|
||||
title={
|
||||
queried
|
||||
? '已查询过,但斗鱼这次没给出绑定结论(既非已绑也非未绑)'
|
||||
: '还没查询过绑定 —— 点工具栏「批量一键查询」'
|
||||
}
|
||||
>
|
||||
<Text type="secondary">{queried ? '未能判定' : '未查询'}</Text>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Space size={2} wrap>
|
||||
@@ -405,25 +492,78 @@ export default function AccountsPage() {
|
||||
),
|
||||
},
|
||||
{
|
||||
// 兑换记录:次数 + 最近一次(商品名 + 日期)。
|
||||
// 数据源是账号自己的事件流(`account_events.exchange`),不是 douyu_tasks 的 JSON ——
|
||||
// 后者是执行日志,S5 起业务事实已经在事件里了。完整历史看详情页时间线。
|
||||
// 高价值套装:这只关乎**账号价值** —— 没兑换过才值钱。
|
||||
//
|
||||
// ⚠️ 语义与直觉相反,别标反了:
|
||||
// **没兑换过** = 还能用来绑定兑换 = **高价值**(绿色)
|
||||
// 兑换过 1 个 → 价值降低;两个都兑换过 → 价值最低
|
||||
// 数据来自一键查询拉的**斗鱼官方兑换记录**。
|
||||
title: '高价值套装',
|
||||
dataIndex: 'high_value_owned',
|
||||
width: 170,
|
||||
render: (owned: string[] | undefined, record: AccountItem) => {
|
||||
const used = owned ?? [];
|
||||
// 没查过 ≠ 没兑换:必须分开说,否则会把"没数据"当成"高价值"
|
||||
// 「有没有查过」看查询时间:只看 owned 是否为空的话,
|
||||
// 「查过但没兑换」(高价值)和「没查过」(未知)就分不开了。
|
||||
const queried = Boolean(record.overview_queried_at);
|
||||
if (!queried) {
|
||||
return (
|
||||
<Tooltip title="还没做过一键查询,点工具栏「批量一键查询」">
|
||||
<Text type="secondary">未查询</Text>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
if (used.length === 0) {
|
||||
return <Tag color="green">两个都可兑换</Tag>;
|
||||
}
|
||||
return (
|
||||
<Space size={4} wrap>
|
||||
{used.map((n) => (
|
||||
<Tag key={n} color="orange">
|
||||
{n.replace(/^套装-/, '')} 已兑换
|
||||
</Tag>
|
||||
))}
|
||||
</Space>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
// 兑换记录:次数 + 最近一次。
|
||||
//
|
||||
// 只反映**斗鱼官方记录**(后端聚合已按 source=official_sync 过滤)——
|
||||
// 我们当场记的那些留给详情页时间线,列表要的是"官方权威且完整"的口径。
|
||||
// 点这一格弹窗看全部(按作用域分组),不用进详情页。
|
||||
title: '兑换记录',
|
||||
dataIndex: 'exchange_count',
|
||||
width: 170,
|
||||
render: (_, record: AccountItem) => {
|
||||
if (!record.exchange_count) return <Text type="secondary">未兑换</Text>;
|
||||
if (!record.exchange_count) {
|
||||
return <Text type="secondary">未兑换</Text>;
|
||||
}
|
||||
return (
|
||||
<Space direction="vertical" size={0} style={{ maxWidth: '100%' }}>
|
||||
<Text>{record.exchange_count} 次</Text>
|
||||
<Text type="secondary" style={{ fontSize: 12 }} ellipsis title={record.last_exchange_name}>
|
||||
{formatTimeShort(record.last_exchange_at)}
|
||||
{/* 列的标题已经是「兑换记录」,事件 title 里的「兑换 」前缀在这儿是重复的 */}
|
||||
{record.last_exchange_name
|
||||
? ` ${record.last_exchange_name.replace(/^兑换\s*/, '')}`
|
||||
: ''}
|
||||
</Text>
|
||||
</Space>
|
||||
<Tooltip title="点击查看全部官方兑换记录">
|
||||
<div
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
style={{ cursor: 'pointer' }}
|
||||
onClick={() => void openExchangeRecords(record)}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === 'Enter') void openExchangeRecords(record);
|
||||
}}
|
||||
>
|
||||
<Space direction="vertical" size={0} style={{ maxWidth: '100%' }}>
|
||||
<Text>{record.exchange_count} 次</Text>
|
||||
<Text type="secondary" style={{ fontSize: 12 }} ellipsis>
|
||||
{formatTimeShort(record.last_exchange_at)}
|
||||
{/* 列标题已是「兑换记录」,事件 title 里的「兑换 」前缀在这儿重复 */}
|
||||
{record.last_exchange_name
|
||||
? ` ${record.last_exchange_name.replace(/^兑换\s*/, '')}`
|
||||
: ''}
|
||||
</Text>
|
||||
</Space>
|
||||
</div>
|
||||
</Tooltip>
|
||||
);
|
||||
},
|
||||
},
|
||||
@@ -730,6 +870,54 @@ export default function AccountsPage() {
|
||||
options={tags.map((t) => ({ value: t, label: t }))}
|
||||
/>
|
||||
</Modal>
|
||||
|
||||
<Modal
|
||||
title={
|
||||
<Space>
|
||||
<span>官方兑换记录</span>
|
||||
{exAccount && (
|
||||
<Text type="secondary" style={{ fontSize: 12, fontWeight: 'normal' }}>
|
||||
{exAccount.username}
|
||||
</Text>
|
||||
)}
|
||||
</Space>
|
||||
}
|
||||
open={Boolean(exAccount)}
|
||||
onCancel={() => setExAccount(null)}
|
||||
footer={<Button onClick={() => setExAccount(null)}>关闭</Button>}
|
||||
width={760}
|
||||
styles={{ body: { maxHeight: '65vh', overflowY: 'auto' } }}
|
||||
>
|
||||
{exLoading ? (
|
||||
<Spin />
|
||||
) : !exRecords || exRecords.total === 0 ? (
|
||||
<Text type="secondary">
|
||||
没有官方兑换记录。若还没查过这个账号,先点工具栏「批量一键查询」。
|
||||
</Text>
|
||||
) : (
|
||||
<Space direction="vertical" size={16} style={{ width: '100%' }}>
|
||||
{EXCHANGE_SCOPES.map(({ key, label }) => {
|
||||
const rows = exRecords.groups[key] ?? [];
|
||||
if (rows.length === 0) return null;
|
||||
return (
|
||||
<div key={key}>
|
||||
<Text strong>
|
||||
{label}({rows.length} 条)
|
||||
</Text>
|
||||
<Table
|
||||
size="small"
|
||||
style={{ marginTop: 8 }}
|
||||
rowKey={(row) => `${row.commodity_id}-${row.occurred_at ?? ''}`}
|
||||
columns={EXCHANGE_COLUMNS}
|
||||
dataSource={rows}
|
||||
pagination={false}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</Space>
|
||||
)}
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Alert, Card, Descriptions, Empty, Space, Table, Tag, Typography } from 'antd';
|
||||
import { Alert, Card, Col, Empty, Row, Space, Table, Tag, Tooltip, Typography } from 'antd';
|
||||
import type { ColumnsType } from 'antd/es/table';
|
||||
|
||||
const { Text } = Typography;
|
||||
@@ -42,8 +42,22 @@ export interface AccountOverviewResult {
|
||||
};
|
||||
high_value_goods?: HighValueGoods[];
|
||||
limited_goods_total?: number;
|
||||
exchange_records?: Array<Record<string, unknown>>;
|
||||
/** 按作用域分组:elite / esports / peace */
|
||||
exchange_records?: Record<string, Array<Record<string, unknown>>>;
|
||||
exchange_record_count?: number;
|
||||
/** 三个作用域的绑定明细(一键查询会真的去查,以前从不查 → 97% 显示未知) */
|
||||
bind?: Record<
|
||||
string,
|
||||
{
|
||||
derived?: string | null;
|
||||
role_name?: string;
|
||||
area_name?: string;
|
||||
plat_name?: string;
|
||||
nickname?: string;
|
||||
change_role_wait_time?: number | null;
|
||||
can_change_time?: number | null;
|
||||
}
|
||||
>;
|
||||
/** 单项失败:**必须展示**,否则「没查到」会被读成「没有」 */
|
||||
errors?: Record<string, string>;
|
||||
}
|
||||
@@ -90,93 +104,147 @@ function formatTime(value: string | number | null | undefined): string {
|
||||
* 我们没法只凭它断言账号真的拿到了。所以写「不可再兑」并把 count 一起显示,
|
||||
* 让运营自己判断 —— 这比给一个可能错的结论好。
|
||||
*/
|
||||
function HighValueCard({ goods }: { goods: HighValueGoods }) {
|
||||
if (goods.missing) {
|
||||
return (
|
||||
<Card size="small" style={{ width: 280, borderStyle: 'dashed' }}>
|
||||
<Space direction="vertical" size={2}>
|
||||
<Text strong>{goods.name}</Text>
|
||||
<Tag color="default">未查到该商品</Tag>
|
||||
<Text type="secondary" style={{ fontSize: 12 }}>
|
||||
{goods.reason || '限兑列表和官方兑换记录里都没有它'}
|
||||
</Text>
|
||||
/**
|
||||
* 高价值套装的展示状态。
|
||||
*
|
||||
* ⚠️ **颜色是「价值」口径,不是「有没有」口径** —— 别标反:
|
||||
* 没兑换过 → 「可兑换」**绿色**(这个账号还值钱,能用来绑定兑换)
|
||||
* 兑换过 → 「已兑换」**橙色**(价值降低)
|
||||
* 同一件东西两个都兑换过,账号价值最低。
|
||||
*
|
||||
* 「是否已获得」只看**官方兑换记录**:`count`/`store_status` 是全局库存,
|
||||
* 同一时刻不同账号看到的都一样,不能用来判断这个账号有没有。
|
||||
*/
|
||||
function goodsState(g: HighValueGoods): { text: string; color: string } {
|
||||
if (g.missing) return { text: '未查到该商品', color: 'default' };
|
||||
return g.owned
|
||||
? { text: '已兑换(价值降低)', color: 'orange' }
|
||||
: { text: '可兑换', color: 'green' };
|
||||
}
|
||||
|
||||
const goodsColumns: ColumnsType<HighValueGoods> = [
|
||||
{
|
||||
title: '高价值套装',
|
||||
dataIndex: 'name',
|
||||
key: 'name',
|
||||
width: 200,
|
||||
render: (name: string, g) =>
|
||||
g.missing ? (
|
||||
<Tooltip title={g.reason || '限兑列表和官方兑换记录里都没有它'}>
|
||||
<Text type="secondary">{name}</Text>
|
||||
</Tooltip>
|
||||
) : (
|
||||
<Text strong>{name}</Text>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '可兑换 / 已兑换',
|
||||
key: 'owned',
|
||||
width: 130,
|
||||
render: (_, g) => {
|
||||
const state = goodsState(g);
|
||||
return <Tag color={state.color}>{state.text}</Tag>;
|
||||
},
|
||||
},
|
||||
{
|
||||
title: '兑换记录里的名字',
|
||||
key: 'obtained',
|
||||
render: (_, g) =>
|
||||
g.obtained_names?.length ? (
|
||||
<Text style={{ fontSize: 12 }}>{g.obtained_names.join('、')}</Text>
|
||||
) : (
|
||||
<Text type="secondary">—</Text>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '积分价',
|
||||
dataIndex: 'score',
|
||||
key: 'score',
|
||||
width: 90,
|
||||
render: (v: number | null | undefined) => v ?? '—',
|
||||
},
|
||||
{
|
||||
title: '当前库存',
|
||||
dataIndex: 'count',
|
||||
key: 'count',
|
||||
width: 120,
|
||||
render: (v: number | null | undefined, g) =>
|
||||
v == null ? (
|
||||
'—'
|
||||
) : (
|
||||
<Space size={4}>
|
||||
<span>{v}</span>
|
||||
{v === 0 && <Text type="secondary">(售罄)</Text>}
|
||||
{g.in_goods_list === false && <Text type="secondary">(已下架)</Text>}
|
||||
</Space>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
// ⚠️ 「是否已获得」只看官方兑换记录。`count`/`store_status` 是**全局库存**,
|
||||
// 同一时刻不同账号看到的都一样,**不能**用来判断这个账号有没有。
|
||||
const owned = goods.owned === true;
|
||||
return (
|
||||
<Card
|
||||
size="small"
|
||||
style={{ width: 280, borderColor: owned ? '#52c41a' : undefined }}
|
||||
title={<Text strong>{goods.name}</Text>}
|
||||
extra={
|
||||
<Tag color={owned ? 'green' : 'default'}>{owned ? '✅ 已获得' : '未获得'}</Tag>
|
||||
}
|
||||
>
|
||||
<Descriptions size="small" column={1} colon={false}>
|
||||
{owned && (
|
||||
<Descriptions.Item label="记录">
|
||||
{(goods.obtained_names || []).join('、') || '-'}
|
||||
</Descriptions.Item>
|
||||
)}
|
||||
<Descriptions.Item label="积分价">{goods.score ?? '-'}</Descriptions.Item>
|
||||
<Descriptions.Item label="当前库存">
|
||||
{goods.count ?? '-'}
|
||||
{goods.count === 0 ? '(已售罄)' : ''}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="活动时间">
|
||||
{formatTime(goods.start_time)} ~ {formatTime(goods.end_time)}
|
||||
</Descriptions.Item>
|
||||
</Descriptions>
|
||||
{!goods.in_goods_list && (
|
||||
<Text type="secondary" style={{ fontSize: 12 }}>
|
||||
当前限兑列表里没有它(活动窗口可能已结束),但兑换记录仍在。
|
||||
</Text>
|
||||
)}
|
||||
</Card>
|
||||
);
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '活动时间',
|
||||
key: 'window',
|
||||
width: 200,
|
||||
render: (_, g) =>
|
||||
g.missing ? '—' : `${formatTime(g.start_time)} ~ ${formatTime(g.end_time)}`,
|
||||
},
|
||||
];
|
||||
|
||||
/** 三个作用域的展示顺序(后端按 scope 分组返回)。 */
|
||||
const EXCHANGE_SCOPES: Array<{ key: string; label: string }> = [
|
||||
{ key: 'elite', label: '精英宝典' },
|
||||
{ key: 'esports', label: '电竞手册' },
|
||||
{ key: 'peace', label: '和平小店' },
|
||||
];
|
||||
|
||||
/** 三个作用域的展示顺序(与后端 bind 的 key 对应)。 */
|
||||
const BIND_SCOPES: Array<{ key: string; label: string }> = [
|
||||
{ key: 'elite', label: '精英宝典' },
|
||||
{ key: 'esports', label: '电竞手册' },
|
||||
{ key: 'peace', label: '和平小店' },
|
||||
];
|
||||
|
||||
/** 换绑冷却(秒)→ 可读;0 / 空表示没有冷却。 */
|
||||
function formatWait(seconds: number | null | undefined): string {
|
||||
if (!seconds || seconds <= 0) return '无';
|
||||
const hours = Math.floor(seconds / 3600);
|
||||
if (hours >= 24) return `${Math.floor(hours / 24)} 天 ${hours % 24} 小时`;
|
||||
if (hours >= 1) return `${hours} 小时`;
|
||||
return `${Math.floor(seconds / 60)} 分钟`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 一键查询结果面板。
|
||||
*
|
||||
* ⚠️ **只展示账号表里没有的东西**(高价值套装是否已获得、官方兑换记录)。
|
||||
*
|
||||
* 鱼翅 / 积分 / 钱包余额 / 开通状态这些,账号表本来就有对应字段
|
||||
* (`gold_balance` / `points` / `exchange_balance` / `elite_opened` / `esports_opened`),
|
||||
* 查询的作用是**刷新它们**,然后由账号详情里已有的界面直接反映出来 ——
|
||||
* 在这里再复制一份展示是多余的,还会让人分不清哪份才是准的。
|
||||
*/
|
||||
export default function AccountOverviewPanel({
|
||||
result,
|
||||
queriedAt,
|
||||
}: {
|
||||
result: AccountOverviewResult;
|
||||
/** 查询时间(优先用账号上记录的,回落到结果里的) */
|
||||
queriedAt?: string | null;
|
||||
}) {
|
||||
if (!result) return <Empty description="暂无结果" />;
|
||||
const errors = result.errors || {};
|
||||
const goods = result.high_value_goods || [];
|
||||
const records = result.exchange_records || [];
|
||||
const recordGroups = result.exchange_records || {};
|
||||
|
||||
const recordColumns: ColumnsType<Record<string, unknown>> = [
|
||||
{
|
||||
title: '商品',
|
||||
dataIndex: 'commodityName',
|
||||
key: 'commodityName',
|
||||
render: (v: unknown) => String(v ?? '-'),
|
||||
key: 'name',
|
||||
render: (_, row) => String(row.commodityName ?? row.commodity_name ?? '-'),
|
||||
},
|
||||
{
|
||||
title: '时间',
|
||||
title: '积分',
|
||||
key: 'score',
|
||||
width: 90,
|
||||
render: (_, row) => String(row.score ?? '-'),
|
||||
},
|
||||
{
|
||||
// 官方记录带**真实兑换时间**
|
||||
title: '兑换时间',
|
||||
key: 'time',
|
||||
width: 170,
|
||||
render: (_, row) =>
|
||||
formatTime(
|
||||
(row.createTime ?? row.create_time ?? row.time) as string | number | null,
|
||||
),
|
||||
formatTime((row.time ?? row.occurred_at) as string | number | null),
|
||||
},
|
||||
{
|
||||
title: '使用昵称',
|
||||
key: 'show',
|
||||
render: (_, row) => String(row.showName ?? row.show_name ?? '-'),
|
||||
},
|
||||
];
|
||||
|
||||
@@ -199,38 +267,81 @@ export default function AccountOverviewPanel({
|
||||
/>
|
||||
)}
|
||||
|
||||
<Card size="small" title="🎯 高价值套装">
|
||||
{goods.length === 0 ? (
|
||||
<Text type="secondary">没有配置关注的高价值套装,或本次没取到</Text>
|
||||
) : (
|
||||
<Space wrap size={12}>
|
||||
{goods.map((g) => (
|
||||
<HighValueCard key={g.commodity_id || g.name} goods={g} />
|
||||
))}
|
||||
</Space>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
size="small"
|
||||
title={`兑换记录${result.exchange_record_count ? `(${result.exchange_record_count} 条)` : ''}`}
|
||||
>
|
||||
{records.length === 0 ? (
|
||||
<Text type="secondary">官方暂无兑换记录</Text>
|
||||
title="🎯 高价值套装(没兑换过才值钱)" styles={{ body: { padding: 0 } }}>
|
||||
{goods.length === 0 ? (
|
||||
<div style={{ padding: 12 }}>
|
||||
<Text type="secondary">没有配置关注的高价值套装,或本次没取到</Text>
|
||||
</div>
|
||||
) : (
|
||||
<Table
|
||||
size="small"
|
||||
rowKey={(_, i) => String(i)}
|
||||
columns={recordColumns}
|
||||
dataSource={records}
|
||||
pagination={{ pageSize: 10, size: 'small' }}
|
||||
rowKey={(g) => g.commodity_id || g.name}
|
||||
columns={goodsColumns}
|
||||
dataSource={goods}
|
||||
pagination={false}
|
||||
/>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
<Text type="secondary" style={{ fontSize: 12 }}>
|
||||
查询时间:{formatTime(queriedAt ?? result.queried_at)}
|
||||
</Text>
|
||||
<Card size="small" title="🎮 角色绑定明细">
|
||||
<Row gutter={[16, 12]}>
|
||||
{BIND_SCOPES.map(({ key, label }) => {
|
||||
const info = (result.bind ?? {})[key];
|
||||
if (!info) {
|
||||
return (
|
||||
<Col span={8} key={key}>
|
||||
<Text type="secondary">{label}:未查询</Text>
|
||||
</Col>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Col span={8} key={key}>
|
||||
<Space direction="vertical" size={2}>
|
||||
<Text strong>{label}</Text>
|
||||
<Text>
|
||||
{info.role_name ? info.role_name : '(未绑定角色)'}
|
||||
</Text>
|
||||
<Text type="secondary" style={{ fontSize: 12 }}>
|
||||
{[info.plat_name, info.area_name].filter(Boolean).join(' · ') || '-'}
|
||||
</Text>
|
||||
<Text type="secondary" style={{ fontSize: 12 }}>
|
||||
换绑冷却 {formatWait(info.change_role_wait_time)}
|
||||
{info.can_change_time
|
||||
? ` · 可换绑 ${formatTime(info.can_change_time)}`
|
||||
: ''}
|
||||
</Text>
|
||||
</Space>
|
||||
</Col>
|
||||
);
|
||||
})}
|
||||
</Row>
|
||||
</Card>
|
||||
|
||||
{EXCHANGE_SCOPES.map(({ key, label }) => {
|
||||
const rows = recordGroups[key] ?? [];
|
||||
return (
|
||||
<Card
|
||||
key={key}
|
||||
size="small"
|
||||
title={`兑换记录 · ${label}${rows.length ? `(${rows.length} 条)` : ''}`}
|
||||
styles={{ body: { padding: rows.length ? 0 : 12 } }}
|
||||
>
|
||||
{rows.length === 0 ? (
|
||||
<Text type="secondary">官方暂无{label}兑换记录</Text>
|
||||
) : (
|
||||
<Table
|
||||
size="small"
|
||||
rowKey={(_, i) => String(i)}
|
||||
columns={recordColumns}
|
||||
dataSource={rows}
|
||||
pagination={{ pageSize: 10, size: 'small' }}
|
||||
/>
|
||||
)}
|
||||
</Card>
|
||||
);
|
||||
})}
|
||||
</Space>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -34,3 +34,16 @@ export function formatTimeShort(val: string | null | undefined): string {
|
||||
return d.isValid() ? d.format('MM-DD HH:mm') : val;
|
||||
}
|
||||
|
||||
/**
|
||||
* 斗鱼给的**秒级时间戳** → 可读文本。
|
||||
*
|
||||
* ⚠️ `0` / `null` / 负数 一律显示 `-`:斗鱼用 0 表示「没有这个时间」,
|
||||
* 而 `new Date(0)` 是 **1970/1/1** —— 直接格式化会让运营以为
|
||||
* "到期时间是 1970 年"(这个 bug 真出现过)。
|
||||
*/
|
||||
export function formatUnixSeconds(val: number | string | null | undefined): string {
|
||||
if (val === null || val === undefined || val === '') return '-';
|
||||
const seconds = typeof val === 'number' ? val : Number(val);
|
||||
if (!Number.isFinite(seconds) || seconds <= 0) return '-';
|
||||
return formatTime(new Date(seconds * 1000).toISOString());
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user