12 Commits
Author SHA1 Message Date
yml2213 bb20533c90 feat(douyu-pool): 支持和平精英号池兑换与商品自动刷新,优化号池操作面板
- 扩展号池支持 peace (和平精英/小跑道) 活动 scope,映射 xpd_balance 与 exchange_xpd_goods 任务
- 新增 POST /douyu/pool/refresh-goods 接口与前端一键刷新,支持复用库内有效 CK 自动更新商品快照
- 前端 DouyuPoolPage 升级视觉设计与栅格布局,商品选择器支持按活动类型分类联动
- 修复 DouyuTask.result 类型守卫、account_events actor_id 类型防御与 runner 过滤规则边界值处理
- 验证方式:全量 pytest (797 通过)、pyright (0 错误)、tsc -b 及 ruff format/check 全部通过
2026-10-08 13:15:21 +08:00
yml2213 88422f2f05 Merge branch 'fix/pyright-env-and-type-guards' into dev 2026-10-08 12:34:11 +08:00
yml2213 a3c3a46b9c fix(tooling): 修复 pyright 解释器配置与类型守卫,补齐 ruff 门禁与两处历史 bug
- pyrightconfig.json 钉死 Python 3.12 虚拟环境,消除由于查找系统 Python 3.9 带来的假性报错
- 修复 huya/login.py 引用不存在函数的问题并补充单元测试
- 修复 browser_harvest.py 对 set 下标访问的错误并提升报错信息质量
- 虎牙 6 个子路由显式导入依赖,消除 import * 带来的未定义变量报警
- 规范化 Pydantic Field(default=...) 默认值声明
- 完善 solver.py / app_login.py 等核心路径类型守卫与 @overload 重载
- 在 pyproject.toml 中显式锁定 ruff lint 规则集 (E4, E7, E9, F, B, I, BLE)
- 门禁脚本同步增加 ruff check 检查并在 AGENTS.md 补齐实践经验总结
2026-10-08 12:33:39 +08:00
yml2213 224b147735 Merge branch 'main' into dev: 同步充值渠道切换修复 2026-10-08 11:53:26 +08:00
yml2213 ec07e4fc06 fix(config): 修复切换充值渠道报错及补齐 peace_enabled 字段声明
- 在 DouyuConfigOut 与 DouyuConfigUpdate 中补齐 peace_enabled 声明与序列化
- 在 update_config 中使用 getattr(req, field, None) 安全读取属性,避免 AttributeError 导致 500
- 在 _config_out 中加入 peace_enabled 输出映射
- 增加切换充值渠道与配置更新的单元测试
2026-10-08 11:49:41 +08:00
yml2213 578fb08dab test(pool): 修复测试用例中硬编码历史日期导致租约过期判定的问题 2026-10-08 11:41:32 +08:00
yml2213 077f14ef23 Merge branch 'main' into dev: 同步分配管理优化、登录异常分型及历史数据刷正 2026-10-08 11:38:48 +08:00
yml2213 4eef45efe4 fix(accounts): 完善手机号必绑与账号注销等登录异常分型识别
- 补充必须绑定手机号与账号注销/封禁/冻结等错误文案的识别规则
- 增加数据修正迁移 20261008_0052,回写历史账号和登录任务的失败分型
- 增加列表查询与导出时根据错误文案自动兜底细化 failure_kind 的逻辑
- 增加并完善相关分型单元测试
2026-10-08 11:26:19 +08:00
yml2213 f8ad6e1777 perf(assignments): 优化分配管理页面加载性能与角标数量展示
- 前端改造为服务端分页查询 (accountApi.listPaged),避免一次性拉取 1.6 万+ 账号导致页面卡死
- 优化后端 assignments_summary 聚合查询,消除大子查询临时表
- 修复 Badge 默认 99+ 限制,设置 overflowCount 支持展示完整账号数量
- 修复测试用例 test_business_events.py 当前时间跨天断言问题
2026-10-08 11:08:41 +08:00
yml2213 f101414f5e feat(accounts): 新增登录异常分型统计、多选/全量导出、筛选记忆及页面组件模块化拆分
- 新增登录失败异常分型统计:支持「必须绑定手机号」、「极验滑块」、「凭证错误」、「邮箱取码失败」、「邮箱配额已满」、「网络异常」分型识别、生命周期联动(待人工)与一键筛选;
- 新增账号名单与明细导出功能:支持勾选多选或按当前筛选条件全选,可导出纯用户名名单 (TXT) 或 UTF-8 BOM 结构化明细报表 (CSV),并支持一键复制到剪贴板;
- 优化筛选条件记忆机制:支持页面切换/返回后自动保留所有筛选与排序状态,新增顶部「重置全部筛选」快捷按钮;
- 模块化拆分 AccountsPage:将 2100+ 行的大文件拆解至 pages/accounts/ 子目录(包含状态卡片、筛选面板、工具栏、操作弹窗与表格构建器),提升可维护性;
- 验证方式:新增 5 个后端自动化单测 (test_account_failure_and_export.py),全量 694 个测试用例通过,前端 TypeScript 编译与 pre-commit 代码规范检查全部通过。
2026-10-07 17:23:39 +08:00
yml2213 603fc6eadc feat(douyu-pool): 完善微信扫码支付与任务闭环及常用快捷选择
- 前端在扫码支付弹窗中增加显眼充值金额卡片与多账号 Tabs 支付标注
- 前端增加常用与历史快捷皮肤选择胶囊栏,支持本地缓存记忆与一键切换
- 后端补给链首步引入 query_elite_status 并支持 require_opened 前置熔断校验
- 优化供给与预估花费文案展示,增加兑换结果大图预览与凭证复制功能
- 验证方式:全量 784 个 pytest 用例全部通过,前端 tsc/build 校验通过
2026-10-07 16:59:43 +08:00
yml2213 7c1a6caf47 fix(config): 补充 peace_enabled 字段声明并增加安全属性读取
- 在 DouyuConfigOut 与 DouyuConfigUpdate 中加入 peace_enabled 声明与序列化
- 在 update_config 中使用 getattr(req, field, None) 做安全兜底,避免 500
2026-10-07 16:19:23 +08:00
63 changed files with 4955 additions and 1665 deletions
+5 -1
View File
@@ -29,7 +29,11 @@ done <<< "$staged"
if [ "${#python_files[@]}" -gt 0 ]; then
echo "[pre-commit] 检查 Python 格式..."
uv run --group dev ruff format --check "${python_files[@]}"
echo "[pre-commit] Python 格式通过"
# ⚠️ 只跑 format 不够:format 不管「未使用导入 / 未排序导入 / 宽 except」这类
# 问题,之前全仓攒了 6 条(含一个 F401 死导入)没人拦。两条一起跑才算校验。
echo "[pre-commit] 检查 Python lint..."
uv run --group dev ruff check "${python_files[@]}"
echo "[pre-commit] Python 格式 + lint 通过"
fi
if [ "$frontend_changed" -eq 1 ]; then
+3 -1
View File
@@ -44,7 +44,9 @@ done <<< "$push_lines"
if [ "${#python_files[@]}" -gt 0 ]; then
echo "[pre-push] 检查 Python 格式..."
uv run --group dev ruff format --check "${python_files[@]}"
echo "[pre-push] Python 格式通过"
echo "[pre-push] 检查 Python lint..."
uv run --group dev ruff check "${python_files[@]}"
echo "[pre-push] Python 格式 + lint 通过"
fi
if [ "$frontend_changed" -eq 1 ]; then
+9 -4
View File
@@ -35,11 +35,14 @@
关键是**反向验证** —— 把 bug 注入回去,确认用例真的会变红,再还原。
「跑了一下没报错」不算验证。
- **提交/推送会跑钩子**,所以本地必须按同样标准自查:
- `pre-commit`:`ruff format --check`(**只跑 `ruff check` 不够**,格式不对会直接拦下提交)
- `pre-commit`:`ruff format --check` **和** `ruff check`(两个都要跑,见坑 #8)
+ 前端 `tsc -b`;
- `pre-push`:上面这些 + **全量 pytest**。
- `pre-push`:上面这些 + **全量 pytest**(`TYPECHECK=1` 时额外跑 Pyright)。
- **断言要看 `model_dump()`(序列化结果)**,只看属性会假绿(原因见坑 #2)。
- **别信「测试通过」** —— 用例可能是假绿的(原因见坑 #3)。
- **Pyright 只查 `core`/`utils`/`web`,`tests` 有意排除**(原因和重新打开的方法都写在
`pyrightconfig.json` 的注释里)。别为了让它闭嘴去给 FastAPI 路由补返回值注解 ——
那等于加了 `response_model`,会真的裁剪响应体。
## 4. 数据库与迁移
@@ -100,8 +103,10 @@ docker compose up -d douyu-login
| 5 | **`docker compose run` 默认读 stdin**:用 `ssh 'bash -s' < 脚本` 喂进去时,它会把脚本剩下的行吃掉 | 用 `docker compose run -T --rm ... </dev/null` |
| 6 | **镜像同步脚本会白等 15 分钟**:`pgrep -f 'mysqldump.*douyu_login'` 匹配到了自己所在的 shell,等待循环永不提前退出 | 判定远端进程存活别用会自匹配的 `pgrep -f` 模式 |
| 7 | **`set -e` + 输出过滤(管道接 `grep -v`)会半途静默中止**:过滤把输出全吃掉时 grep 返回 1,被 `set -e` 当成失败(曾在「已删库、还没导入」处中止,镜像库一度是空的) | 过滤输出后别让 `set -e` 接管退出码;关键步骤显式检查成功 |
| 8 | **`ruff check` 通过 ≠ 能提交**:钩子查的是 `ruff format` | 提交前本地跑一遍 `.githooks/pre-commit` |
| 8 | **格式检查和 lint 检查,只跑一个都会漏**:`ruff format --check` 对「未使用导入 / 未排序导入 / 宽 except」全部放过(实测同一个文件、同一处未使用 `import json`:format 退出码 0,check 退出码 1),而 `ruff check` 又完全不管格式 | 钩子现在两条都跑;本地自查也两条都跑(`./dev.sh format-check` + `./dev.sh lint-check`) |
| 9 | **偷换概念把「账号级状态」当成「全局字段」**:斗鱼商城 `storehome` 的 `count`(库存)确实是全局的,但 **`status` 字段是强账号维度的!`status=1` 就是「已达兑换上限」(限量 1 件已满/已兑换)**。曾把两者混为一谈,误以为商品列表全不可信,跑去依赖早已被官方清空的 `exchangeList`,导致已兑换的账号被错误打上「两个都可兑换」绿标 | 判定高价值资产准入:**以 `storehome.status==1` 为最高裁判**;`exchangeList` 仅做历史展示兜底,绝不可当作否定已拥有的依据 |
| 10 | **Pyright 的报错数量取决于「它怎么找到解释器」**:`pyrightconfig.json` 原本没钉解释器,直接跑 `.venv/bin/pyright` 时它会去 PATH 摸 `/usr/bin/python3`(macOS 自带 3.9),进而读用户级 `~/Library/Python/3.9/site-packages` 里的 **SQLAlchemy 1.4.54** 和 3.9 语义 → 全仓报 **2926** 条(`Mapped[int]` 说「不是泛型」、`int \| None` 说「需要 3.10+」、`UTC` 说不认识),而同一个仓库 `uv run pyright` 只有 **273** 条。**90% 的「错误」是环境假象** | 必须在配置里显式写 `venvPath`/`venv`/`pythonVersion`;IDE 里出现成片这类报错先查解释器。自查命令:`pyright --verbose` 看 `Assuming Python version` 和 Search paths 里有不有 3.9 |
| 11 | **Pyright 不认 `Field()` 的位置参数默认值**:`x: int = Field(3, ge=1, le=10)` 会被判成「必填」,凡是不传该参数的调用点全报 `Arguments missing for parameters`;`Field(default=3, ...)` 才认。运行期 pydantic 两边等价(否则测试早红了),纯静态判定差异 | schema 里一律写 `Field(default=..., ...)`;排查手法是写最小复现(一个 pydantic 模型 + 一次构造)确认到底是哪边的问题 |
## 8. 仓库事实(速查)
@@ -112,6 +117,6 @@ docker compose up -d douyu-login
| 本地服务 | `./dev.sh`(8800 端口,`--reload`);**启动时会自动跑迁移** |
| 本地 MySQL | 容器 `live-hub-py-mysql-1`,端口 3307;库见 §4 |
| 生产镜像库 | `douyu_login_prod`(`scripts/refresh_local_prod_mirror.sh` 同步,只读用) |
| 迁移 head | `main` = `20261004_0051`;`dev` = `20261007_0052`(**两侧不一致,切分支前先对齐库**) |
| 迁移 head | `main` = `20261008_0052`;`dev` = `20261008_0053`(**两侧不一致,切分支前先对齐库**)。这行会过期,动手前用 `git ls-tree -r --name-only <ref> web/backend/migrations/versions/` 自己算一遍 head(没被任何 `down_revision` 引用的那个) |
| 前端 | `tsc -b` 开了 `noUnusedLocals`,死代码/未用导入直接报 TS6133;镜像构建时会 `npm run build` |
| 测试 | `pytest tests/ -q`(用 `douyu_login_test`);`ruff format` + `ruff check` |
+5 -1
View File
@@ -145,6 +145,7 @@ uv run --group dev pytest # 或 ./dev.sh test
uv run --group dev pytest tests/test_cookie_operations.py
./dev.sh format tests conftest.py
./dev.sh format-check tests conftest.py
./dev.sh lint-check tests conftest.py
./dev.sh type-check # 渐进式 Pyright
docker compose --profile test run --rm test
```
@@ -168,9 +169,12 @@ docker compose --profile test run --rm test
./dev.sh frontend-check # 单独跑前端 TypeScript
```
- **pre-commit**:暂存的 Python 文件做 Ruff 格式检查;改了 `web/frontend/` 则跑 `tsc -b`
- **pre-commit**:暂存的 Python 文件做 Ruff 格式检查 **+ `ruff check` lint**;改了 `web/frontend/` 则跑 `tsc -b`
- **pre-push**:上述检查 + 全量 pytest
- Pyright 默认不开(噪音大):`TYPECHECK=1 git push`
—— 注意 `pyrightconfig.json` 已钉死 `.venv`/Python 3.12;**没有这段配置时 pyright 会去
摸 macOS 自带的 Python 3.9**,读成 SQLAlchemy 1.4 并凭空多报约 2600 条假错(2926 vs 273)。
若在 IDE 里看到成片「Mapped 不是泛型 / 联合类型需要 3.10+」,先查解释器有没有选对。
- 紧急绕过:`git push --no-verify` 或 `SKIP_TESTS=1 git push`
## 技术栈
+47 -7
View File
@@ -31,6 +31,7 @@ import struct
import time
import uuid
from collections.abc import Mapping
from typing import Literal, overload
from urllib.parse import parse_qs, quote, urlparse
import requests
@@ -245,7 +246,7 @@ def solve_safe_auth(
k: v[0]
for k, v in parse_qs(urlparse(risk_url).query, keep_blank_values=True).items()
}
app_id = str(q.get("appId") or "5002")
app_id = q.get("appId") or "5002"
last_err: Exception | None = None
for attempt in range(max_retry):
solver = HuyaVerificationSolver(
@@ -293,6 +294,42 @@ def parse_real_uid(resp: bytes) -> int:
raise HuyaAppLoginError("无法从登录响应解析真实 UID")
@overload
def login_cred_with_flow(
account: str,
password: str,
max_rounds: int = ...,
device_info: dict | None = ...,
proxies: dict | None = ...,
include_device_token: Literal[False] = ...,
sms_url: str = ...,
) -> tuple[bytes, int]: ...
@overload
def login_cred_with_flow(
account: str,
password: str,
max_rounds: int = ...,
device_info: dict | None = ...,
proxies: dict | None = ...,
include_device_token: Literal[True] = ...,
sms_url: str = ...,
) -> tuple[bytes, int, str]: ...
@overload
def login_cred_with_flow(
account: str,
password: str,
max_rounds: int = ...,
device_info: dict | None = ...,
proxies: dict | None = ...,
include_device_token: bool = ...,
sms_url: str = ...,
) -> tuple[bytes, int] | tuple[bytes, int, str]: ...
def login_cred_with_flow(
account: str,
password: str,
@@ -405,7 +442,11 @@ class QrRole:
self.req_counter = random.randint(40_000_000, 41_000_000)
self.s.headers.update(
{
"User-Agent": UA_PC if pc else mobile_user_agent(device_info),
"User-Agent": (
UA_PC
if pc or device_info is None
else mobile_user_agent(device_info)
),
"Origin": UDB_BASE,
"content-type": "application/json;charset=UTF-8",
"Accept": "*/*",
@@ -550,8 +591,7 @@ class HuyaAppPasswordLogin:
jar = session.cookies
if hasattr(jar, "items"):
pairs = [
(str(key), "" if value is None else str(value))
for key, value in jar.items()
(key, "" if value is None else value) for key, value in jar.items()
]
else:
pairs = [
@@ -576,13 +616,13 @@ class HuyaAppPasswordLogin:
raw_cred = (
base64.urlsafe_b64encode(cred).decode("ascii").rstrip("=")
if isinstance(cred, bytes)
else str(cred or "")
else (cred or "")
)
# 本次登录/指纹响应明确返回的字段,必须覆盖旧 Session 值。
set_value("udb_cred", raw_cred, overwrite=True)
if uid:
set_value("udb_uid", int(uid), overwrite=True)
set_value("yyuid", int(uid), overwrite=True)
set_value("udb_uid", uid, overwrite=True)
set_value("yyuid", uid, overwrite=True)
set_value("udb_biztoken", biztoken, overwrite=True)
set_value("udb_version", "1.0", overwrite=True)
set_value("udb_origin", "0", overwrite=True)
+23 -6
View File
@@ -136,11 +136,18 @@ def launch(
proc = subprocess.Popen(
args, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, text=True
)
# 上面用的是 stderr=PIPE,所以 proc.stderr 一定不是 None(静态类型是
# IO[str] | None)。收一次窄,顺便在真拿不到 stderr 时给出明确报错。
stderr = proc.stderr
if stderr is None:
proc.kill()
raise RuntimeError("Chrome stderr 未接通,无法读取调试端口")
ws_url = None
deadline = time.time() + 20
last_probe_error: Exception | None = None
while time.time() < deadline:
# 1) 从 DevTools 输出的 ws url(browser 级)
line = proc.stderr.readline()
line = stderr.readline()
if "DevTools listening on" in line:
browser_ws = line.strip().split(" ")[-1]
else:
@@ -151,23 +158,33 @@ def launch(
f"http://127.0.0.1:{port}/json/list", timeout=2
) as resp:
targets = json.load(resp)
pages = {
# 必须是 list 而不是 set:下面要按下标取「第一个」page target,
# set 不可下标。这里曾写成集合推导式,pages[0] 抛出的 TypeError
# 被下面的宽 except 吞掉,于是每次都静默退回 browser 级 endpoint,
# 页面级探测长期失效却无人察觉。回归用例:
# tests/test_huya_browser_harvest.py::test_launch_prefers_page_target_over_browser_endpoint
pages = [
t
for t in targets
if t.get("type") == "page" and t.get("webSocketDebuggerUrl")
}
]
if pages:
ws_url = pages[0]["webSocketDebuggerUrl"]
break
except Exception: # noqa: BLE001, S110 - 端口未就绪时轮询重试
pass
except Exception as exc: # noqa: BLE001 - 端口未就绪时轮询重试
# 不静默:记下最后一次探测异常,端口最终没起来时一并报出来,
# 避免「代码 bug」被读成「端口没起来」。
last_probe_error = exc
# 3) 兜底:browser 级 endpoint
if browser_ws:
ws_url = browser_ws
break
if not ws_url:
proc.kill()
raise RuntimeError("Chrome 调试端口未就绪")
detail = (
f";最后一次 CDP 探测异常: {last_probe_error!r}" if last_probe_error else ""
)
raise RuntimeError(f"Chrome 调试端口未就绪{detail}")
return proc, ws_url
+7 -1
View File
@@ -35,7 +35,13 @@ class HuyaEliteWssSession:
self.logger = logger or (lambda _message: None)
self.http = HuyaHttpClient(logger=self.logger)
self.loop = asyncio.new_event_loop()
self.client: HuyaWssClient | None = None
# 会话内**始终**持有 client:下面(本函数的 try 之前)无条件创建,
# close() 只置 self._closed,从不把它改回 None。原先标成 `| None = None`
# 是陈旧声明,代价是 20 处 `self.client.xxx(...)` 全被报「可能为 None」。
# 顺带说明:_run() 里 `self.client is None` 这条兜底因此是死代码 ——
# 而且它本来就被求值顺序绕过(`self.client.xxx()` 作为实参先于 _run 执行),
# 保留它只为防御未来有人真的把 client 置空。
self.client: HuyaWssClient
self._closed = False
if kind == "activity":
+1 -1
View File
@@ -172,7 +172,7 @@ class CaptchaCaptureRecord:
dtu_bytes: bytes,
puzzle_bytes: bytes,
restored_bg_bytes: bytes | None = None,
angle: int | float | None = None,
angle: float | None = None,
raw_data: dict[str, Any] | None = None,
) -> Path:
"""捕获旋转验证码的所有图片和元数据。"""
+24 -14
View File
@@ -6,6 +6,7 @@ import base64
import io
import json
import random
import re
import time
import uuid
from collections.abc import Mapping
@@ -15,7 +16,6 @@ from pathlib import Path
from typing import Any, cast
from urllib.parse import parse_qs, quote, urlparse
import re
import cv2
import execjs
import numpy as np
@@ -65,7 +65,7 @@ def _cookie_mapping(cookie: Mapping[str, str] | str | None) -> dict[str, str]:
parsed = SimpleCookie()
parsed.load(cookie)
return {key: morsel.value for key, morsel in parsed.items()}
return {str(key): str(value) for key, value in cookie.items()}
return {key: value for key, value in cookie.items()}
class HuyaVerificationSolver:
@@ -214,7 +214,7 @@ class HuyaVerificationSolver:
background = cv2.cvtColor(cv2.Canny(background, 100, 200), cv2.COLOR_GRAY2RGB)
result = cv2.matchTemplate(background, target, cv2.TM_CCOEFF_NORMED)
_, _, _, max_loc = cv2.minMaxLoc(result)
return int(max_loc[0])
return max_loc[0]
@staticmethod
def _opencv_rotate_angle(
@@ -331,7 +331,10 @@ class HuyaVerificationSolver:
if Path(font_path).is_file():
try:
return ImageFont.truetype(font_path, size)
except Exception:
except OSError:
# 字体文件在、但 FreeType 打不开或格式不对(实测「cannot open
# resource」和「unknown file format」都是 OSError)—— 换下一个候选。
# 收窄异常类型:宽 except 会把参数写错之类的真 bug 一起吞掉。
continue
return ImageFont.load_default()
@@ -627,7 +630,7 @@ class HuyaVerificationSolver:
restored_bg, tip_bytes, int(data.get("location_y") or 0)
)
slider_box = self.ocr.ocr_slider_box(composite)
yolo_x = int(slider_box[0] - 13)
yolo_x = slider_box[0] - 13
opencv_x = self._opencv_slider_x(tip_bytes, restored_bg)
if abs(opencv_x - yolo_x) < 10:
logger.debug("虎牙滑块识别距离: yolo={}, opencv={}", yolo_x, opencv_x)
@@ -666,7 +669,7 @@ class HuyaVerificationSolver:
if tip_bytes:
merged = self._vertical_concat_align_left(bg_bytes, tip_bytes)
points = self.ocr.ocr_click_points(merged)
final_points = [[int(x), int(y) - 44] for x, y in points]
final_points = [[x, y - 44] for x, y in points]
else:
question = str(data.get("question") or "")
target_chars = self._extract_target_chars_from_question(question)
@@ -675,7 +678,7 @@ class HuyaVerificationSolver:
synth_tip = self._synthesize_text_tip(target_chars)
merged = self._vertical_concat_align_left(bg_bytes, synth_tip)
points = self.ocr.ocr_click_points(merged)
final_points = [[int(x), int(y) - 44] for x, y in points]
final_points = [[x, y - 44] for x, y in points]
tip_bytes = synth_tip
else:
logger.info(f"虎牙点选题目未能提取明确目标字: {question}")
@@ -699,11 +702,11 @@ class HuyaVerificationSolver:
drag_distance = max(5, int((angle / 360.0) * 260))
track_points = generate_slide_track(drag_distance)
act_data = {
"point": int(round(angle)),
"point": round(angle),
"travel": format_track(track_points),
"code": self.code,
"sceneType": self.scene_type,
"endTime": int(track_points[-1][-1]) - int(track_points[0][-1]),
"endTime": track_points[-1][-1] - track_points[0][-1],
}
act = self.js_ctx.call("get_act", act_data, self.huyapk)
self.behavior_events.append(
@@ -726,11 +729,11 @@ class HuyaVerificationSolver:
def _send_slider_verify(self, url: str, point: int) -> dict:
track_points = generate_slide_track(point)
act_data = {
"point": int(point),
"point": point,
"travel": format_track(track_points),
"code": self.code,
"sceneType": self.scene_type,
"endTime": int(track_points[-1][-1]) - int(track_points[0][-1]),
"endTime": track_points[-1][-1] - track_points[0][-1],
}
act = self.js_ctx.call("get_act", act_data, self.huyapk)
self.behavior_events.append(
@@ -759,7 +762,7 @@ class HuyaVerificationSolver:
current_time = start_time
for point in points:
current_time += random.randint(1000, 2000)
click_data.append([int(point[0]), int(point[1]), current_time])
click_data.append([point[0], point[1], current_time])
interval_time_list = [item[-1] for item in click_data]
act_data = {
@@ -958,11 +961,18 @@ class HuyaVerificationSolver:
or "/auth/xz/" in vurl
or "rotate" in self.strategy_url
):
last_result = self._send_rotate_verify(vurl, float(point))
if isinstance(point, (int, float)):
last_result = self._send_rotate_verify(vurl, float(point))
else:
logger.warning(f"旋转验证识别返回非数值结果: {point}")
continue
elif isinstance(point, list):
last_result = self._send_click_verify(vurl, point)
elif point is not None:
last_result = self._send_slider_verify(vurl, point)
else:
last_result = self._send_slider_verify(vurl, int(point))
logger.warning("验证码识别未返回有效结果")
continue
if isinstance(last_result, dict) and (
last_result.get("authId") or last_result.get("nextAuthUrl")
+1 -1
View File
@@ -56,7 +56,7 @@ class WupRequest:
os.write_struct(0, struct_data)
elif isinstance(struct_data, dict):
os.write_struct_begin(0)
for tag_id, (field_name, field_value) in enumerate(struct_data.items()):
for tag_id, (_, field_value) in enumerate(struct_data.items()):
self._write_field(os, tag_id, field_value)
os.write_struct_end()
elif isinstance(struct_data, (list, tuple)):
+6
View File
@@ -96,6 +96,12 @@ if [ "${1:-}" = "format-check" ]; then
exec uv run --group dev python -m ruff format --check "$@"
fi
# 与 format-check 分开:ruff format 不查未使用导入/未排序导入/宽 except 这类问题。
if [ "${1:-}" = "lint-check" ]; then
shift
exec uv run --group dev python -m ruff check "$@"
fi
if [ "${1:-}" = "type-check" ]; then
shift
exec uv run --group dev python -m pyright "$@"
+4
View File
@@ -41,6 +41,10 @@ packages = ["core", "utils", "web"]
[tool.pytest.ini_options]
testpaths = ["tests"]
[tool.ruff.lint]
select = ["E4", "E7", "E9", "F", "B", "I", "BLE"]
ignore = ["E402", "E731", "E741", "B904", "B905"]
[tool.ruff.lint.per-file-ignores]
# FastAPI evaluates dependency metadata in route parameter defaults by design.
"web/backend/**/*.py" = ["B008"]
+22 -2
View File
@@ -1,5 +1,6 @@
{
"include": ["core", "utils", "web", "tests"],
// tests/ 有意**不**做类型检查(见下方说明),所以不放进 include。
"include": ["core", "utils", "web"],
"exclude": [
"**/__pycache__",
"artifacts",
@@ -10,5 +11,24 @@
],
"typeCheckingMode": "basic",
"reportMissingImports": "none",
"reportMissingModuleSource": "none"
"reportMissingModuleSource": "none",
// 必须显式钉死解释器:否则 pyright 会去 PATH 上摸 /usr/bin/python3(macOS 自带 3.9),
// 读到用户级 ~/Library/Python/3.9 里的 SQLAlchemy 1.4 + 把语义版本当日 3.9,
// 凭空多出约 2600 条假错(详见 pyright --verbose 的 "Assuming Python version")。
"venvPath": ".",
"venv": ".venv",
"pythonVersion": "3.12",
// ── 为什么 tests/ 不做类型检查 ───────────────────────────────────────────
// 打开 tests 会多出约 119 条,且**全部是同一类噪音**,不是测试写错了:
// 1) FastAPI 路由函数没有(也不该有)返回值注解,pyright 只能从 return
// 字面量反推成一个很窄的 dict 类型,于是 `result["items"][0]` 报
// 「No overloads for __getitem__」;给路由补注解=给 FastAPI 加了
// response_model,会真的裁剪响应体,绝不能为了消警告去加。
// 2) 测试故意传 `db=None` 走 mock 分支,而形参注解是 Session。
// 3) `resp.json()` 静态类型是 object,下标取值必然报错。
// 这三类要么得改生产签名、要么得在测试里撒 cast/ignore,属于 AGENTS.md 说的
//「没人要的重构」。测试的正确性本来就由 pytest **真跑一遍**来保证,而
// 未定义名/未用导入已由 `ruff check`(含 F 系列)覆盖。
// 要临时把 tests 也检查一遍:把 "tests" 加回上面的 include 再跑
// `./dev.sh type-check`,看完记得改回来。
}
+215
View File
@@ -0,0 +1,215 @@
"""账号登录失败分类统计、筛选与多选导出测试。
涵盖:
1. `list_accounts` 携带 `failure_kind` 筛选;
2. `AccountOut` 序列化包含 `relogin_failure_kind`、`relogin_failure_label`、`relogin_last_error`;
3. `accounts_summary` 聚合返回 `login_failures` 分类统计;
4. `POST /api/accounts/export` 导出纯文本账号名单 (txt) 与结构化报表 (csv);
5. `must_bind_mobile` 自动分型与进入人工态判定。
"""
from __future__ import annotations
import csv
import io
from tests.support.db import get_test_engine, make_test_session
from web.backend.models import Account, User
from web.backend.routers.accounts import (
accounts_summary,
export_accounts,
list_accounts,
)
from web.backend.schemas import AccountExportRequest
from web.backend.services.account_lifecycle import STATUS_MANUAL, derive_status
from web.backend.services.login_failure import classify_failure, failure_kind_label
class TestAccountFailureClassificationAndExport:
def setup_method(self):
self.engine = get_test_engine()
self.session = make_test_session(self.engine)
self.admin = User(
username="fail-admin", password_hash="h", role="super_admin", is_active=True
)
self.support = User(
username="fail-support", password_hash="h", role="support", is_active=True
)
self.session.add_all([self.admin, self.support])
self.session.commit()
def teardown_method(self):
self.session.close()
def _create_account(self, name: str, **kwargs) -> Account:
acc = Account(
username=name,
password="pwd",
email=f"{name}@test.com",
email_password="epwd",
cookie=kwargs.pop("cookie", "acf_uid=123"),
ck_check_status=kwargs.pop("ck_check_status", "valid"),
**kwargs,
)
self.session.add(acc)
self.session.commit()
return acc
def test_classify_must_bind_mobile(self):
"""测试必须绑定手机号分型判定。"""
assert (
classify_failure("跳过手机号绑定失败: 必须绑定手机号") == "must_bind_mobile"
)
assert classify_failure("登录失败: 必须绑定手机号") == "must_bind_mobile"
assert (
classify_failure(
"重新登录失败: 跳过手机号绑定失败: 必须绑定手机号(旧 Cookie 已保留)"
)
== "must_bind_mobile"
)
assert failure_kind_label("must_bind_mobile") == "必须绑定手机号"
# 验证 must_bind_mobile 在 CK 失效时被 derive_status 推导为 manual 待人工
acc = Account(
username="bind_test",
password="p",
email="e@e.com",
email_password="ep",
cookie="c",
ck_check_status="invalid",
relogin_failure_kind="must_bind_mobile",
relogin_attempts=1,
)
assert derive_status(acc) == STATUS_MANUAL
def test_classify_account_canceled_or_banned(self):
"""测试账号已注销/封禁/冻结归入凭证/账号异常问题。"""
assert (
classify_failure(
"重新登录失败: 第二次登录失败: 账号已注销(旧 Cookie 已保留)"
)
== "credential"
)
assert classify_failure("第二次登录失败: 账号已注销") == "credential"
assert classify_failure("登录失败: 该账号已被封禁") == "credential"
assert classify_failure("账号已冻结,请联系客服") == "credential"
def test_list_accounts_filter_by_failure_kind_and_serialization(self):
"""测试按 failure_kind 筛选与 AccountOut 序列化包含失败字段。"""
self._create_account(
"acc_mobile",
relogin_failure_kind="must_bind_mobile",
relogin_last_error="跳过手机号绑定失败: 必须绑定手机号",
)
self._create_account(
"acc_captcha",
relogin_failure_kind="captcha",
relogin_last_error="极验验证码拦截",
)
self._create_account("acc_normal", relogin_failure_kind="")
# 1. 筛选 must_bind_mobile
res_mobile = list_accounts(
failure_kind="must_bind_mobile",
page=1,
page_size=20,
db=self.session,
current=self.admin,
)
assert res_mobile["total"] == 1
item = res_mobile["items"][0]
assert item.username == "acc_mobile"
# 检查 Pydantic 序列化 (防静默丢字段)
dumped = item.model_dump()
assert dumped["relogin_failure_kind"] == "must_bind_mobile"
assert dumped["relogin_failure_label"] == "必须绑定手机号"
assert "必须绑定手机号" in dumped["relogin_last_error"]
# 2. 筛选 captcha
res_captcha = list_accounts(
failure_kind="captcha",
page=1,
page_size=20,
db=self.session,
current=self.admin,
)
assert res_captcha["total"] == 1
assert res_captcha["items"][0].username == "acc_captcha"
def test_accounts_summary_login_failures_aggregation(self):
"""测试 accounts_summary 接口聚合各错误分类统计。"""
self._create_account("acc_m1", relogin_failure_kind="must_bind_mobile")
self._create_account("acc_m2", relogin_failure_kind="must_bind_mobile")
self._create_account("acc_c1", relogin_failure_kind="captcha")
self._create_account("acc_q1", relogin_failure_kind="email_quota")
self._create_account("acc_norm", relogin_failure_kind="")
summary = accounts_summary(db=self.session, current=self.admin)
assert "login_failures" in summary
failures = summary["login_failures"]
assert failures.get("must_bind_mobile") == 2
assert failures.get("captcha") == 1
assert failures.get("email_quota") == 1
def test_export_accounts_txt_format(self):
"""测试导出纯账号名名单 (txt)。"""
acc1 = self._create_account("user_alpha", tag="VIP")
acc2 = self._create_account("user_beta", tag="VIP")
self._create_account("user_gamma", tag="OTHER")
# 1. 显式 ID 多选导出
req1 = AccountExportRequest(
account_ids=[acc1.id, acc2.id],
format="txt",
)
resp1 = export_accounts(req1, db=self.session, current=self.admin)
assert resp1.media_type.startswith("text/plain")
body1 = resp1.body.decode("utf-8")
assert body1.split("\n") == ["user_alpha", "user_beta"]
# 2. 按筛选条件全选导出 (all_matching=True)
req2 = AccountExportRequest(
all_matching=True,
tag="VIP",
format="txt",
)
resp2 = export_accounts(req2, db=self.session, current=self.admin)
body2 = resp2.body.decode("utf-8")
assert body2.split("\n") == ["user_alpha", "user_beta"]
def test_export_accounts_csv_format(self):
"""测试导出完整明细报表 (csv,带 BOM 和中文分型)。"""
acc = self._create_account(
"user_csv_test",
points=500,
gold_balance=10,
tag="TEST_TAG",
relogin_failure_kind="must_bind_mobile",
relogin_last_error="跳过手机号绑定失败: 必须绑定手机号",
assigned_to=self.support.id,
)
req = AccountExportRequest(
account_ids=[acc.id],
format="csv",
)
resp = export_accounts(req, db=self.session, current=self.admin)
assert resp.media_type.startswith("text/csv")
content = resp.body.decode("utf-8")
assert content.startswith("\ufeff") # 校验 UTF-8 BOM
reader = csv.reader(io.StringIO(content.lstrip("\ufeff")))
rows = list(reader)
header = rows[0]
assert "账号" in header
assert "登录异常分类" in header
assert "最新报错" in header
assert "归属客服" in header
data_row = rows[1]
assert data_row[0] == "user_csv_test"
assert data_row[2] == "必须绑定手机号"
assert "必须绑定手机号" in data_row[3]
assert data_row[4] == "TEST_TAG"
assert data_row[5] == "fail-support"
+1 -1
View File
@@ -19,7 +19,7 @@ from web.backend.models import (
from web.backend.services import account_pool as pool
from web.backend.services.automation.jobs import account_lease_reaper as reaper
NOW = datetime(2026, 10, 7, 12, 0, 0, tzinfo=UTC)
NOW = datetime.now(UTC).replace(microsecond=0)
class _ReaperBase:
+2 -1
View File
@@ -2052,7 +2052,8 @@ class TestHighValueAccountFilters:
def test_null_high_value_owned_not_treated_as_both_available(self):
"""high_value_owned 为 None 的账号(如被重置过),绝不能误判为双套均可兑换。"""
from datetime import datetime, UTC
from datetime import UTC, datetime
from web.backend.models import Account
from web.backend.routers.accounts import accounts_summary
+1 -1
View File
@@ -19,7 +19,7 @@ from tests.support.db import get_test_engine, make_test_session
from web.backend.models import Account, AccountEvent, AccountLease, DouyuTask, User
from web.backend.services import account_pool as pool
NOW = datetime(2026, 10, 7, 10, 0, 0, tzinfo=UTC)
NOW = datetime.now(UTC).replace(microsecond=0)
COMMODITY = "20260120QYOOB_bag10"
+6 -3
View File
@@ -454,8 +454,9 @@ class TestPointsExpireJob(_Base):
def test_expired_points_are_recorded_once(self):
from datetime import timedelta
now = datetime.now(UTC)
self.account.points = 500
self.account.points_expire_at = NOW - timedelta(days=1)
self.account.points_expire_at = now - timedelta(days=1)
self.session.commit()
out = self._run()
@@ -472,8 +473,9 @@ class TestPointsExpireJob(_Base):
def test_not_yet_expired_is_left_alone(self):
from datetime import timedelta
now = datetime.now(UTC)
self.account.points = 500
self.account.points_expire_at = NOW + timedelta(days=3)
self.account.points_expire_at = now + timedelta(days=3)
self.session.commit()
assert self._run()["written"] == 0
@@ -484,8 +486,9 @@ class TestPointsExpireJob(_Base):
"""积分已经为 0 就没有东西可到期 —— 写一条 -0 只是噪声。"""
from datetime import timedelta
now = datetime.now(UTC)
self.account.points = 0
self.account.points_expire_at = NOW - timedelta(days=1)
self.account.points_expire_at = now - timedelta(days=1)
self.session.commit()
out = self._run()
+26
View File
@@ -140,6 +140,32 @@ class TestDouyuGoldRechargeChannel:
assert channel == {"gold_recharge_channel": "supplier_api"}
def test_update_config_switching_recharge_channel_and_peace_enabled(self):
from web.backend.routers.douyu import update_config
from web.backend.schemas import DouyuConfigUpdate
admin_user = self.session.get(User, self.task.created_by)
# 1. 切换到 supplier_api
req = DouyuConfigUpdate(
gold_recharge_channel="supplier_api",
peace_enabled=True,
)
res = update_config(req, db=self.session, current=admin_user)
dumped = res.model_dump()
assert dumped["gold_recharge_channel"] == "supplier_api"
assert dumped["peace_enabled"] is True
# 2. 切换回 wechat_qr
req2 = DouyuConfigUpdate(
gold_recharge_channel="wechat_qr",
peace_enabled=False,
)
res2 = update_config(req2, db=self.session, current=admin_user)
dumped2 = res2.model_dump()
assert dumped2["gold_recharge_channel"] == "wechat_qr"
assert dumped2["peace_enabled"] is False
def test_recharge_audit_detail_includes_safe_account_identity(self):
record_audit(
self.session,
+23 -2
View File
@@ -101,13 +101,33 @@ class TestSupply(_ApiBase):
def test_unsupported_scope_is_400(self):
with pytest.raises(HTTPException) as exc:
pool_router.pool_supply(
scope="peace",
scope="unknown_scope",
commodity_id=COMMODITY,
db=self.session,
current=self.support,
)
assert exc.value.status_code == 400
def test_peace_scope_supply(self):
from web.backend.models import DouyuXpdGoodsSnapshot
xpd_item = DouyuXpdGoodsSnapshot(
commodity_id="xpd_bag_1",
name="和平礼包",
price=8800,
)
self.session.add(xpd_item)
self.session.commit()
supply = pool_router.pool_supply(
scope="peace",
commodity_id="xpd_bag_1",
db=self.session,
current=self.support,
)
assert supply["commodity"]["name"] == "和平礼包"
assert supply["commodity"]["score"] == 8800
class TestExchange(_ApiBase):
def _patch_runner(self, monkeypatch, captured: list):
@@ -151,6 +171,7 @@ class TestExchange(_ApiBase):
assert task.task_type == "exchange_goods"
assert task.handbook_scope == "elite"
assert task.batch_id == result.batch_id
assert task.result is not None
assert task.result["payload"]["commodity_id"] == COMMODITY
assert task.result["payload"]["num"] == 1
@@ -208,8 +229,8 @@ class TestExchange(_ApiBase):
assert result.allocated == 1
tasks = self.session.query(DouyuTask).order_by(DouyuTask.id.asc()).all()
assert [t.task_type for t in tasks] == [
"query_elite_status",
"query_gold_balance",
"query_points",
"create_gold_qr",
"donate_elite_gift",
"exchange_goods",
+120
View File
@@ -0,0 +1,120 @@
"""虎牙「短信接码一键登录」端点:调用契约与成功/失败两条分支。
背景(这是本文件的**存在理由**,别删):该端点曾引用一个从来不存在的
``core.huya.auto_register.auto_register_huya_phone``(git 全历史都没有 ``def``),
所以每次调用都在 import 阶段抛 ``ImportError`` → HTTP 500,且因为导入写在函数体
内部,静态检查之外没有任何东西拦得住它。用例锁死「端点必须调用真实存在的
``register_huya_with_sms_line``」这个契约,名字再被改就不会静默回归。
"""
import pytest
from fastapi import HTTPException
from core.huya.auto_register import HuyaAutoRegisterResult
from tests.support.db import get_test_engine, make_test_session
from web.backend.models import HuyaAccount, User
from web.backend.routers.huya.login import auto_sms_login_account
# 能被 parse_huya_cookie_line 认出来的最小虎牙 CK(含 yyuid= / udb_uid=)。
LOGIN_COOKIE = "yyuid=100; udb_uid=100"
def _ok_result(item, **kwargs):
return HuyaAutoRegisterResult(
phone=item.phone,
provider=item.provider,
success=True,
status="success",
message="接码成功",
cookie=LOGIN_COOKIE,
)
class TestAutoSmsLoginAccount:
def setup_method(self):
self.engine = get_test_engine()
self.session = make_test_session(self.engine)
self.user = User(username="operator", password_hash="hash", role="super_admin")
self.account = HuyaAccount(
uid="",
yyuid="",
cookie="",
game_phone="13800000000",
sms_url="https://sms.example.com/get?p=1",
)
self.session.add_all([self.user, self.account])
self.session.commit()
def teardown_method(self):
self.session.close()
def _call(self):
return auto_sms_login_account(
self.account.id, db=self.session, current=self.user
)
def test_calls_existing_register_helper_and_saves_cookie(self, monkeypatch):
"""核心契约:必须调用真实存在的注册函数,并把返回的 CK 回填落库。"""
calls: dict = {}
def fake_register(item, **kwargs):
calls["item"] = item
calls["kwargs"] = kwargs
return _ok_result(item, **kwargs)
# 用字符串形式 patch 目标模块属性:端点内部是 `from ... import ...`,
# 每次调用都会重新取模块属性,所以这层 patch 必须生效。
monkeypatch.setattr(
"core.huya.auto_register.register_huya_with_sms_line", fake_register
)
out = self._call()
assert out["success"] is True
# 断言序列化结果,不看属性(AGENTS.md 坑 #2)
assert out["account"].model_dump()["uid"] == "100"
assert calls["item"].phone == "13800000000"
assert calls["item"].url == "https://sms.example.com/get?p=1"
# 超时/轮询间隔是端点的既有行为,不能被顺手改掉
assert calls["kwargs"]["wait_seconds"] == 90
assert calls["kwargs"]["poll_interval"] == 2
self.session.refresh(self.account)
assert self.account.status == "active"
assert self.account.login_channel == "sms"
assert "udb_uid=100" in self.account.cookie
def test_failure_marks_account_login_failed(self, monkeypatch):
"""注册失败要落库成 login_failed 并返回 502,而不是假装成功。"""
def fake_register(item, **kwargs):
return HuyaAutoRegisterResult(
phone=item.phone,
provider=item.provider,
success=False,
status="failed",
message="接码平台超时",
)
monkeypatch.setattr(
"core.huya.auto_register.register_huya_with_sms_line", fake_register
)
with pytest.raises(HTTPException) as excinfo:
self._call()
assert excinfo.value.status_code == 502
assert "接码平台超时" in str(excinfo.value.detail)
self.session.refresh(self.account)
assert self.account.status == "login_failed"
def test_missing_phone_or_sms_url_is_rejected_before_import(self):
"""缺手机号/接码链接要在调用注册前 400,不能先崩在 import 上。"""
self.account.game_phone = ""
self.session.commit()
with pytest.raises(HTTPException) as excinfo:
self._call()
assert excinfo.value.status_code == 400
+49
View File
@@ -1,3 +1,5 @@
import io
import json
from pathlib import Path
from core.huya import browser_harvest
@@ -51,3 +53,50 @@ def test_launch_can_show_window_when_requested(monkeypatch):
browser_harvest.launch(Path("/tmp/test-huya-profile"), 9556, headless=False)
assert "--headless=new" not in calls[0]
def test_launch_prefers_page_target_over_browser_endpoint(monkeypatch):
"""页面级 ws 必须优先于 browser 级(Network 域只能挂在 page target 上)。
这里原本写的是 ``pages[0]``,而 ``pages`` 是集合推导出来的 **set** ——
``set`` 不可下标,抛出的 TypeError 又被外层 ``except Exception: pass``
吞掉,于是每次都退回 browser 级 endpoint:页面级探测**从来没有成功过一次**,
而且没有任何日志能看出来。这就是本用例存在的意义。
"""
page_ws = "ws://127.0.0.1/devtools/page/PAGE"
browser_ws = "ws://127.0.0.1/devtools/browser/test"
payload = json.dumps([{"type": "page", "webSocketDebuggerUrl": page_ws}])
monkeypatch.setattr(
browser_harvest.subprocess, "Popen", lambda args, **kwargs: _FakeProcess()
)
# _FakeProcess.stderr 会给出 browser 级 endpoint,用来证明「选中了页面级」
monkeypatch.setattr(
browser_harvest.urllib.request,
"urlopen",
lambda *args, **kwargs: io.StringIO(payload),
)
_proc, ws_url = browser_harvest.launch(Path("/tmp/test-huya-profile"), 9557)
assert ws_url == page_ws
assert ws_url != browser_ws
def test_launch_falls_back_to_browser_endpoint_without_page_target(monkeypatch):
"""没有 page target 时才允许退回 browser 级 endpoint。"""
browser_ws = "ws://127.0.0.1/devtools/browser/test"
payload = json.dumps([{"type": "service_worker", "webSocketDebuggerUrl": "ws://x"}])
monkeypatch.setattr(
browser_harvest.subprocess, "Popen", lambda args, **kwargs: _FakeProcess()
)
monkeypatch.setattr(
browser_harvest.urllib.request,
"urlopen",
lambda *args, **kwargs: io.StringIO(payload),
)
_proc, ws_url = browser_harvest.launch(Path("/tmp/test-huya-profile"), 9558)
assert ws_url == browser_ws
+1 -1
View File
@@ -26,7 +26,7 @@ TESTS_DIR = Path(__file__).resolve().parent
PROJECT_ROOT = TESTS_DIR.parent
VERSIONS_DIR = PROJECT_ROOT / "web" / "backend" / "migrations" / "versions"
HEAD_REVISION = "20261007_0052"
HEAD_REVISION = "20261008_0053"
# 迁移新增、但不声明在模型里的复合查询索引。
EXTRA_INDEXES = (
+3 -2
View File
@@ -28,12 +28,13 @@ class TestBuildSupplyChain:
assert chain[0].payload == {"commodity_id": "C1", "num": 1}
def test_tier_b_refreshes_before_spending(self):
"""链首必须先刷余额 —— 否则 `_skip_when` 读的是旧值,会多充钱。"""
"""链首必须先查开通状态与余额 —— 否则未开通会误充值,旧值会多充钱。"""
chain = pool.build_supply_chain(self._candidate(300), commodity_id="C1")
assert [s.task_type for s in chain][:2] == [
"query_elite_status",
"query_gold_balance",
"query_points",
]
assert chain[0].payload == {"require_opened": True}
def test_tier_b_topup_amount_is_exact_gap(self):
# 缺口 980 分 → 98 个令 → 98 元
@@ -0,0 +1,73 @@
"""同步历史重登失败分型:根据最新 classify_failure 规则刷正 accounts 和 login_tasks
## 背景
新增了「必须绑定手机号」与「账号注销/封禁」分型,历史已存在报错文案的账号需要回写正确的 failure_kind,
使「登录异常一键筛选」与列表角标统计准确。
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from web.backend.services.login_failure import classify_failure
revision: str = "20261008_0052"
down_revision: str | None = "20261004_0051"
branch_labels: str | None = None
depends_on: str | None = None
def upgrade() -> None:
conn = op.get_bind()
# 1. 查询 accounts 中有 relogin_last_error 的记录
rows = conn.execute(
sa.text(
"SELECT id, relogin_last_error, relogin_failure_kind "
"FROM accounts "
"WHERE relogin_last_error IS NOT NULL AND relogin_last_error != ''"
)
).fetchall()
for row in rows:
acc_id, err_text, current_kind = row[0], row[1], row[2]
new_kind = classify_failure(err_text)
if new_kind and new_kind != current_kind:
conn.execute(
sa.text("UPDATE accounts SET relogin_failure_kind = :k WHERE id = :id"),
{"k": new_kind, "id": acc_id},
)
# 2. 查询 login_tasks 中有 message 的记录
# 检查 login_tasks 是否有 relogin_failure_kind 列
col_exists = conn.execute(
sa.text(
"SELECT COUNT(*) FROM information_schema.columns "
"WHERE table_schema = DATABASE() "
"AND table_name = 'login_tasks' AND column_name = 'relogin_failure_kind'"
)
).scalar()
if col_exists:
task_rows = conn.execute(
sa.text(
"SELECT id, message, relogin_failure_kind "
"FROM login_tasks "
"WHERE message IS NOT NULL AND message != ''"
)
).fetchall()
for row in task_rows:
task_id, msg, current_kind = row[0], row[1], row[2]
new_kind = classify_failure(msg)
if new_kind and new_kind != current_kind:
conn.execute(
sa.text(
"UPDATE login_tasks SET relogin_failure_kind = :k WHERE id = :id"
),
{"k": new_kind, "id": task_id},
)
def downgrade() -> None:
pass
@@ -25,8 +25,8 @@ from __future__ import annotations
import sqlalchemy as sa
from alembic import op
revision: str = "20261007_0052"
down_revision: str | None = "20261004_0051"
revision: str = "20261008_0053"
down_revision: str | None = "20261008_0052"
branch_labels: str | None = None
depends_on: str | None = None
+163 -18
View File
@@ -1,8 +1,8 @@
"""账号管理路由"""
import csv
import io
from typing import Any
from fastapi import APIRouter, Depends, HTTPException, Query
from fastapi import APIRouter, Depends, HTTPException, Query, Response
from sqlalchemy import and_, case, func, or_, select, text
from sqlalchemy.orm import Session, defer, joinedload
@@ -24,6 +24,7 @@ from ..schemas import (
AccountAutomationUpdate,
AccountBulkSelection,
AccountBulkTag,
AccountExportRequest,
AccountImport,
AccountLifecycleUpdate,
AccountOut,
@@ -56,7 +57,6 @@ from ..services.account_lifecycle import (
set_manual_state,
)
from ..services.account_service import (
cookie_account_ids_query,
parse_and_build_accounts,
)
from ..services.account_value import (
@@ -69,6 +69,7 @@ from ..services.account_value import (
)
from ..services.audit_service import record_account_action, record_audit
from ..services.douyu_service import cookie_holding_filter
from ..services.login_failure import classify_failure, failure_kind_label
router = APIRouter(prefix="/api/accounts", tags=["账号管理"])
@@ -104,6 +105,10 @@ def _query_str(value) -> str:
return value.strip() if isinstance(value, str) else ""
def _query_bool(value) -> bool:
return value is True
def _filter_accounts_query(
db: Session,
query,
@@ -117,6 +122,7 @@ def _filter_accounts_query(
search: str = "",
status: str = "",
ck_status: str = "",
failure_kind: str = "",
bind_status: str = "",
high_value_filter: str = "",
min_points: int | None = None,
@@ -128,9 +134,9 @@ def _filter_accounts_query(
role_bind_status: str = "",
):
"""复用列表筛选条件,供分页列表和全量批量操作保持一致。"""
if has_cookie:
query = query.filter(Account.id.in_(cookie_account_ids_query(db)))
if assigned_only and user_has_permission(current, "account:view_all"):
if _query_bool(has_cookie):
query = query.filter(Account.cookie.isnot(None), Account.cookie != "")
if _query_bool(assigned_only) and user_has_permission(current, "account:view_all"):
query = query.filter(Account.assigned_to.isnot(None))
# 归属筛选:未分配 / 已分配,再叠加「指定客服」。与其它条件(标签、CK、
# 搜索…)是**同时生效**的,这正是「综合筛选」的用法。
@@ -155,6 +161,9 @@ def _filter_accounts_query(
ck_value = _query_str(ck_status)
if ck_value:
query = query.filter(Account.ck_check_status == ck_value)
fk_value = _query_str(failure_kind)
if fk_value:
query = query.filter(Account.relogin_failure_kind == fk_value)
bind_value = _query_str(bind_status)
if bind_value:
# 三个作用域任一命中即算(列表上「绑定」是一列,不分开筛)
@@ -252,6 +261,7 @@ def _selected_account_ids(
search=req.search,
status=req.status,
ck_status=req.ck_status,
failure_kind=req.failure_kind,
bind_status=req.bind_status,
high_value_filter=req.high_value_filter,
min_points=req.min_points,
@@ -405,6 +415,10 @@ def list_accounts(
ck_status: str = Query(
"", description="按 CK 健康结论筛选:valid / invalid / error"
),
failure_kind: str = Query(
"",
description="按最近登录失败分型筛选:must_bind_mobile/captcha/credential/email_code/email_quota/network",
),
bind_status: str = Query(
"", description="按角色绑定筛选:unknown/unbound/pending/bound"
),
@@ -445,6 +459,7 @@ def list_accounts(
search=search,
status=status,
ck_status=ck_status,
failure_kind=failure_kind,
bind_status=bind_status,
high_value_filter=high_value_filter,
min_points=min_points,
@@ -565,6 +580,12 @@ def list_accounts(
result = []
for acc in accounts:
eff_kind = acc.relogin_failure_kind or ""
if acc.relogin_last_error:
refined = classify_failure(acc.relogin_last_error)
if not eff_kind or (eff_kind == "network" and refined != "network"):
eff_kind = refined
item = AccountOut(
id=acc.id,
username=acc.username,
@@ -577,6 +598,9 @@ def list_accounts(
status_label=STATUS_LABELS.get(acc.status or "", acc.status or ""),
status_reason=acc.status_reason or "",
auto_managed=bool(acc.auto_managed),
relogin_failure_kind=eff_kind,
relogin_failure_label=failure_kind_label(eff_kind),
relogin_last_error=acc.relogin_last_error or "",
# 关键列:全部是 accounts 行上的字段,无 JOIN / 无聚合
has_cookie=bool(acc.cookie),
ck_check_status=acc.ck_check_status or "",
@@ -646,6 +670,19 @@ def accounts_summary(
)
by_status = {str(row[0] or ""): int(row[1] or 0) for row in status_rows}
visible_total = sum(by_status.values())
# 登录失败分型统计(不含空值与归档)
failure_rows = (
visible.filter(
Account.relogin_failure_kind != "",
Account.relogin_failure_kind.isnot(None),
)
.with_entities(Account.relogin_failure_kind, func.count(Account.id))
.group_by(Account.relogin_failure_kind)
.all()
)
login_failures = {str(row[0] or ""): int(row[1] or 0) for row in failure_rows}
# 高价值及核心资产分布(单次聚合,供前端快捷胶囊展示)
bairimeng_expr = suit_owned_expr(Account.high_value_owned, SUIT_BAIRIMENG)
mengtu_expr = suit_owned_expr(Account.high_value_owned, SUIT_MENGTU)
@@ -681,6 +718,8 @@ def accounts_summary(
"visible_total": visible_total,
# 生命周期分布(键是 6 状态的枚举值)
"by_status": by_status,
# 登录异常分类统计
"login_failures": login_failures,
# 高价值与核心资产统计
"high_value": high_value_summary,
# 需要人关注的:CK 已被判失效的账号数(含待人工)
@@ -702,6 +741,99 @@ def accounts_summary(
}
@router.post("/export")
def export_accounts(
req: AccountExportRequest,
db: Session = Depends(get_db),
current: User = Depends(get_current_user),
):
"""导出账号:支持纯文本账号名单(txt)或完整详情(csv)。"""
selected_ids = _selected_account_ids(db, current, req)
if not selected_ids:
if req.format == "csv":
content = "\ufeff账号,生命周期状态,登录异常分类,最新报错,标签,归属客服,鱼翅,积分,精英宝典,电竞手册,CK状态,备注\n"
return Response(
content=content,
media_type="text/csv; charset=utf-8",
headers={"Content-Disposition": 'attachment; filename="accounts.csv"'},
)
return Response(
content="",
media_type="text/plain; charset=utf-8",
headers={"Content-Disposition": 'attachment; filename="accounts.txt"'},
)
accounts = (
db.query(Account)
.options(joinedload(Account.assigned_user))
.filter(Account.id.in_(selected_ids))
.order_by(Account.id.asc())
.all()
)
if req.format == "txt":
# 纯账号名字,换行分隔
lines = [acc.username for acc in accounts if acc.username]
text_content = "\n".join(lines)
return Response(
content=text_content,
media_type="text/plain; charset=utf-8",
headers={"Content-Disposition": 'attachment; filename="accounts.txt"'},
)
# 导出 CSV (带 UTF-8 BOM,防止 Excel 打开乱码)
output = io.StringIO()
writer = csv.writer(output)
writer.writerow(
[
"账号",
"生命周期状态",
"登录异常分类",
"最新报错",
"标签",
"归属客服",
"鱼翅",
"积分",
"精英宝典",
"电竞手册",
"CK状态",
"备注",
]
)
for acc in accounts:
eff_kind = acc.relogin_failure_kind or ""
if acc.relogin_last_error:
refined = classify_failure(acc.relogin_last_error)
if not eff_kind or (eff_kind == "network" and refined != "network"):
eff_kind = refined
writer.writerow(
[
acc.username or "",
STATUS_LABELS.get(acc.status or "", acc.status or ""),
failure_kind_label(eff_kind) if eff_kind else "",
acc.relogin_last_error or "",
acc.tag or "",
acc.assigned_user.username if acc.assigned_user else "未分配",
acc.gold_balance if acc.gold_balance is not None else "",
acc.points if acc.points is not None else "",
"已开通"
if acc.elite_opened is True
else ("未开通" if acc.elite_opened is False else "未知"),
"已开通"
if acc.esports_opened is True
else ("未开通" if acc.esports_opened is False else "未知"),
acc.ck_check_status or "",
acc.remark or "",
]
)
csv_content = "\ufeff" + output.getvalue()
return Response(
content=csv_content,
media_type="text/csv; charset=utf-8",
headers={"Content-Disposition": 'attachment; filename="accounts.csv"'},
)
@router.post("/import")
def import_accounts(
req: AccountImport,
@@ -897,30 +1029,40 @@ def assignments_summary(
current: User = Depends(require_permission("account:assign")),
):
"""分配概览:每个客服分配了多少账号(仅统计当前仍持有 CK 的账号)。"""
cookie_subq = select(Account.id).where(cookie_holding_filter())
cookie_accounts = db.query(Account).filter(Account.id.in_(cookie_subq)).subquery()
results = (
db.query(
User.id, User.username, func.count(cookie_accounts.c.id).label("count")
db.query(User.id, User.username, func.count(Account.id).label("count"))
.outerjoin(
Account,
and_(
Account.assigned_to == User.id,
Account.cookie.isnot(None),
Account.cookie != "",
),
)
.outerjoin(cookie_accounts, cookie_accounts.c.assigned_to == User.id)
.filter(User.role == "support")
.group_by(User.id, User.username)
.order_by(func.count(cookie_accounts.c.id).desc())
.order_by(func.count(Account.id).desc())
.all()
)
total_unassigned = (
db.query(func.count(cookie_accounts.c.id))
.filter(cookie_accounts.c.assigned_to.is_(None))
db.query(func.count(Account.id))
.filter(
Account.assigned_to.is_(None),
Account.cookie.isnot(None),
Account.cookie != "",
)
.scalar()
) or 0
total_assigned = sum(int(cnt or 0) for _, _, cnt in results)
total_accounts = total_assigned + total_unassigned
return {
"support_users": [
{"id": uid, "username": uname, "assigned_count": cnt}
{"id": uid, "username": uname, "assigned_count": int(cnt or 0)}
for uid, uname, cnt in results
],
"unassigned_count": total_unassigned,
"assigned_count": total_assigned,
"total_count": total_accounts,
}
@@ -1500,7 +1642,10 @@ def account_events(
.all()
}
for item in items:
item["actor_name"] = actor_names.get(item.get("actor_id"), "")
actor_id = item.get("actor_id")
item["actor_name"] = (
actor_names.get(actor_id, "") if isinstance(actor_id, int) else ""
)
return {
"items": items,
+5 -3
View File
@@ -58,10 +58,12 @@ def _audit_log_out(db: Session, row: AuditLog) -> dict:
for task, account in tasks_and_accounts:
task_result = task.result if isinstance(task.result, dict) else {}
channel = str(task_result.get("recharge_channel") or "")
# 先落到局部变量再判 isinstance:直接写
# `x.get(k) if isinstance(x.get(k), dict) else {}` 是两次独立取值,
# 类型检查器无法据此收窄,会报「可能为 None」。
raw_supplier_order = task_result.get("supplier_order")
supplier_order = (
task_result.get("supplier_order")
if isinstance(task_result.get("supplier_order"), dict)
else {}
raw_supplier_order if isinstance(raw_supplier_order, dict) else {}
)
supplier_order_id = str(
supplier_order.get("order_id")
+3 -1
View File
@@ -414,6 +414,7 @@ def _task_out(task: DouyuTask, *, include_detail: bool = False) -> DouyuTaskOut:
def _config_out(config: DouyuConfig) -> DouyuConfigOut:
text = lambda field: str(douyu_config_value(field, getattr(config, field)))
number = lambda field: int(douyu_config_value(field, getattr(config, field)))
boolean = lambda field: bool(douyu_config_value(field, getattr(config, field)))
return DouyuConfigOut(
manual_id=text("manual_id"),
rid=text("rid"),
@@ -429,6 +430,7 @@ def _config_out(config: DouyuConfig) -> DouyuConfigOut:
esports_chicken_skin_id=text("esports_chicken_skin_id"),
esports_firework_gift_id=text("esports_firework_gift_id"),
esports_firework_skin_id=text("esports_firework_skin_id"),
peace_enabled=boolean("peace_enabled"),
xpd_act_alias=text("xpd_act_alias"),
xpd_act_id=text("xpd_act_id"),
xpd_rid=text("xpd_rid"),
@@ -624,7 +626,7 @@ def update_config(
config = ensure_douyu_config(db)
changed_fields = []
for field in DOUYU_CONFIG_FIELDS:
value = getattr(req, field)
value = getattr(req, field, None)
if value is None:
continue
setattr(config, field, value.strip() if isinstance(value, str) else value)
+149 -11
View File
@@ -21,6 +21,8 @@ from typing import Any
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from core.douyu import DouyuActivityClient, DouyuActivityError
from ..database import get_db
from ..deps import require_permission
from ..models import (
@@ -28,6 +30,7 @@ from ..models import (
AccountLease,
DouyuEsportsGoodsSnapshot,
DouyuGoodsSnapshot,
DouyuXpdGoodsSnapshot,
User,
)
from ..permissions import user_has_permission
@@ -53,9 +56,12 @@ POOL_BATCH_CONCURRENCY = 1
def _goods_snapshot(db: Session, scope: str, commodity_id: str):
model = (
DouyuGoodsSnapshot if scope == pool.SCOPE_ELITE else DouyuEsportsGoodsSnapshot
)
if scope == pool.SCOPE_ELITE:
model = DouyuGoodsSnapshot
elif scope == pool.SCOPE_ESPORTS:
model = DouyuEsportsGoodsSnapshot
else:
model = DouyuXpdGoodsSnapshot
return (
db.query(model)
.filter(model.commodity_id == commodity_id)
@@ -73,14 +79,124 @@ def _require_scope(scope: str) -> str:
return scope
def _try_auto_refresh_goods(db: Session, scope: str) -> bool:
"""尝试从库内找一个有效账号刷新该作用域的商品快照。"""
acc = (
db.query(Account)
.filter(
Account.status == "active",
Account.ck_check_status == "valid",
Account.cookie.isnot(None),
Account.cookie != "",
)
.first()
)
if not acc or not acc.cookie:
return False
try:
client = DouyuActivityClient(cookie=str(acc.cookie))
cfg = ensure_douyu_config(db)
now = _utcnow()
if scope == pool.SCOPE_ELITE:
res = client.list_goods(manual_id=str(cfg.manual_id), rid=str(cfg.rid))
for raw in res.get("goods", []):
cid = str(raw.get("commodityId") or raw.get("commodity_id") or "")
if not cid:
continue
row = (
db.query(DouyuGoodsSnapshot)
.filter(DouyuGoodsSnapshot.commodity_id == cid)
.first()
)
if row is None:
row = DouyuGoodsSnapshot(commodity_id=cid)
db.add(row)
row.name = str(raw.get("commodityName") or raw.get("name") or "")
row.score = int(raw.get("score") or 0)
row.status = str(raw.get("status") or "")
row.raw = raw
row.updated_at = now
db.commit()
return True
elif scope == pool.SCOPE_ESPORTS:
res = client.list_esports_goods(
manual_id=str(cfg.esports_manual_id), rid=str(cfg.room_id)
)
for raw in res.get("goods", []):
cid = str(raw.get("commodityId") or raw.get("commodity_id") or "")
if not cid:
continue
row = (
db.query(DouyuEsportsGoodsSnapshot)
.filter(DouyuEsportsGoodsSnapshot.commodity_id == cid)
.first()
)
if row is None:
row = DouyuEsportsGoodsSnapshot(commodity_id=cid)
db.add(row)
row.name = str(raw.get("commodityName") or raw.get("name") or "")
row.score = int(raw.get("score") or 0)
row.status = str(raw.get("status") or "")
row.raw = raw
row.updated_at = now
db.commit()
return True
elif scope == "peace":
ctx = client.xpd_embed_query(
act_alias=str(cfg.xpd_act_alias), rid=str(cfg.xpd_rid)
)
embed_q = ctx.get("query") or {}
role_res = client.xpd_get_role(
embed_query=embed_q,
act_id=str(cfg.xpd_act_id),
rid=str(cfg.xpd_rid),
)
role = role_res.get("info") or {}
res = client.xpd_list_goods(
embed_query=embed_q,
act_id=str(cfg.xpd_act_id),
openid=str(role.get("game_open_id") or ""),
roleid=str(role.get("role_id") or ""),
areaid=str(acc.xpd_area_id or 1),
)
for raw in res.get("goods", []):
cid = str(raw.get("commodity_id") or raw.get("commodityId") or "")
if not cid:
continue
row = (
db.query(DouyuXpdGoodsSnapshot)
.filter(DouyuXpdGoodsSnapshot.commodity_id == cid)
.first()
)
if row is None:
row = DouyuXpdGoodsSnapshot(commodity_id=cid)
db.add(row)
row.name = str(raw.get("name") or raw.get("commodityName") or "")
row.price = int(raw.get("price") or 0)
row.org_price = int(raw.get("org_price") or 0)
row.category = str(raw.get("category") or "")
row.goods_left = raw.get("goods_left")
row.raw = raw
row.updated_at = now
db.commit()
return True
except (DouyuActivityError, OSError, ValueError, KeyError, TypeError):
db.rollback()
return False
return False
def _goods_required(db: Session, scope: str, commodity_id: str) -> int:
goods = _goods_snapshot(db, scope, commodity_id)
if goods is None:
_try_auto_refresh_goods(db, scope)
goods = _goods_snapshot(db, scope, commodity_id)
if goods is None:
raise HTTPException(
status_code=404,
detail="找不到该商品,请先在对应工作台刷新商品列表",
)
score = int(goods.score or 0)
score = int(getattr(goods, "score", None) or getattr(goods, "price", None) or 0)
if score <= 0:
raise HTTPException(status_code=400, detail="该商品没有有效积分价格,无法分配")
return score
@@ -94,9 +210,30 @@ def _is_pool_admin(current: User) -> bool:
return user_has_permission(current, "account:pool_admin")
@router.post("/refresh-goods")
def pool_refresh_goods(
scope: str = Query("elite", pattern="^(elite|esports|peace)$"),
db: Session = Depends(get_db),
current: User = Depends(require_permission("account:pool_use")),
) -> dict[str, Any]:
"""使用库内有效 CK 自动刷新商品快照。"""
ok = _try_auto_refresh_goods(db, scope)
model = (
DouyuGoodsSnapshot
if scope == pool.SCOPE_ELITE
else (
DouyuEsportsGoodsSnapshot
if scope == pool.SCOPE_ESPORTS
else DouyuXpdGoodsSnapshot
)
)
count = db.query(model).count()
return {"success": ok, "scope": scope, "count": count}
@router.get("/supply")
def pool_supply(
scope: str = Query("elite", pattern="^(elite|esports)$"),
scope: str = Query("elite", pattern="^(elite|esports|peace)$"),
commodity_id: str = Query(..., min_length=1, max_length=64),
db: Session = Depends(get_db),
current: User = Depends(require_permission("account:pool_use")),
@@ -221,9 +358,12 @@ async def pool_exchange(
)
account_ids = [lease.account_id for lease in leases]
task_type = (
"exchange_goods" if scope == pool.SCOPE_ELITE else "exchange_esports_goods"
)
if scope == pool.SCOPE_ELITE:
task_type = "exchange_goods"
elif scope == pool.SCOPE_ESPORTS:
task_type = "exchange_esports_goods"
else:
task_type = "exchange_xpd_goods"
by_id = {c.account_id: c for c in candidates}
# 补给链:A 梯队只有「兑换」一步;B 梯队是「查余额 → 充值 → 查积分 → 赠令 → 兑换」。
@@ -384,9 +524,7 @@ def list_leases(
id=row.id,
account_id=row.account_id,
username=(
accounts.get(row.account_id).username
if accounts.get(row.account_id)
else ""
accounts[row.account_id].username if row.account_id in accounts else ""
),
holder_user_id=row.holder_user_id,
holder_name=holders.get(row.holder_user_id, ""),
+13 -1
View File
@@ -544,4 +544,16 @@ def _unbind_device_accounts(accounts: list[str]) -> tuple[list[str], list[str]]:
return removed, missing
__all__ = [name for name in globals() if not name.startswith("__")]
# 运行期导出清单:显式列出「非 dunder」的全部模块级名字(**含下划线开头的内部
# helper**),因为 python 的 `import *` 只要模块定义了 `__all__` 就照单全收。
#
# ⚠️ 六个 huya 路由模块(accounts/cookies/register/workbench/login/devices)原本
# 用 `from ._common import *`,全部已改为**显式导入**。原因不是风格洁癖:pyright
# 不会执行上面的推导式,只能按 PEP 8 保守假设「下划线名不导出」,于是那 108 处
# helper 调用全被报成「未定义」—— 更糟的是,它让这 6 个模块的类型检查彻底失明
# (helper 改名/删除时静态检查一声不吭,只能等运行期 500;曾因此漏掉一个
# `ImportError` 死端点)。新增代码请一律用显式导入。
#
# 这里保留计算式 `__all__` 是为了不改动任何运行期行为:万一还有别处 `import *`,
# 行为与改造前完全一致。pyright 无法静态求值它,故就地忽略该诊断。
__all__ = [name for name in globals() if not name.startswith("__")] # pyright: ignore[reportUnsupportedDunderAll]
+47 -1
View File
@@ -2,7 +2,53 @@
from fastapi import APIRouter
from ._common import *
from ._common import (
DEFAULT_EXCHANGE_TARGET,
AccountAssign,
AccountBulkSelection,
AccountBulkTag,
AccountTag,
BatchAssign,
Depends,
HTTPException,
HuyaAccount,
HuyaBrowserExchangeRequest,
HuyaCookieImport,
HuyaPasswordAccountImport,
HuyaTask,
HuyaWorkbenchAccount,
Query,
Session,
User,
_account_out,
_account_out_light,
_can_view_huya_all,
_can_view_huya_assigned,
_can_view_huya_cookie,
_clear_huya_account_references,
_filter_huya_accounts_query,
_huya_cookie_state_map,
_huya_password_state_map,
_require_huya_perm,
_require_huya_tag_permission,
_selected_huya_account_ids,
_visible_huya_accounts_query,
browser_login_script,
cookie_pairs,
defer,
ensure_huya_config,
exchange_target_options,
exchange_target_url,
func,
get_current_user,
get_db,
huya_config_value,
import_huya_cookies,
import_huya_password_accounts,
normalize_huya_cookie,
or_,
record_audit,
)
router = APIRouter()
+24 -1
View File
@@ -2,7 +2,30 @@
from fastapi import APIRouter
from ._common import *
from ._common import (
Depends,
HTTPException,
HuyaAccount,
Query,
Session,
StreamingResponse,
User,
_can_view_huya_cookie,
_cookie_out,
_cookie_out_light,
_has_huya_perm,
_require_huya_perm,
_visible_huya_accounts_query,
csv,
defer,
get_current_user,
get_db,
io,
normalize_huya_cookie,
or_,
rebuild_web_cookie_from_raw,
record_audit,
)
router = APIRouter()
+19 -1
View File
@@ -2,7 +2,25 @@
from fastapi import APIRouter
from ._common import *
from ._common import (
_DEVICE_BINDINGS_PERMS_VIEW,
Depends,
HTTPException,
HuyaAccount,
HuyaDeviceBindingsBatchDeleteRequest,
Session,
User,
_fp_state_dir,
_load_profile_db,
_mask_hex,
_require_huya_perm,
_save_profile_db,
_unbind_device_accounts,
get_current_user,
get_db,
shutil,
user_has_permission,
)
router = APIRouter()
+42 -3
View File
@@ -4,7 +4,41 @@ import time
from fastapi import APIRouter
from ._common import *
from ._common import (
UTC,
AccountBulkSelection,
Depends,
HTTPException,
HuyaAccount,
HuyaAppLoginError,
HuyaAppPasswordLoginRequest,
HuyaAppQrAuthRequiredError,
HuyaCredentialError,
HuyaLoginError,
HuyaPasswordLoginRequest,
HuyaPasswordLoginSelectedRequest,
HuyaSmsCodeRequest,
HuyaSmsLoginRequest,
HuyaTestSmsUrlRequest,
Session,
User,
_account_out,
_can_view_huya_cookie,
_require_huya_perm,
_selected_huya_account_ids,
_visible_huya_accounts_query,
cast,
datetime,
get_current_user,
get_db,
logger,
login_huya_app_password,
login_huya_password,
login_huya_sms,
save_huya_login_cookie_to_account,
send_huya_sms_code,
upsert_huya_cookie,
)
router = APIRouter()
@@ -287,7 +321,12 @@ def auto_sms_login_account(
sms_url = (account.sms_url or "").strip()
if not phone or not sms_url:
raise HTTPException(status_code=400, detail="该账号缺少手机号或接码链接")
from core.huya.auto_register import auto_register_huya_phone
# ⚠️ 这里原来是 `auto_register_huya_phone` —— 该名字在 core.huya.auto_register
# 里**从来没存在过**(2026-09-06 起就是死的),每次调用都在 import 阶段抛
# ImportError → 500。真实函数名是 register_huya_with_sms_line,返回的
# HuyaAutoRegisterResult 同样有 .success / .cookie / .message。
# 回归用例:tests/test_huya_auto_sms_login.py
from core.huya.auto_register import register_huya_with_sms_line
from core.sms_provider import SmsLine, detect_provider
item = SmsLine(
@@ -296,7 +335,7 @@ def auto_sms_login_account(
provider=detect_provider(sms_url),
raw=f"{phone}----{sms_url}",
)
res = auto_register_huya_phone(item, wait_seconds=90, poll_interval=2)
res = register_huya_with_sms_line(item, wait_seconds=90, poll_interval=2)
if not res.success or not res.cookie:
account.status = "login_failed"
account.updated_at = datetime.now(UTC)
+21 -1
View File
@@ -2,7 +2,27 @@
from fastapi import APIRouter
from ._common import *
from ._common import (
Depends,
HTTPException,
HuyaAutoRegisterBatchOut,
HuyaAutoRegisterRequest,
HuyaAutoRegisterRetryRequest,
HuyaRegisterSuccessLogOut,
ProxyConfig,
Query,
Session,
StreamingResponse,
User,
_require_huya_perm,
export_success_logs_text,
get_current_user,
get_db,
huya_register_registry,
list_success_logs,
parse_sms_lines,
threading,
)
router = APIRouter()
+46 -1
View File
@@ -2,7 +2,52 @@
from fastapi import APIRouter
from ._common import *
from ._common import (
HUYA_CONFIG_FIELDS,
SUPPORTED_TASK_TYPES,
UTC,
Depends,
HTTPException,
HuyaBatchRunner,
HuyaConfigOut,
HuyaConfigUpdate,
HuyaGoodsOut,
HuyaGoodsSnapshot,
HuyaRechargeGoodsOut,
HuyaRechargeGoodsSnapshot,
HuyaTask,
HuyaTaskBatchRequest,
HuyaTaskOut,
HuyaWorkbench,
HuyaWorkbenchAccount,
HuyaWorkbenchAccountsUpdate,
Query,
Session,
SessionLocal,
User,
WebSocket,
WebSocketDisconnect,
_config_out,
_has_huya_perm,
_huya_task_summary,
_require_huya_batch_owner,
_require_huya_task_account_access,
_task_out,
_visible_huya_tasks_query,
_workbench_account_ids,
apply_huya_config_defaults,
asyncio,
authenticate_websocket,
cleanup_orphan_huya_tasks,
create_planned_tasks,
datetime,
ensure_huya_config,
get_db,
huya_batch_registry,
record_audit,
require_permission,
threading,
)
router = APIRouter()
+47 -30
View File
@@ -20,7 +20,7 @@ class YybTaskCreateRequest(BaseModel):
class YybLoginRequest(BaseModel):
provider: str = Field(..., pattern="^(qq|wechat)$")
timeout: int = Field(600, ge=60, le=1800)
timeout: int = Field(default=600, ge=60, le=1800)
class YybSelectionRequest(BaseModel):
@@ -28,7 +28,7 @@ class YybSelectionRequest(BaseModel):
points: int = Field(..., gt=0)
product_id: str = Field(..., min_length=1, max_length=128)
zone_id: str = Field(..., min_length=1, max_length=64)
zone_name: str = Field("", max_length=128)
zone_name: str = Field(default="", max_length=128)
role_id: str = Field(..., min_length=1, max_length=64)
role_name: str = Field(..., min_length=1, max_length=128)
@@ -91,7 +91,7 @@ class UserInfo(BaseModel):
class UserCreate(BaseModel):
username: str = Field(..., min_length=2, max_length=64)
password: str = Field(..., min_length=6, max_length=128)
role: str = Field("support", pattern="^(super_admin|operation|support)$")
role: str = Field(default="support", pattern="^(super_admin|operation|support)$")
remark: str = ""
@@ -138,6 +138,7 @@ class AccountBulkSelection(BaseModel):
has_cookie: bool = False
status: str = ""
ck_status: str = ""
failure_kind: str = ""
bind_status: str = ""
high_value_filter: str = ""
min_points: int | None = None
@@ -149,6 +150,12 @@ class AccountBulkSelection(BaseModel):
role_bind_status: str = ""
class AccountExportRequest(AccountBulkSelection):
"""账号导出请求:支持纯账号名单(txt)或结构化明细(csv)。"""
format: str = Field(default="txt", pattern="^(txt|csv)$")
class BatchAssign(AccountBulkSelection):
"""批量分配 / 取消分配。
@@ -206,6 +213,10 @@ class AccountOut(BaseModel):
status_label: str = ""
status_reason: str = ""
auto_managed: bool = True
# 登录失败分型(2026-10-07):客服排查重登/登录异常
relogin_failure_kind: str = ""
relogin_failure_label: str = ""
relogin_last_error: str = ""
# 列表页的「关键列」:全部直接来自 accounts 行,不需要任何 JOIN 或聚合
# (客服一眼要能看出「这账号能不能用、要不要我处理」)。
has_cookie: bool = False
@@ -250,6 +261,9 @@ class AccountOut(BaseModel):
"status_label": self.status_label,
"status_reason": self.status_reason,
"auto_managed": self.auto_managed,
"relogin_failure_kind": self.relogin_failure_kind,
"relogin_failure_label": self.relogin_failure_label,
"relogin_last_error": self.relogin_last_error,
"has_cookie": self.has_cookie,
"ck_check_status": self.ck_check_status,
"ck_checked_at": _isoformat(self.ck_checked_at),
@@ -281,7 +295,7 @@ class LoginBatchRequest(BaseModel):
concurrency: int = 3 # 并发数,1-10
api_strategy: str = "wgapi" # 接口策略: wgapi(新版)或 iframe(旧版备选)
mode: str = Field(
"login", pattern="^(login|check)$"
default="login", pattern="^(login|check)$"
) # login=登录取CK,check=账号状态检测
@@ -338,9 +352,9 @@ class AccountCheckBatchRequest(BaseModel):
status: str = ""
ck_status: str = ""
bind_status: str = ""
concurrency: int = Field(3, ge=1, le=10)
max_login_retries: int = Field(0, ge=0, le=50)
max_total_time: float = Field(300, ge=0, le=3600)
concurrency: int = Field(default=3, ge=1, le=10)
max_login_retries: int = Field(default=0, ge=0, le=50)
max_total_time: float = Field(default=300, ge=0, le=3600)
use_proxy: bool = False
# 登录接口策略,与登录任务同一套取值:wgapi(默认,保持原行为)或 iframe。
# 有些人只有其中一套能收到邮箱验证码,所以要能选。
@@ -432,11 +446,11 @@ class HuyaAutoRegisterRequest(BaseModel):
text: str = Field(..., min_length=1)
tag: str = ""
concurrency: int = Field(1, ge=1, le=5)
wait_seconds: float = Field(180, ge=15, le=600)
poll_interval: float = Field(5, ge=1, le=30)
password_prefix: str = Field("hy", max_length=8)
fixed_password: str = Field("", max_length=64)
concurrency: int = Field(default=1, ge=1, le=5)
wait_seconds: float = Field(default=180, ge=15, le=600)
poll_interval: float = Field(default=5, ge=1, le=30)
password_prefix: str = Field(default="hy", max_length=8)
fixed_password: str = Field(default="", max_length=64)
use_proxy: bool = False
@@ -449,12 +463,12 @@ class HuyaAutoRegisterRetryRequest(BaseModel):
- all_unfinished: 失败+未完成都跑
"""
mode: str = Field("continue", max_length=32)
concurrency: int | None = Field(None, ge=1, le=5)
wait_seconds: float | None = Field(None, ge=15, le=600)
poll_interval: float | None = Field(None, ge=1, le=30)
password_prefix: str | None = Field(None, max_length=8)
fixed_password: str | None = Field(None, max_length=64)
mode: str = Field(default="continue", max_length=32)
concurrency: int | None = Field(default=None, ge=1, le=5)
wait_seconds: float | None = Field(default=None, ge=15, le=600)
poll_interval: float | None = Field(default=None, ge=1, le=30)
password_prefix: str | None = Field(default=None, max_length=8)
fixed_password: str | None = Field(default=None, max_length=64)
use_proxy: bool | None = None
@@ -536,9 +550,9 @@ class HuyaPasswordLoginSelectedRequest(BaseModel):
assigned_only: bool = False
has_cookie: bool = False
force_new_device: bool = False
max_attempts: int = Field(2, ge=1, le=3)
interval_seconds: float = Field(8, ge=0, le=60)
retry_delay_seconds: float = Field(3, ge=0, le=30)
max_attempts: int = Field(default=2, ge=1, le=3)
interval_seconds: float = Field(default=8, ge=0, le=60)
retry_delay_seconds: float = Field(default=3, ge=0, le=30)
class HuyaDeviceBindingsBatchDeleteRequest(BaseModel):
@@ -633,7 +647,7 @@ class HuyaConfigUpdate(BaseModel):
class HuyaTaskBatchRequest(BaseModel):
account_ids: list[int]
task_type: str
handbook_scope: str = Field("legacy", pattern="^(legacy|elite)$")
handbook_scope: str = Field(default="legacy", pattern="^(legacy|elite)$")
concurrency: int = 3
payload: dict[str, Any] = Field(default_factory=dict)
@@ -646,7 +660,7 @@ class HuyaWorkbenchAccountsUpdate(BaseModel):
class HuyaBrowserExchangeRequest(BaseModel):
"""浏览器兑换的目标页选择(常量见 services/huya_exchange_targets.py)。"""
target: str | None = Field(None, pattern="^(live_room|elite|esports)$")
target: str | None = Field(default=None, pattern="^(live_room|elite|esports)$")
class HuyaTaskOut(BaseModel):
@@ -769,6 +783,7 @@ class DouyuConfigOut(BaseModel):
esports_chicken_skin_id: str = "0"
esports_firework_gift_id: str = "24767"
esports_firework_skin_id: str = "3850"
peace_enabled: bool = False
xpd_act_alias: str = "20260623KDQFH"
xpd_act_id: str = "46195"
xpd_rid: str = "9263298"
@@ -797,6 +812,7 @@ class DouyuConfigOut(BaseModel):
"esports_chicken_skin_id": self.esports_chicken_skin_id,
"esports_firework_gift_id": self.esports_firework_gift_id,
"esports_firework_skin_id": self.esports_firework_skin_id,
"peace_enabled": self.peace_enabled,
"xpd_act_alias": self.xpd_act_alias,
"xpd_act_id": self.xpd_act_id,
"xpd_rid": self.xpd_rid,
@@ -817,23 +833,24 @@ class DouyuConfigUpdate(BaseModel):
confirm_act_alias: str | None = None
legacy_act_alias: str | None = None
room_id: str | None = None
elite_amount: int | None = Field(None, ge=1)
elite_amount: int | None = Field(default=None, ge=1)
esports_manual_id: str | None = None
esports_act_alias: str | None = None
esports_amount: int | None = Field(None, ge=1)
esports_amount: int | None = Field(default=None, ge=1)
esports_chicken_gift_id: str | None = None
esports_chicken_skin_id: str | None = None
esports_firework_gift_id: str | None = None
esports_firework_skin_id: str | None = None
peace_enabled: bool | None = None
xpd_act_alias: str | None = None
xpd_act_id: str | None = None
xpd_rid: str | None = None
gold_pay_type: int | None = Field(None, ge=1, le=9)
gold_pay_type: int | None = Field(default=None, ge=1, le=9)
gold_recharge_channel: str | None = Field(
None, pattern="^(wechat_qr|supplier_api)$"
default=None, pattern="^(wechat_qr|supplier_api)$"
)
gold_api_product_id: str | None = Field(None, max_length=128)
gold_api_account_template_name: str | None = Field(None, max_length=64)
gold_api_product_id: str | None = Field(default=None, max_length=128)
gold_api_account_template_name: str | None = Field(default=None, max_length=64)
gift_id: str | None = None
skin_id: str | None = None
@@ -842,7 +859,7 @@ class DouyuTaskBatchRequest(BaseModel):
account_ids: list[int]
task_type: str
handbook_scope: str = Field(..., pattern="^(elite|esports|peace)$")
concurrency: int = Field(3, ge=1, le=10)
concurrency: int = Field(default=3, ge=1, le=10)
payload: dict[str, Any] = Field(default_factory=dict)
+1 -1
View File
@@ -71,7 +71,7 @@ AUTOMATABLE_STATES: tuple[str, ...] = DERIVED_STATES
# 重登失败分型 → 需要人工(自动重试只会加重风控 / 重试多少次都一样)。
# 放在这里而不是 job 里:`derive_status` 要用它,service 不该反过来依赖 job。
MANUAL_KINDS = frozenset({"captcha", "credential"})
MANUAL_KINDS = frozenset({"captcha", "credential", "must_bind_mobile"})
STATUS_LABELS = {
STATUS_IMPORTED: "未登录",
+9 -2
View File
@@ -32,7 +32,7 @@ from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
from ..models import Account, AccountEvent, AccountLease, DouyuTask, User
from .account_binding import SCOPE_ELITE, SCOPE_ESPORTS
from .account_binding import SCOPE_ELITE, SCOPE_ESPORTS, SCOPE_PEACE
#: 租约默认有效期(分钟)。到点由 `account_lease_reaper` 兜底回收。
DEFAULT_LEASE_TTL_MINUTES = 60
@@ -53,6 +53,7 @@ _POOL_OWNER_ROLES = ("super_admin", "operation")
_SCOPE_COLUMNS: dict[str, tuple[str, str | None]] = {
SCOPE_ELITE: ("points", "elite_opened"),
SCOPE_ESPORTS: ("esports_points", "esports_opened"),
SCOPE_PEACE: ("xpd_balance", None),
}
SUPPORTED_POOL_SCOPES = tuple(_SCOPE_COLUMNS)
@@ -635,9 +636,15 @@ def build_supply_chain(
)
]
# 检查手册开通状态与最新积分
status_step = (
SupplyStep("query_elite_status", {"require_opened": True})
if exchange_task_type == "exchange_goods"
else SupplyStep("query_points", {})
)
steps: list[SupplyStep] = [
status_step,
SupplyStep("query_gold_balance", {}),
SupplyStep("query_points", {}),
]
# 充值:余额够就跳过(闸门在执行时求值,读的是刚刷新过的账号字段)
for amount in recharge_amounts_for(candidate.topup_gifts):
@@ -41,10 +41,10 @@ from __future__ import annotations
import json
from datetime import UTC, datetime, timedelta
from typing import Any
from typing import Any, cast
from loguru import logger
from sqlalchemy import text
from sqlalchemy import CursorResult, text
from sqlalchemy.orm import Session
from ....models import AutomationJob
@@ -133,7 +133,9 @@ def _delete_batch(
),
params,
)
return int(result.rowcount or 0)
# Session.execute 的静态返回类型是 Result[Any],但 DML 语句实际拿到的是
# CursorResult(rowcount 只定义在它上面)。运行期行为不变,只是把这一点写实。
return int(cast(CursorResult[Any], result).rowcount or 0)
def run_douyu_tasks_retention(db: Session, job: AutomationJob) -> dict[str, Any]:
+4 -1
View File
@@ -291,8 +291,11 @@ class DouyuBatchRunnerCore:
current = getattr(account, column, None)
if current is None:
return ""
raw_val = rule.get("value")
if raw_val is None:
return ""
try:
target = int(rule.get("value"))
target = int(raw_val)
except (TypeError, ValueError):
return ""
if compare(int(current), target):
+15 -3
View File
@@ -117,6 +117,16 @@ class ManualMixin:
state = "已开通" if result["elite_opened"] else "未开通"
expire_text = self._format_expire_text(result["elite_expire_time"])
points = result["elite_manual_score"]
payload = self._task_payload(task)
if payload.get("require_opened") and not result["elite_opened"]:
self._mark_task(
db,
task,
"failed",
"精英宝典未开通,无法继续充值或兑换,请先开通手册",
result,
)
return
self._mark_task(
db,
task,
@@ -211,9 +221,11 @@ class ManualMixin:
account.esports_opened = manual_type is not None and manual_type >= 1
# 到期时间也落库 —— 否则界面只能显示"已开通",看不到什么时候到期
expire_raw = result.get("expire_time")
expire_int = (
int(expire_raw) if str(expire_raw or "").strip().isdigit() else None
)
# 先规整成字符串再判 isdigit:原来写 `int(expire_raw) if str(expire_raw
# or "").strip().isdigit()` —— 判的是 A、转的是 B,类型检查器收窄不了,
# 而且同一份值取了两遍。规整到一个局部变量后两个问题一起没了。
expire_text = str(expire_raw or "").strip()
expire_int = int(expire_text) if expire_text.isdigit() else None
# ⚠️ 斗鱼用 0 表示「没有到期时间」。直接存 0 的话界面会显示 1970/1/1
# (这个坑在积分到期上踩过一次,这里别再踩)。
account.esports_expire_time = (
@@ -67,9 +67,12 @@ def _match_suit_item(want: str, rows: list[dict[str, Any]]) -> dict[str, Any] |
# 优先找带「套装」前缀的
for it in rows:
cname = str(it.get("commodityName") or "").strip()
if core in cname and not any(k in cname for k in SUIT_EXCLUDE_KEYWORDS):
if "套装" in cname:
return it
if (
core in cname
and not any(k in cname for k in SUIT_EXCLUDE_KEYWORDS)
and "套装" in cname
):
return it
# 3. 兜底匹配不带排除词的项
for it in rows:
+4 -2
View File
@@ -7,7 +7,7 @@ import copy
import threading
import time
from datetime import UTC, datetime
from typing import Any
from typing import Any, Literal
from loguru import logger
from sqlalchemy.orm import Session
@@ -51,7 +51,9 @@ class HuyaBatchRunnerCore:
def stop(self):
self._stop.set()
def _open_wss_session(self, uid: int, cookie: str, kind: str):
def _open_wss_session(
self, uid: int, cookie: str, kind: Literal["activity", "shop"]
):
"""在当前任务线程创建并登记 WSS 会话,统一由 finally 回收。"""
from core.huya.elite_session import HuyaEliteWssSession
+4 -2
View File
@@ -4,7 +4,7 @@ from __future__ import annotations
import time
from datetime import UTC, datetime
from typing import TYPE_CHECKING, Any
from typing import TYPE_CHECKING, Any, Literal
from sqlalchemy.orm import Session
@@ -40,7 +40,9 @@ class RechargeMixin:
def _push_log(self, level: str, message: str) -> None: ...
def _mark_task(self, *args: Any, **kwargs: Any) -> None: ...
def _update_task_progress(self, *args: Any, **kwargs: Any) -> None: ...
def _open_wss_session(self, uid: int, cookie: str, kind: str): ...
def _open_wss_session(
self, uid: int, cookie: str, kind: Literal["activity", "shop"]
): ...
def _shop_client(self, uid: int, cookie: str): ...
@staticmethod
+23 -6
View File
@@ -24,6 +24,7 @@ from __future__ import annotations
#: 型别 → 中文标签(导出 CSV 与页面上用同一份,避免两处各写一遍漂移)。
FAILURE_KIND_LABELS: dict[str, str] = {
"must_bind_mobile": "必须绑定手机号",
"captcha": "极验/验证码拦截",
"credential": "账号凭证问题",
"email_code": "邮箱取码失败",
@@ -39,20 +40,36 @@ NOT_AN_ACCOUNT_FAULT: frozenset[str] = frozenset({"interrupted"})
def classify_failure(message: str | None) -> str:
"""把重登/登录失败消息映射成分型(见规划 §7.4.3)。
顺序很重要:「邮箱验证码发送次数已达上限」既含「验证码」也含「上限」,
必须先在 ``email_quota`` 命中,否则会被归到可重试的 ``email_code`` 上,
导致次日才该重试的账号被按小时反复撞配额。
顺序很重要:
1. 「必须绑定手机号 / 跳过手机号绑定失败」优先归入 ``must_bind_mobile``;
2. 「邮箱验证码发送次数已达上限」既含「验证码」也含「上限」,必须先在 ``email_quota`` 命中;
3. 极验滑块命中 ``captcha``。
"""
text = message or ""
if "必须绑定手机号" in text or "跳过手机号绑定失败" in text or "绑定手机" in text:
return "must_bind_mobile"
if "上限" in text or "配额" in text:
return "email_quota"
if "极验" in text or "验证" in text and "滑块" in text:
if "极验" in text or ("验证" in text and "滑块" in text):
return "captcha"
if "验证码" in text:
if "验证码" in text or "取码" in text:
return "email_code"
if "中断" in text or "已停止" in text or "任务已停止" in text:
return "interrupted"
if "密码" in text or "账号不存在" in text or "缺少密码或邮箱" in text:
if any(
k in text
for k in (
"密码",
"账号不存在",
"缺少密码或邮箱",
"注销",
"已注销",
"封禁",
"冻结",
"限制登录",
"禁止登录",
)
):
return "credential"
# 请求失败/超时/连接异常,以及未知文案:都按可重试处理。
# 宁可多给一次机会(有每日上限兜底),也不要把可能只是抖动的账号推给人工。
+4 -1
View File
@@ -27,7 +27,7 @@ from .account_events_service import (
EVENT_RELOGIN_OK,
emit,
)
from .account_lifecycle import on_ck_verdict, on_login_success
from .account_lifecycle import on_ck_verdict, on_login_success, sync_status
from .cookie_check_service import check_douyu_cookie
from .douyu_service import LOGIN_ATTEMPT_IN_FLIGHT_STATUSES
from .login_failure import classify_failure, failure_kind_label, is_account_fault
@@ -155,6 +155,9 @@ def _mark_attempt_failed(
if db is None or account is None:
# 没有会话(纯内存构造的用例)或没有账号:跳过旁路事件,绝不影响主流程。
return
account.relogin_failure_kind = kind
account.relogin_last_error = (message or "")[:512]
sync_status(db, account, occurred_at=completed_at)
emit(
db,
account_id=account.id,
@@ -71,9 +71,9 @@ full = gradient_rounded(S, RADIUS)
draw_gift(full)
base = "web/extension/huya-exchange-helper/"
for size in (128, 48):
full.resize((size, size), Image.LANCZOS).save(f"{base}icon{size}.png")
full.resize((size, size), Image.Resampling.LANCZOS).save(f"{base}icon{size}.png")
simple = gradient_rounded(512, 100)
draw_gift_simple(simple)
simple.resize((16, 16), Image.LANCZOS).save(f"{base}icon16.png")
simple.resize((16, 16), Image.Resampling.LANCZOS).save(f"{base}icon16.png")
print("icons regenerated")
+4
View File
@@ -5,6 +5,7 @@ import type {
AccountItem,
AccountBulkSelection,
AccountBulkTagRequest,
AccountExportRequest,
AccountOverview,
AssignmentsSummary,
BasicSummary,
@@ -29,6 +30,7 @@ export const accountApi = {
include_sensitive?: boolean;
status?: string;
ck_status?: string;
failure_kind?: string;
bind_status?: string;
high_value_filter?: string;
min_points?: number;
@@ -43,6 +45,8 @@ export const accountApi = {
},
) =>
api.get<PaginatedResponse<AccountItem>, PaginatedResponse<AccountItem>>('/accounts', { params }),
export: (data: AccountExportRequest) =>
api.post('/accounts/export', data, { responseType: 'blob' }),
summary: () => api.get<BasicSummary, BasicSummary>('/accounts/summary'),
import: (text: string, tag?: string) =>
api.post<MessageCountResponse, MessageCountResponse>('/accounts/import', { text, tag: tag || '' }),
+25 -3
View File
@@ -15,7 +15,7 @@ import type {
*/
export const douyuPoolApi = {
/** 不锁号地预览「能分出几个、要花多少钱」 */
supply: (scope: 'elite' | 'esports', commodityId: string) =>
supply: (scope: 'elite' | 'esports' | 'peace', commodityId: string) =>
api.get<DouyuPoolSupply, DouyuPoolSupply>('/douyu/pool/supply', {
params: { scope, commodity_id: commodityId },
}),
@@ -37,7 +37,29 @@ export const douyuPoolApi = {
api.post<{ success: boolean; released: number }, { success: boolean; released: number }>(
`/douyu/pool/leases/release-batch/${batchId}`,
),
/** 复用旧接口拿商品列表(皮肤下拉的数据源) */
goods: () => api.get<{ commodity_id: string; name: string; score: number | null }[], { commodity_id: string; name: string; score: number | null }[]>('/douyu/goods'),
/** 使用有效 CK 自动刷新远端商品快照 */
refreshGoods: (scope: 'elite' | 'esports' | 'peace' = 'elite') =>
api.post<{ success: boolean; scope: string; count: number }, { success: boolean; scope: string; count: number }>(
'/douyu/pool/refresh-goods',
null,
{ params: { scope } },
),
/** 复用接口拿商品列表(皮肤下拉的数据源,按活动 scope 分流) */
goods: async (scope: 'elite' | 'esports' | 'peace' = 'elite') => {
if (scope === 'peace') {
const list = await api.get<
{ commodity_id: string; name: string; price: number | null }[],
{ commodity_id: string; name: string; price: number | null }[]
>('/douyu/xpd-goods');
return (list || []).map((item) => ({
commodity_id: item.commodity_id,
name: item.name,
score: item.price,
}));
}
return api.get<{ commodity_id: string; name: string; score: number | null }[], { commodity_id: string; name: string; score: number | null }[]>(
scope === 'esports' ? '/douyu/esports-goods' : '/douyu/goods',
);
},
stopBatch: (batchId: string) => api.post<MessageResponse, MessageResponse>(`/douyu/stop/${batchId}`),
};
+14 -1
View File
@@ -37,6 +37,7 @@ export interface AccountBulkSelection {
has_cookie?: boolean;
status?: string;
ck_status?: string;
failure_kind?: string;
bind_status?: string;
high_value_filter?: string;
min_points?: number;
@@ -48,6 +49,10 @@ export interface AccountBulkSelection {
role_bind_status?: string;
}
export interface AccountExportRequest extends AccountBulkSelection {
format?: 'txt' | 'csv';
}
export interface AccountBulkTagRequest extends AccountBulkSelection {
tag_value: string;
}
@@ -98,6 +103,8 @@ export interface HighValueSummary {
export interface BasicSummary {
/** 生命周期状态分布(键是 6 状态枚举值);归档默认不计入 */
by_status?: Record<string, number>;
/** 登录失败分型统计 */
login_failures?: Record<string, number>;
/** 不含归档的账号数 */
visible_total?: number;
/** 高价值及核心资产统计 */
@@ -301,6 +308,10 @@ export interface AccountItem {
status_label: string;
status_reason: string;
auto_managed: boolean;
// 登录失败分型(2026-10-07)
relogin_failure_kind?: string;
relogin_failure_label?: string;
relogin_last_error?: string;
// 列表页关键列(都直接来自 accounts 行)
has_cookie: boolean;
ck_check_status: string;
@@ -326,6 +337,8 @@ export interface AccountItem {
export interface AssignmentsSummary {
support_users: SupportUserItem[];
unassigned_count: number;
assigned_count?: number;
total_count?: number;
}
export interface SupportUserItem {
@@ -1202,7 +1215,7 @@ export interface DouyuPoolAccount {
}
export interface DouyuPoolExchangeRequest {
scope: 'elite' | 'esports';
scope: 'elite' | 'esports' | 'peace';
commodity_id: string;
quantity: number;
allow_topup: boolean;
File diff suppressed because it is too large Load Diff
+186 -100
View File
@@ -1,14 +1,19 @@
import { useEffect, useState, useMemo } from 'react';
import { useEffect, useState, useCallback } from 'react';
import {
Card, Table, Button, Select, Input, Tag, Row, Col, Statistic,
Space, Tabs, Typography, Badge, theme,
Space, Tabs, Typography, Badge, theme, Tooltip,
} from 'antd';
import { message } from '../utils/antdMessage';
import {
UserOutlined, CheckCircleOutlined, TeamOutlined,
SwapOutlined, ClearOutlined, UsergroupAddOutlined,
} from '@ant-design/icons';
import { accountApi, type AccountItem, type SupportUserItem } from '../api/modules';
import {
accountApi,
type AccountItem,
type SupportUserItem,
type AssignmentsSummary,
} from '../api/modules';
import { getErrorMessage } from '../utils/error';
const { Text } = Typography;
@@ -17,13 +22,19 @@ const STORAGE_KEY_SELECTED_USER = 'assignments_selected_user_id';
export default function AssignmentsPage() {
const { token } = theme.useToken();
const [accounts, setAccounts] = useState<AccountItem[]>([]);
const [summary, setSummary] = useState<AssignmentsSummary | null>(null);
const [supportUsers, setSupportUsers] = useState<SupportUserItem[]>([]);
const [selectedUser, setSelectedUser] = useState<SupportUserItem | null>(null);
const [allTags, setAllTags] = useState<string[]>([]);
// 表格分页与筛选状态
const [pagedAccounts, setPagedAccounts] = useState<AccountItem[]>([]);
const [totalCount, setTotalCount] = useState(0);
const [tableLoading, setTableLoading] = useState(false);
const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]);
const [searchText, setSearchText] = useState('');
const [filterTag, setFilterTag] = useState<string | undefined>(undefined);
const [activeTab, setActiveTab] = useState('unassigned');
const [activeTab, setActiveTab] = useState<'unassigned' | 'assigned'>('unassigned');
const [assigning, setAssigning] = useState(false);
const [pageSize, setPageSize] = useState(() => {
const v = localStorage.getItem('assignment_page_size');
@@ -31,83 +42,86 @@ export default function AssignmentsPage() {
});
const [currentPage, setCurrentPage] = useState(1);
// 加载分配概览
const loadSummary = async () => {
// 加载分配概览统计
const loadSummary = useCallback(async () => {
try {
const data = await accountApi.assignmentsSummary();
setSummary(data);
setSupportUsers(data.support_users);
return data.support_users;
} catch (e: unknown) {
message.error(getErrorMessage(e));
return [];
}
};
}, []);
// 加载账号(仅已成功登录过的)
const loadAccounts = async () => {
// 加载标签列表
const loadTags = useCallback(async () => {
try {
const all = await accountApi.list({ has_cookie: true, include_sensitive: false });
setAccounts(all);
const tags = await accountApi.listTags();
setAllTags(tags);
} catch {
// 忽略标签加载异常
}
}, []);
// 分页按需加载账号(服务端过滤与分页)
const loadPagedAccounts = useCallback(async () => {
setTableLoading(true);
try {
const params: Parameters<typeof accountApi.listPaged>[0] = {
page: currentPage,
page_size: pageSize,
has_cookie: true,
include_sensitive: false,
search: searchText.trim() || undefined,
tag: filterTag || undefined,
};
if (activeTab === 'unassigned') {
params.assign_status = 'unassigned';
} else if (selectedUser) {
params.assigned_user_id = selectedUser.id;
}
const data = await accountApi.listPaged(params);
setPagedAccounts(data.items);
setTotalCount(data.total);
} catch (e: unknown) {
message.error(getErrorMessage(e));
} finally {
setTableLoading(false);
}
};
}, [activeTab, selectedUser, currentPage, pageSize, searchText, filterTag]);
// 初始化加载 + 自动选中客服
// 初始化加载
useEffect(() => {
const init = async () => {
loadAccounts();
loadTags();
const users = await loadSummary();
if (users.length > 0) {
const savedId = localStorage.getItem(STORAGE_KEY_SELECTED_USER);
const savedUser = savedId ? users.find((u: SupportUserItem) => u.id === Number(savedId)) : null;
const savedUser = savedId ? users.find((u) => u.id === Number(savedId)) : null;
setSelectedUser(savedUser || users[0]);
}
};
init();
}, []);
}, [loadSummary, loadTags]);
// 标签列表
const allTags = useMemo(() => {
const tags = [...new Set(accounts.map((a) => (a.tag || '').trim()).filter(Boolean))];
return tags.sort();
}, [accounts]);
// 未分配账号
const unassignedAccounts = useMemo(() => {
return accounts.filter((a) => !a.assigned_to);
}, [accounts]);
// 当前选中客服的已分配账号
const assignedAccounts = useMemo(() => {
if (!selectedUser) return [];
return accounts.filter((a) => a.assigned_to === selectedUser.id);
}, [accounts, selectedUser]);
// 当前显示的账号集合
const displayAccounts = useMemo(() => {
let list = activeTab === 'unassigned' ? unassignedAccounts : assignedAccounts;
if (searchText) {
const s = searchText.toLowerCase();
list = list.filter((a) => a.username.toLowerCase().includes(s));
}
if (filterTag) {
list = list.filter((a) => (a.tag || '').trim() === filterTag);
}
return list;
}, [activeTab, unassignedAccounts, assignedAccounts, searchText, filterTag]);
// 当筛选或选中客服变化时触发分页请求
useEffect(() => {
loadPagedAccounts();
}, [loadPagedAccounts]);
// 切换客服
const handleSelectUser = (user: SupportUserItem) => {
setSelectedUser(user);
setSelectedRowKeys([]);
setActiveTab('unassigned');
setSearchText('');
setFilterTag(undefined);
setCurrentPage(1);
localStorage.setItem(STORAGE_KEY_SELECTED_USER, String(user.id));
};
// 批量分配
// 批量分配选中账号
const handleBatchAssign = async () => {
if (selectedRowKeys.length === 0) {
message.warning('请先选择账号');
@@ -122,10 +136,8 @@ export default function AssignmentsPage() {
await accountApi.batchAssign(selectedRowKeys, selectedUser.id);
message.success(`已将 ${selectedRowKeys.length} 个账号分配给 ${selectedUser.username}`);
setSelectedRowKeys([]);
await loadAccounts();
const users = await loadSummary();
const refreshed = users.find((u: SupportUserItem) => u.id === selectedUser.id);
if (refreshed) setSelectedUser(refreshed);
await loadSummary();
await loadPagedAccounts();
} catch (e: unknown) {
message.error(getErrorMessage(e));
} finally {
@@ -144,10 +156,8 @@ export default function AssignmentsPage() {
await accountApi.batchAssign(selectedRowKeys, null);
message.success(`已取消 ${selectedRowKeys.length} 个账号的分配`);
setSelectedRowKeys([]);
await loadAccounts();
const users = await loadSummary();
const refreshed = users.find((u: SupportUserItem) => u.id === selectedUser?.id);
if (refreshed) setSelectedUser(refreshed);
await loadSummary();
await loadPagedAccounts();
} catch (e: unknown) {
message.error(getErrorMessage(e));
} finally {
@@ -155,31 +165,29 @@ export default function AssignmentsPage() {
}
};
// 一键将未分配账号全部分配给选中客服
// 一键将当前未分配(含搜索/标签筛选)全部分配给选中客服
const handleAssignAllUnassigned = async () => {
if (!selectedUser) {
message.warning('请先选择客服');
return;
}
const ids = unassignedAccounts
.filter((a) => {
if (searchText && !a.username.toLowerCase().includes(searchText.toLowerCase())) return false;
if (filterTag && (a.tag || '').trim() !== filterTag) return false;
return true;
})
.map((a) => a.id);
if (ids.length === 0) {
message.info('没有未分配的账号');
if (totalCount === 0) {
message.info('当前筛选下没有未分配的账号');
return;
}
setAssigning(true);
try {
await accountApi.batchAssign(ids, selectedUser.id);
message.success(`已将 ${ids.length} 个账号分配给 ${selectedUser.username}`);
await loadAccounts();
const users = await loadSummary();
const refreshed = users.find((u: SupportUserItem) => u.id === selectedUser.id);
if (refreshed) setSelectedUser(refreshed);
const res = await accountApi.batchAssignSelection({
all_matching: true,
assign_status: 'unassigned',
tag: filterTag || undefined,
search: searchText.trim() || undefined,
assigned_to: selectedUser.id,
});
message.success(res.message || `已全部分配给 ${selectedUser.username}`);
setSelectedRowKeys([]);
await loadSummary();
await loadPagedAccounts();
} catch (e: unknown) {
message.error(getErrorMessage(e));
} finally {
@@ -187,18 +195,52 @@ export default function AssignmentsPage() {
}
};
// 统计
const assignedCount = accounts.filter((a) => !!a.assigned_to).length;
const unassignedCount = accounts.length - assignedCount;
// 统计数据
const assignedCount = summary?.assigned_count ?? 0;
const unassignedCount = summary?.unassigned_count ?? 0;
const totalAccountCount = summary?.total_count ?? (assignedCount + unassignedCount);
// 获取当前选中客服已分配总数
const currentSelectedUserAssignedCount =
(selectedUser ? supportUsers.find((u) => u.id === selectedUser.id)?.assigned_count : 0) ??
selectedUser?.assigned_count ??
0;
const columns = [
{ title: 'ID', dataIndex: 'id', width: 60 },
{ title: '用户名', dataIndex: 'username' },
{ title: 'ID', dataIndex: 'id', width: 70 },
{
title: '用户名',
dataIndex: 'username',
render: (text: string) => <Text strong>{text}</Text>,
},
{
title: '标签',
dataIndex: 'tag',
width: 100,
render: (tag: string) => tag ? <Tag color="blue">{tag}</Tag> : <Text type="secondary">-</Text>,
width: 120,
render: (tag: string) => (tag ? <Tag color="blue">{tag}</Tag> : <Text type="secondary">-</Text>),
},
{
title: '积分 / 鱼翅',
dataIndex: 'points',
width: 140,
render: (_: unknown, record: AccountItem) => (
<Space size={4}>
<span>积分 {record.points ?? '-'}</span>
<Text type="secondary" style={{ fontSize: 12 }}>
/ 鱼翅 {record.gold_balance ?? '-'}
</Text>
</Space>
),
},
{
title: '状态',
dataIndex: 'status',
width: 110,
render: (status: string, record: AccountItem) => (
<Tag color={status === 'active' ? 'green' : 'default'}>
{record.status_label || status || '-'}
</Tag>
),
},
];
@@ -208,22 +250,38 @@ export default function AssignmentsPage() {
{/* 统计卡片 */}
<Row gutter={12} style={{ flexShrink: 0 }}>
<Col span={6}>
<Card size="small"><Statistic title="总账号" value={accounts.length} prefix={<TeamOutlined />} /></Card>
</Col>
<Col span={6}>
<Card size="small">
<Statistic title="已分配" value={assignedCount} styles={{ content: { color: token.colorSuccess } }} prefix={<CheckCircleOutlined />} />
<Statistic title="总账号 (持CK)" value={totalAccountCount} prefix={<TeamOutlined />} />
</Card>
</Col>
<Col span={6}>
<Card size="small">
<Statistic title="未分配" value={unassignedCount} styles={{ content: { color: token.colorError } }} prefix={<SwapOutlined />} />
<Statistic
title="已分配"
value={assignedCount}
styles={{ content: { color: token.colorSuccess } }}
prefix={<CheckCircleOutlined />}
/>
</Card>
</Col>
<Col span={6}>
<Card size="small">
<Statistic title="客服人数" value={supportUsers.length} prefix={<UsergroupAddOutlined />} />
<Statistic
title="未分配"
value={unassignedCount}
styles={{ content: { color: token.colorError } }}
prefix={<SwapOutlined />}
/>
</Card>
</Col>
<Col span={6}>
<Card size="small">
<Statistic
title="客服人数"
value={supportUsers.length}
prefix={<UsergroupAddOutlined />}
/>
</Card>
</Col>
</Row>
@@ -236,7 +294,7 @@ export default function AssignmentsPage() {
title="客服列表"
size="small"
style={{ flex: 1, display: 'flex', flexDirection: 'column', minHeight: 0 }}
bodyStyle={{ flex: 1, overflow: 'auto', padding: '8px' }}
styles={{ body: { flex: 1, overflow: 'auto', padding: '8px' } }}
>
<div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
{supportUsers.map((user) => {
@@ -267,7 +325,14 @@ export default function AssignmentsPage() {
<UserOutlined style={{ color: token.colorPrimary }} />
<Text strong>{user.username}</Text>
</Space>
<Badge count={user.assigned_count} showZero style={{ backgroundColor: token.colorPrimary }} />
<Tooltip title={`已分配 ${user.assigned_count} 个账号`}>
<Badge
count={user.assigned_count}
overflowCount={999999}
showZero
style={{ backgroundColor: token.colorPrimary }}
/>
</Tooltip>
</div>
);
})}
@@ -290,7 +355,7 @@ export default function AssignmentsPage() {
<>
<span>已选中客服:</span>
<Tag color="blue" style={{ fontSize: 14, padding: '2px 10px' }}>
{selectedUser.username}(已分配 {selectedUser.assigned_count} 个)
{selectedUser.username}(已分配 {currentSelectedUserAssignedCount} 个)
</Tag>
</>
) : (
@@ -299,15 +364,27 @@ export default function AssignmentsPage() {
</Space>
}
style={{ flex: 1, display: 'flex', flexDirection: 'column', minHeight: 0 }}
bodyStyle={{ flex: 1, display: 'flex', flexDirection: 'column', minHeight: 0, padding: 0 }}
styles={{ body: { flex: 1, display: 'flex', flexDirection: 'column', minHeight: 0, padding: 0 } }}
>
{/* 筛选栏 */}
<div style={{ padding: '8px 16px', borderBottom: `1px solid ${token.colorBorderSecondary}`, display: 'flex', gap: 8, alignItems: 'center', flexShrink: 0 }}>
<div
style={{
padding: '8px 16px',
borderBottom: `1px solid ${token.colorBorderSecondary}`,
display: 'flex',
gap: 8,
alignItems: 'center',
flexShrink: 0,
}}
>
<Input.Search
placeholder="搜索用户名"
allowClear
value={searchText}
onChange={(e) => setSearchText(e.target.value)}
onChange={(e) => {
setSearchText(e.target.value);
setCurrentPage(1);
}}
style={{ width: 200 }}
size="small"
/>
@@ -316,7 +393,10 @@ export default function AssignmentsPage() {
showSearch
placeholder="按标签筛选"
value={filterTag}
onChange={(v) => setFilterTag(v || undefined)}
onChange={(v) => {
setFilterTag(v || undefined);
setCurrentPage(1);
}}
filterOption={(input, option) =>
String(option?.label || '').toLowerCase().includes(input.trim().toLowerCase())
}
@@ -330,17 +410,21 @@ export default function AssignmentsPage() {
<Tabs
size="small"
activeKey={activeTab}
onChange={(key) => { setActiveTab(key); setSelectedRowKeys([]); }}
onChange={(key) => {
setActiveTab(key as 'unassigned' | 'assigned');
setSelectedRowKeys([]);
setCurrentPage(1);
}}
style={{ padding: '0 16px', flexShrink: 0, marginBottom: 0 }}
items={[
{
key: 'unassigned',
label: `未分配 (${unassignedAccounts.length})`,
label: `未分配 (${unassignedCount})`,
},
{
key: 'assigned',
label: selectedUser
? `已分配给 ${selectedUser.username} (${assignedAccounts.length})`
? `已分配给 ${selectedUser.username} (${currentSelectedUserAssignedCount})`
: '已分配账号',
disabled: !selectedUser,
},
@@ -389,12 +473,14 @@ export default function AssignmentsPage() {
{/* 表格 */}
<Table
columns={columns}
dataSource={displayAccounts}
dataSource={pagedAccounts}
rowKey="id"
size="small"
loading={tableLoading}
pagination={{
current: currentPage,
pageSize,
total: totalCount,
size: 'small',
showSizeChanger: true,
showTotal: (t) => `共 ${t} 条`,
@@ -403,7 +489,7 @@ export default function AssignmentsPage() {
if (size !== pageSize) {
setPageSize(size);
localStorage.setItem('assignment_page_size', String(size));
setCurrentPage(1); // 切换 pageSize 时重置到第1页
setCurrentPage(1);
}
},
}}
@@ -411,7 +497,7 @@ export default function AssignmentsPage() {
selectedRowKeys,
onChange: (keys) => setSelectedRowKeys(keys as number[]),
}}
scroll={{ y: 'calc(100vh - 500px)' }}
scroll={{ y: 'calc(100vh - 460px)' }}
/>
</Card>
</Col>
File diff suppressed because it is too large Load Diff
@@ -253,7 +253,7 @@ export default function HuyaAssignmentsPage() {
<UserOutlined style={{ color: token.colorPrimary }} />
<Text strong>{user.username}</Text>
</Space>
<Badge count={user.assigned_count} showZero style={{ backgroundColor: token.colorPrimary }} />
<Badge count={user.assigned_count} overflowCount={999999} showZero style={{ backgroundColor: token.colorPrimary }} />
</div>
);
})}
@@ -0,0 +1,351 @@
import type { TableProps } from 'antd';
import { Space, Button, Typography, Tag, Tooltip, Select, Popconfirm } from 'antd';
import { DeleteOutlined } from '@ant-design/icons';
import type { NavigateFunction } from 'react-router-dom';
import type { AccountItem } from '../../../api/modules';
import { formatTimeShort } from '../../../utils/time';
import {
type AccountSortKey,
STATUS_TONES,
FAILURE_KIND_LABELS,
} from '../types';
const { Text } = Typography;
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>
);
}
export interface UseAccountColumnsOptions {
navigate: NavigateFunction;
sortKey: AccountSortKey | '';
sortOrder: 'ascend' | 'descend' | null;
canViewFull: boolean;
canTag: boolean;
canDelete: boolean;
canAssign: boolean;
sensitiveVisible: boolean;
tags: string[];
tagColorMap: Record<string, string>;
onOpenExchangeRecords: (record: AccountItem) => void;
onOpenAssignModal: (recordId: number) => void;
onSetTag: (accountId: number, tag: string) => void;
onDelete: (id: number) => void;
}
export function buildAccountColumns({
navigate,
sortKey,
sortOrder,
canViewFull,
canTag,
canDelete,
canAssign,
sensitiveVisible,
tags,
tagColorMap,
onOpenExchangeRecords,
onOpenAssignModal,
onSetTag,
onDelete,
}: UseAccountColumnsOptions): TableProps<AccountItem>['columns'] {
const sortProps = (key: AccountSortKey, tip?: string) => ({
key,
sorter: true,
sortOrder: sortKey === key ? sortOrder : null,
showSorterTooltip: tip ? { title: tip } : true,
});
const columns: TableProps<AccountItem>['columns'] = [
{
title: '账号',
dataIndex: 'username',
...sortProps('username'),
width: 200,
ellipsis: true,
render: (username: string, record: AccountItem) => (
<Space direction="vertical" size={0} style={{ maxWidth: '100%' }}>
<Button
type="link"
size="small"
style={{ padding: 0, maxWidth: '100%', overflow: 'hidden', textOverflow: 'ellipsis' }}
title={username}
onClick={() => navigate(`/accounts/${record.id}`)}
>
{username}
</Button>
<Text type="secondary" style={{ fontSize: 12 }}>
#{record.id}
</Text>
</Space>
),
},
{
title: '状态',
dataIndex: 'status',
...sortProps('status', '正常在前'),
width: 190,
render: (status: string, record: AccountItem) => {
const tone = STATUS_TONES[status] ?? 'default';
const ckNote = !record.has_cookie
? '无 CK'
: record.ck_check_status === 'error'
? '检测异常'
: record.ck_checked_at
? `检测 ${formatTimeShort(record.ck_checked_at)}`
: '未检测';
const fkMeta = record.relogin_failure_kind
? FAILURE_KIND_LABELS[record.relogin_failure_kind]
: null;
return (
<Space direction="vertical" size={2}>
<Space size={4} wrap>
<Tag color={tone} style={{ marginInlineEnd: 0 }}>
{record.status_label || status || '-'}
</Tag>
{record.auto_managed === false && (
<Tag color="orange" style={{ marginInlineEnd: 0 }}>
不自动
</Tag>
)}
{record.relogin_failure_kind && (
<Tooltip
title={
record.relogin_last_error
? `失败原因: ${record.relogin_last_error}`
: record.relogin_failure_label || record.relogin_failure_kind
}
>
<Tag
color={fkMeta?.color || 'red'}
style={{ marginInlineEnd: 0, cursor: 'pointer' }}
>
{record.relogin_failure_label || fkMeta?.label || record.relogin_failure_kind}
</Tag>
</Tooltip>
)}
</Space>
<Text
type={status === 'active' && record.ck_check_status === 'error' ? 'warning' : 'secondary'}
style={{ fontSize: 12 }}
>
{ckNote}
</Text>
</Space>
);
},
},
{
title: '绑定',
dataIndex: 'role_bind_status',
...sortProps('bind', '已绑定在前,先看精英,再看电竞和小店'),
width: 150,
render: (_, record: AccountItem) => {
const allUnknown = [
record.role_bind_status,
record.esports_bind_status,
record.xpd_bind_status,
].every((s) => !s || s === 'unknown');
if (allUnknown) {
const queried = Boolean(record.overview_queried_at);
return (
<Tooltip
title={
queried
? '已查询过,但斗鱼这次没给出绑定结论(既非已绑也非未绑)'
: '还没查询过绑定 —— 点工具栏「批量一键查询」'
}
>
<Text type="secondary">{queried ? '未能判定' : '未查询'}</Text>
</Tooltip>
);
}
return (
<Space size={2} wrap>
<BindChip scope="精" status={record.role_bind_status} />
<BindChip scope="电" status={record.esports_bind_status} />
<BindChip scope="店" status={record.xpd_bind_status} />
</Space>
);
},
},
{
title: '分配',
dataIndex: 'assigned_username',
width: 110,
render: (name: string | null, record: AccountItem) => {
if (name) {
return (
<Tag color="green" style={{ marginInlineEnd: 0 }}>
{name}
</Tag>
);
}
return canAssign ? (
<Button
type="link"
size="small"
style={{ padding: 0 }}
onClick={() => onOpenAssignModal(record.id)}
>
未分配
</Button>
) : (
<Text type="secondary" style={{ fontSize: 12 }}>
未分配
</Text>
);
},
},
{
title: '积分 / 鱼翅',
dataIndex: 'points',
...sortProps('points', '按积分排,没查过的在后;积分相同再看鱼翅'),
width: 120,
render: (_, record: AccountItem) => (
<Space direction="vertical" size={0}>
<Text>积分 {record.points ?? '-'}</Text>
<Text type="secondary" style={{ fontSize: 12 }}>
鱼翅 {record.gold_balance ?? '-'}
</Text>
</Space>
),
},
{
title: '高价值套装',
dataIndex: 'high_value_owned',
...sortProps('high_value', '两个都可兑换在前,未查询在后'),
width: 170,
render: (owned: string[] | null | undefined, record: AccountItem) => {
if (owned === null || owned === undefined || !record.overview_queried_at) {
return (
<Tooltip title="尚未查询高价值套装准入状态,点工具栏「批量一键查询」">
<Text type="secondary">未查询</Text>
</Tooltip>
);
}
if (owned.length === 0) {
return <Tag color="green">两个都可兑换</Tag>;
}
return (
<Space size={4} wrap>
{owned.map((n) => (
<Tag key={n} color="orange">
{n.replace(/^套装-/, '')} 已达上限
</Tag>
))}
</Space>
);
},
},
{
title: '兑换记录',
dataIndex: 'exchange_count',
...sortProps('exchange', '未兑换在前'),
width: 170,
render: (_, record: AccountItem) => {
if (!record.exchange_count) {
return <Text type="secondary">未兑换</Text>;
}
return (
<Tooltip title="点击查看全部官方兑换记录">
<div
role="button"
tabIndex={0}
style={{ cursor: 'pointer' }}
onClick={() => onOpenExchangeRecords(record)}
onKeyDown={(event) => {
if (event.key === 'Enter') onOpenExchangeRecords(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)}
{record.last_exchange_name
? ` ${record.last_exchange_name.replace(/^兑换\s*/, '')}`
: ''}
</Text>
</Space>
</div>
</Tooltip>
);
},
},
{
title: '标签',
dataIndex: 'tag',
...sortProps('tag'),
width: 190,
render: (tag: string, record: AccountItem) => {
if (canTag) {
return (
<Select
mode="tags"
maxCount={1}
allowClear
showSearch
optionFilterProp="label"
size="small"
placeholder="选择或输入标签"
style={{ width: 150 }}
value={tag ? [tag] : []}
onChange={(values) => {
const value = values.at(-1)?.trim() || '';
if (value !== tag) onSetTag(record.id, value);
}}
options={tags.map((value) => ({ value, label: value }))}
/>
);
}
return tag ? <Tag color={tagColorMap[tag]}>{tag}</Tag> : <Text type="secondary">-</Text>;
},
},
];
if (canViewFull && sensitiveVisible) {
columns.push(
{ title: '密码', dataIndex: 'password', width: 120 },
{ title: '邮箱', dataIndex: 'email' },
{ title: '邮箱密码', dataIndex: 'email_password', width: 120 },
);
}
if (canDelete) {
columns.push({
title: '操作',
width: 90,
align: 'center',
render: (_: unknown, record: AccountItem) => (
<Popconfirm title="确认删除?" onConfirm={() => onDelete(record.id)}>
<Button danger size="small" icon={<DeleteOutlined />}>
删除
</Button>
</Popconfirm>
),
});
}
return columns;
}
@@ -0,0 +1,244 @@
import { Modal, Button, Input, Select, Typography, Table, Spin, Space } from 'antd';
import type { AccountItem, AccountExchangeRecords, SupportUserItem } from '../../../api/modules';
import { EXCHANGE_SCOPES, EXCHANGE_COLUMNS } from '../types';
const { TextArea } = Input;
const { Text } = Typography;
export interface ImportModalProps {
open: boolean;
onCancel: () => void;
onOk: () => void;
importing: boolean;
importText: string;
setImportText: (val: string) => void;
importTag: string;
setImportTag: (val: string) => void;
tags: string[];
}
export function BatchImportModal({
open,
onCancel,
onOk,
importing,
importText,
setImportText,
importTag,
setImportTag,
tags,
}: ImportModalProps) {
return (
<Modal
title="批量导入账号"
open={open}
onCancel={onCancel}
onOk={onOk}
confirmLoading={importing}
okText="导入"
width={600}
>
<Text type="secondary">格式:用户名|密码|邮箱|邮箱密码|标签(可选,每行一个)</Text>
<TextArea
rows={10}
value={importText}
onChange={(e) => setImportText(e.target.value)}
placeholder={`用户名|密码|邮箱|邮箱密码|标签\n用户名|密码|邮箱|邮箱密码|标签`}
style={{ marginTop: 8 }}
/>
<div style={{ marginTop: 12 }}>
<Text type="secondary">统一标签(可选):未在行内写标签的账号将使用此标签</Text>
<Select
mode="tags"
style={{ width: '100%', marginTop: 4 }}
placeholder="输入或选择标签"
value={importTag ? [importTag] : []}
onChange={(vals) => setImportTag(vals.length > 0 ? vals[vals.length - 1] : '')}
options={tags.map((t) => ({ value: t, label: t }))}
/>
</div>
</Modal>
);
}
export interface BatchTagModalProps {
open: boolean;
onCancel: () => void;
onOk: () => void;
selectedCount: number;
selectedAllMatching: boolean;
batchTagInput: string;
setBatchTagInput: (val: string) => void;
tags: string[];
}
export function BatchTagModal({
open,
onCancel,
onOk,
selectedCount,
selectedAllMatching,
batchTagInput,
setBatchTagInput,
tags,
}: BatchTagModalProps) {
return (
<Modal
title="批量设置标签"
open={open}
onCancel={onCancel}
onOk={onOk}
okText="确定"
width={400}
>
<p>为{selectedAllMatching ? '当前筛选下' : '选中的'} {selectedCount} 个账号设置标签:</p>
<Select
mode="tags"
style={{ width: '100%' }}
placeholder="输入或选择标签"
value={batchTagInput ? [batchTagInput] : []}
onChange={(vals) => setBatchTagInput(vals.length > 0 ? vals[vals.length - 1] : '')}
options={tags.map((t) => ({ value: t, label: t }))}
/>
</Modal>
);
}
export interface BatchAssignModalProps {
open: boolean;
onCancel: () => void;
assigning: boolean;
selectedCount: number;
selectedAllMatching: boolean;
assignTargetId?: number;
setAssignTargetId: (val?: number) => void;
assignUsers: SupportUserItem[];
onBatchAssign: (target: number | null) => void;
}
export function BatchAssignModal({
open,
onCancel,
assigning,
selectedCount,
selectedAllMatching,
assignTargetId,
setAssignTargetId,
assignUsers,
onBatchAssign,
}: BatchAssignModalProps) {
return (
<Modal
title="批量分配账号"
open={open}
onCancel={onCancel}
confirmLoading={assigning}
footer={[
<Button key="cancel" onClick={onCancel}>
取消
</Button>,
<Button
key="unassign"
danger
loading={assigning}
onClick={() => onBatchAssign(null)}
>
取消分配
</Button>,
<Button
key="assign"
type="primary"
loading={assigning}
disabled={assignTargetId === undefined}
onClick={() => onBatchAssign(assignTargetId ?? null)}
>
确定分配
</Button>,
]}
width={420}
>
<p>
为{selectedAllMatching ? '当前筛选下' : '选中的'} {selectedCount} 个账号分配:
</p>
<Select
showSearch
optionFilterProp="label"
style={{ width: '100%' }}
placeholder="选择要分配给哪个客服"
value={assignTargetId}
onChange={(val) => setAssignTargetId(val ?? undefined)}
options={assignUsers.map((user) => ({
value: user.id,
label: `${user.username}(现 ${user.assigned_count} 个)`,
}))}
/>
<Text type="secondary" style={{ display: 'block', marginTop: 8, fontSize: 12 }}>
只有仍持有 CK 的账号能被分配;取消分配会清空这些账号的归属。
</Text>
</Modal>
);
}
export interface ExchangeRecordsModalProps {
exAccount: AccountItem | null;
exLoading: boolean;
exRecords: AccountExchangeRecords | null;
onClose: () => void;
}
export function ExchangeRecordsModal({
exAccount,
exLoading,
exRecords,
onClose,
}: ExchangeRecordsModalProps) {
return (
<Modal
title={
<Space>
<span>官方兑换记录</span>
{exAccount && (
<Text type="secondary" style={{ fontSize: 12, fontWeight: 'normal' }}>
{exAccount.username}
</Text>
)}
</Space>
}
open={Boolean(exAccount)}
onCancel={onClose}
footer={<Button onClick={onClose}>关闭</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>
);
}
@@ -0,0 +1,262 @@
import React from 'react';
import { Space, Select, Input, Dropdown, Button, Tooltip, Popconfirm, type MenuProps } from 'antd';
import {
FilterOutlined,
DownloadOutlined,
DownOutlined,
EyeInvisibleOutlined,
EyeOutlined,
TagOutlined,
UsergroupAddOutlined,
DeleteOutlined,
ThunderboltOutlined,
ImportOutlined,
ClearOutlined,
} from '@ant-design/icons';
import {
CK_OPTIONS,
FAILURE_KIND_OPTIONS,
BIND_OPTIONS,
} from '../types';
export interface AccountToolbarProps {
tags: string[];
tagFilter: string;
setTagFilter: (val: string) => void;
ckFilter: string;
setCkFilter: (val: string) => void;
failureKindFilter: string;
setFailureKindFilter: (val: string) => void;
bindFilter: string;
setBindFilter: (val: string) => void;
assignFilter: string;
setAssignFilter: (val: string) => void;
assignFilterOptions: Array<{ value: string; label: string }>;
searchText: string;
setSearchText: (val: string) => void;
hasAnyFilter: boolean;
onResetAllFilters: () => void;
exportMenuItems: MenuProps['items'];
exporting: boolean;
selectedCount: number;
canViewFull: boolean;
sensitiveVisible: boolean;
onToggleSensitive: () => void;
canTag: boolean;
onOpenBatchTag: () => void;
canAssign: boolean;
onOpenBatchAssign: () => void;
canDelete: boolean;
selectedAllMatching: boolean;
onBatchDelete: () => void;
selectedRowKeys: React.Key[];
batchQuerying: boolean;
onBatchOverview: () => void;
canImport: boolean;
onOpenImport: () => void;
setCurrentPage: (page: number) => void;
}
export function AccountToolbar({
tags,
tagFilter,
setTagFilter,
ckFilter,
setCkFilter,
failureKindFilter,
setFailureKindFilter,
bindFilter,
setBindFilter,
assignFilter,
setAssignFilter,
assignFilterOptions,
searchText,
setSearchText,
hasAnyFilter,
onResetAllFilters,
exportMenuItems,
exporting,
selectedCount,
canViewFull,
sensitiveVisible,
onToggleSensitive,
canTag,
onOpenBatchTag,
canAssign,
onOpenBatchAssign,
canDelete,
selectedAllMatching,
onBatchDelete,
selectedRowKeys,
batchQuerying,
onBatchOverview,
canImport,
onOpenImport,
setCurrentPage,
}: AccountToolbarProps) {
return (
<div
style={{
marginBottom: 16,
display: 'flex',
justifyContent: 'space-between',
flexWrap: 'wrap',
gap: 8,
}}
>
<h2>账号管理</h2>
<Space wrap>
<Select
allowClear
showSearch
optionFilterProp="label"
placeholder="按标签筛选"
style={{ width: 140 }}
value={tagFilter || undefined}
onChange={(val) => {
setTagFilter(val || '');
setCurrentPage(1);
}}
options={tags.map((t) => ({ value: t, label: t }))}
prefix={<FilterOutlined />}
/>
<Select
allowClear
size="small"
placeholder="按 CK 筛选"
style={{ width: 110 }}
value={ckFilter || undefined}
onChange={(val) => {
setCkFilter(val || '');
setCurrentPage(1);
}}
options={CK_OPTIONS}
/>
<Select
allowClear
size="small"
placeholder="登录异常分类"
style={{ width: 150 }}
value={failureKindFilter || undefined}
onChange={(val) => {
setFailureKindFilter(val || '');
setCurrentPage(1);
}}
options={FAILURE_KIND_OPTIONS}
/>
<Select
allowClear
size="small"
placeholder="按绑定筛选"
style={{ width: 110 }}
value={bindFilter || undefined}
onChange={(val) => {
setBindFilter(val || '');
setCurrentPage(1);
}}
options={BIND_OPTIONS}
/>
<Select
allowClear
showSearch
optionFilterProp="label"
size="small"
placeholder="按分配筛选"
style={{ width: 130 }}
value={assignFilter || undefined}
onChange={(val) => {
setAssignFilter(val || '');
setCurrentPage(1);
}}
options={assignFilterOptions}
/>
<Input.Search
allowClear
size="small"
placeholder="搜索账号/标签/备注"
style={{ width: 200 }}
value={searchText}
onChange={(e) => {
setSearchText(e.target.value);
setCurrentPage(1);
}}
/>
{hasAnyFilter && (
<Button
danger
icon={<ClearOutlined />}
onClick={onResetAllFilters}
title="清空所有筛选与搜索条件并恢复默认排序"
>
重置全部筛选
</Button>
)}
<Dropdown menu={{ items: exportMenuItems }} placement="bottomLeft">
<Button icon={<DownloadOutlined />} loading={exporting}>
导出账号 {selectedCount > 0 ? `(${selectedCount})` : ''}{' '}
<DownOutlined style={{ fontSize: 10 }} />
</Button>
</Dropdown>
{canViewFull && (
<Button
icon={sensitiveVisible ? <EyeInvisibleOutlined /> : <EyeOutlined />}
onClick={onToggleSensitive}
>
{sensitiveVisible ? '隐藏凭据' : '显示凭据'}
</Button>
)}
{canTag && (
<Button
disabled={selectedCount === 0}
icon={<TagOutlined />}
onClick={onOpenBatchTag}
>
批量打标签
</Button>
)}
{canAssign && (
<Button
disabled={selectedCount === 0}
icon={<UsergroupAddOutlined />}
onClick={onOpenBatchAssign}
>
批量分配
</Button>
)}
{canDelete && (
<Popconfirm
title={`确认删除${selectedAllMatching ? '当前筛选下' : '选中的'} ${selectedCount} 个账号?`}
description="将同时删除关联的登录任务"
onConfirm={onBatchDelete}
okText="删除"
okButtonProps={{ danger: true }}
cancelText="取消"
>
<Button danger disabled={selectedCount === 0} icon={<DeleteOutlined />}>
批量删除
</Button>
</Popconfirm>
)}
<Tooltip title="实时向斗鱼查这些账号的鱼翅/积分/开通状态/兑换记录,并标出高价值套装是否已拥有">
<Button
disabled={selectedRowKeys.length === 0}
loading={batchQuerying}
icon={<ThunderboltOutlined />}
onClick={onBatchOverview}
>
批量一键查询
</Button>
</Tooltip>
{canImport && (
<Button
type="primary"
icon={<ImportOutlined />}
onClick={onOpenImport}
>
批量导入
</Button>
)}
</Space>
</div>
);
}
@@ -0,0 +1,745 @@
import { Card, Space, Typography, Button, Tooltip, Tag, Row, Col, Select, InputNumber } from 'antd';
import { WarningOutlined, ThunderboltOutlined, UpOutlined, DownOutlined, ClearOutlined } from '@ant-design/icons';
import type { BasicSummary } from '../../../api/modules';
import { HIGH_VALUE_OPTIONS, BIND_OPTIONS } from '../types';
const { Text } = Typography;
interface FilterPanelProps {
summary: BasicSummary;
failureKindFilter: string;
setFailureKindFilter: (val: string | ((prev: string) => string)) => void;
highValueFilter: string;
setHighValueFilter: (val: string | ((prev: string) => string)) => void;
minPoints?: number;
setMinPoints: (val?: number) => void;
maxPoints?: number;
setMaxPoints: (val?: number) => void;
minGold?: number;
setMinGold: (val?: number) => void;
maxGold?: number;
setMaxGold: (val?: number) => void;
eliteOpened?: boolean;
setEliteOpened: (val?: boolean) => void;
esportsOpened?: boolean;
setEsportsOpened: (val?: boolean) => void;
roleBindStatus: string;
setRoleBindStatus: (val: string) => void;
advFilterOpen: boolean;
setAdvFilterOpen: (val: boolean | ((prev: boolean) => boolean)) => void;
hasCustomFilters: boolean;
onResetAdvancedFilters: () => void;
onResetAdvancedFiltersState: () => void;
setCurrentPage: (page: number) => void;
}
export function FilterPanel({
summary,
failureKindFilter,
setFailureKindFilter,
highValueFilter,
setHighValueFilter,
minPoints,
setMinPoints,
maxPoints,
setMaxPoints,
minGold,
setMinGold,
maxGold,
setMaxGold,
eliteOpened,
setEliteOpened,
esportsOpened,
setEsportsOpened,
roleBindStatus,
setRoleBindStatus,
advFilterOpen,
setAdvFilterOpen,
hasCustomFilters,
onResetAdvancedFilters,
onResetAdvancedFiltersState,
setCurrentPage,
}: FilterPanelProps) {
const FAILURE_CHIPS = [
{
key: 'must_bind_mobile',
label: '必须绑定手机号',
icon: '📱',
count: summary.login_failures?.must_bind_mobile ?? 0,
color: '#ff4d4f',
tooltip: '登录提示必须绑定手机号(无法免绑跳过),需人工补充手机号',
active: failureKindFilter === 'must_bind_mobile',
onClick: () => {
setFailureKindFilter((prev) => (prev === 'must_bind_mobile' ? '' : 'must_bind_mobile'));
setCurrentPage(1);
},
},
{
key: 'captcha',
label: '极验滑块拦截',
icon: '🧩',
count: summary.login_failures?.captcha ?? 0,
color: '#fa8c16',
tooltip: '遭遇极验验证码/滑块拦截,需人工辅助或切换网络',
active: failureKindFilter === 'captcha',
onClick: () => {
setFailureKindFilter((prev) => (prev === 'captcha' ? '' : 'captcha'));
setCurrentPage(1);
},
},
{
key: 'credential',
label: '账号凭证问题',
icon: '🔑',
count: summary.login_failures?.credential ?? 0,
color: '#f5222d',
tooltip: '密码错误、账号不存在或缺少密码/邮箱',
active: failureKindFilter === 'credential',
onClick: () => {
setFailureKindFilter((prev) => (prev === 'credential' ? '' : 'credential'));
setCurrentPage(1);
},
},
{
key: 'email_code',
label: '邮箱取码失败',
icon: '✉️',
count: summary.login_failures?.email_code ?? 0,
color: '#1890ff',
tooltip: '未收到邮箱验证码或 IMAP 无法收取邮件',
active: failureKindFilter === 'email_code',
onClick: () => {
setFailureKindFilter((prev) => (prev === 'email_code' ? '' : 'email_code'));
setCurrentPage(1);
},
},
{
key: 'email_quota',
label: '邮箱配额已满',
icon: '📫',
count: summary.login_failures?.email_quota ?? 0,
color: '#722ed1',
tooltip: '斗鱼限制:该账号今日邮箱验证码发送次数已达上限',
active: failureKindFilter === 'email_quota',
onClick: () => {
setFailureKindFilter((prev) => (prev === 'email_quota' ? '' : 'email_quota'));
setCurrentPage(1);
},
},
{
key: 'network',
label: '网络/未知异常',
icon: '🌐',
count: summary.login_failures?.network ?? 0,
color: '#8c8c8c',
tooltip: '网络抖动、代理超时或未知异常,可自动重试',
active: failureKindFilter === 'network',
onClick: () => {
setFailureKindFilter((prev) => (prev === 'network' ? '' : 'network'));
setCurrentPage(1);
},
},
];
const PRESET_CHIPS = [
{
key: 'both_available',
label: '双套均可换',
icon: '🌟',
count: summary.high_value?.both_available,
color: '#52c41a',
active:
highValueFilter === 'both_available' &&
minPoints === undefined &&
maxPoints === undefined &&
minGold === undefined &&
maxGold === undefined &&
eliteOpened === undefined &&
esportsOpened === undefined &&
!roleBindStatus,
onClick: () => {
if (highValueFilter === 'both_available') {
setHighValueFilter('');
} else {
onResetAdvancedFiltersState();
setHighValueFilter('both_available');
}
setCurrentPage(1);
},
},
{
key: 'can_bairimeng',
label: '可换白日梦',
icon: '👗',
count: summary.high_value?.can_bairimeng,
color: '#1677ff',
active:
highValueFilter === 'can_bairimeng' &&
minPoints === undefined &&
maxPoints === undefined &&
minGold === undefined &&
maxGold === undefined &&
eliteOpened === undefined &&
esportsOpened === undefined &&
!roleBindStatus,
onClick: () => {
if (highValueFilter === 'can_bairimeng') {
setHighValueFilter('');
} else {
onResetAdvancedFiltersState();
setHighValueFilter('can_bairimeng');
}
setCurrentPage(1);
},
},
{
key: 'can_mengtu',
label: '可换萌兔',
icon: '🐰',
count: summary.high_value?.can_mengtu,
color: '#722ed1',
active:
highValueFilter === 'can_mengtu' &&
minPoints === undefined &&
maxPoints === undefined &&
minGold === undefined &&
maxGold === undefined &&
eliteOpened === undefined &&
esportsOpened === undefined &&
!roleBindStatus,
onClick: () => {
if (highValueFilter === 'can_mengtu') {
setHighValueFilter('');
} else {
onResetAdvancedFiltersState();
setHighValueFilter('can_mengtu');
}
setCurrentPage(1);
},
},
{
key: 'high_points',
label: '积分≥300',
icon: '💎',
count: summary.high_value?.high_points,
color: '#fa8c16',
active:
minPoints === 300 &&
maxPoints === undefined &&
!highValueFilter &&
minGold === undefined &&
maxGold === undefined &&
eliteOpened === undefined &&
esportsOpened === undefined &&
!roleBindStatus,
onClick: () => {
if (minPoints === 300) {
setMinPoints(undefined);
} else {
onResetAdvancedFiltersState();
setMinPoints(300);
}
setCurrentPage(1);
},
},
{
key: 'has_gold',
label: '有鱼翅',
icon: '💰',
count: summary.high_value?.has_gold,
color: '#faad14',
active:
minGold === 0.01 &&
maxGold === undefined &&
!highValueFilter &&
minPoints === undefined &&
maxPoints === undefined &&
eliteOpened === undefined &&
esportsOpened === undefined &&
!roleBindStatus,
onClick: () => {
if (minGold === 0.01) {
setMinGold(undefined);
} else {
onResetAdvancedFiltersState();
setMinGold(0.01);
}
setCurrentPage(1);
},
},
{
key: 'elite_opened',
label: '宝典已开通',
icon: '📜',
count: summary.high_value?.elite_opened,
color: '#13c2c2',
active:
eliteOpened === true &&
!highValueFilter &&
minPoints === undefined &&
maxPoints === undefined &&
minGold === undefined &&
maxGold === undefined &&
esportsOpened === undefined &&
!roleBindStatus,
onClick: () => {
if (eliteOpened === true) {
setEliteOpened(undefined);
} else {
onResetAdvancedFiltersState();
setEliteOpened(true);
}
setCurrentPage(1);
},
},
{
key: 'high_value_broken',
label: '高价值待救',
icon: '⚠️',
count: summary.high_value?.high_value_broken,
color: '#f5222d',
tooltip: '两套还能换、只剩一套,或积分≥300,且 CK 已失效',
active:
highValueFilter === 'high_value_broken' &&
minPoints === undefined &&
maxPoints === undefined &&
minGold === undefined &&
maxGold === undefined &&
eliteOpened === undefined &&
esportsOpened === undefined &&
!roleBindStatus,
onClick: () => {
if (highValueFilter === 'high_value_broken') {
setHighValueFilter('');
} else {
onResetAdvancedFiltersState();
setHighValueFilter('high_value_broken');
}
setCurrentPage(1);
},
},
{
key: 'unqueried',
label: '未查资料',
icon: '🔍',
count: summary.high_value?.unqueried,
color: '#8c8c8c',
active:
highValueFilter === 'unqueried' &&
minPoints === undefined &&
maxPoints === undefined &&
minGold === undefined &&
maxGold === undefined &&
eliteOpened === undefined &&
esportsOpened === undefined &&
!roleBindStatus,
onClick: () => {
if (highValueFilter === 'unqueried') {
setHighValueFilter('');
} else {
onResetAdvancedFiltersState();
setHighValueFilter('unqueried');
}
setCurrentPage(1);
},
},
];
return (
<Card
size="small"
style={{ marginBottom: 12, borderRadius: 6 }}
styles={{ body: { padding: '8px 12px' } }}
>
{/* 登录异常分类一键筛选 */}
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
flexWrap: 'wrap',
gap: 8,
paddingBottom: 8,
marginBottom: 8,
borderBottom: '1px solid #f0f0f0',
}}
>
<Space wrap size={[6, 6]} style={{ alignItems: 'center' }}>
<Text type="secondary" style={{ fontSize: 13, marginRight: 4 }}>
<WarningOutlined style={{ color: '#ff4d4f', marginRight: 4 }} />
登录异常一键筛选:
</Text>
{FAILURE_CHIPS.map((chip) => {
const btn = (
<Button
key={chip.key}
size="small"
type={chip.active ? 'primary' : 'default'}
style={{
borderRadius: 14,
fontSize: 12,
height: 26,
padding: '0 10px',
display: 'inline-flex',
alignItems: 'center',
borderColor: chip.active ? chip.color : undefined,
backgroundColor: chip.active ? chip.color : undefined,
color: chip.active ? '#fff' : undefined,
opacity: chip.count === 0 && !chip.active ? 0.5 : 1,
}}
onClick={chip.onClick}
>
<span>
{chip.icon} {chip.label}
</span>
<span
style={{
marginLeft: 5,
padding: '0 5px',
borderRadius: 10,
fontSize: 11,
lineHeight: '16px',
background: chip.active ? 'rgba(255,255,255,0.25)' : '#f0f0f0',
color: chip.active ? '#fff' : chip.count > 0 ? chip.color : '#666',
fontWeight: chip.count > 0 ? 600 : 400,
}}
>
{chip.count ?? 0}
</span>
</Button>
);
return chip.tooltip ? (
<Tooltip key={chip.key} title={chip.tooltip}>
{btn}
</Tooltip>
) : (
btn
);
})}
</Space>
{failureKindFilter && (
<Button
size="small"
type="link"
danger
onClick={() => {
setFailureKindFilter('');
setCurrentPage(1);
}}
style={{ padding: 0 }}
>
清除异常分类筛选
</Button>
)}
</div>
{/* 高价值套装一键筛选 */}
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
flexWrap: 'wrap',
gap: 8,
}}
>
<Space wrap size={[6, 6]} style={{ alignItems: 'center' }}>
<Text type="secondary" style={{ fontSize: 13, marginRight: 4 }}>
<ThunderboltOutlined style={{ color: '#fa8c16', marginRight: 4 }} />
高价值一键筛选:
</Text>
{PRESET_CHIPS.map((chip) => {
const btn = (
<Button
key={chip.key}
size="small"
type={chip.active ? 'primary' : 'default'}
style={{
borderRadius: 14,
fontSize: 12,
height: 26,
padding: '0 10px',
display: 'inline-flex',
alignItems: 'center',
borderColor: chip.active ? chip.color : undefined,
backgroundColor: chip.active ? chip.color : undefined,
color: chip.active ? '#fff' : undefined,
opacity: chip.count === 0 && !chip.active ? 0.5 : 1,
}}
onClick={chip.onClick}
>
<span>
{chip.icon} {chip.label}
</span>
<span
style={{
marginLeft: 5,
padding: '0 5px',
borderRadius: 10,
fontSize: 11,
lineHeight: '16px',
background: chip.active ? 'rgba(255,255,255,0.25)' : '#f0f0f0',
color: chip.active ? '#fff' : '#666',
fontWeight: 500,
}}
>
{chip.count ?? 0}
</span>
</Button>
);
return chip.tooltip ? (
<Tooltip key={chip.key} title={chip.tooltip}>
{btn}
</Tooltip>
) : (
btn
);
})}
</Space>
<Space size={8}>
{hasCustomFilters && (
<Button
size="small"
type="link"
danger
onClick={onResetAdvancedFilters}
style={{ padding: 0 }}
>
清除高价值筛选
</Button>
)}
<Button
size="small"
type={advFilterOpen ? 'primary' : 'default'}
ghost={advFilterOpen}
icon={advFilterOpen ? <UpOutlined /> : <DownOutlined />}
onClick={() => setAdvFilterOpen(!advFilterOpen)}
>
{advFilterOpen ? '收起高级筛选' : '高级自定义筛选'}
{hasCustomFilters && !advFilterOpen && (
<Tag
color="blue"
style={{ marginLeft: 4, marginRight: 0, padding: '0 4px', fontSize: 11 }}
>
已生效
</Tag>
)}
</Button>
</Space>
</div>
{/* 折叠展开的高级筛选面板 */}
{advFilterOpen && (
<div style={{ marginTop: 10, paddingTop: 10, borderTop: '1px dashed #f0f0f0' }}>
<Row gutter={[16, 10]} align="middle">
<Col>
<Space size={6} align="center">
<Text type="secondary" style={{ fontSize: 13 }}>
套装状态:
</Text>
<Select
allowClear
size="small"
placeholder="全部状态"
style={{ width: 180 }}
value={highValueFilter || undefined}
onChange={(val) => {
setHighValueFilter(val || '');
setCurrentPage(1);
}}
options={HIGH_VALUE_OPTIONS}
/>
</Space>
</Col>
<Col>
<Space size={4} align="center">
<Text type="secondary" style={{ fontSize: 13 }}>
积分范围:
</Text>
<InputNumber
size="small"
placeholder="最小"
min={0}
value={minPoints}
onChange={(v) => {
setMinPoints(v ?? undefined);
setCurrentPage(1);
}}
style={{ width: 75 }}
/>
<span>~</span>
<InputNumber
size="small"
placeholder="最大"
min={0}
value={maxPoints}
onChange={(v) => {
setMaxPoints(v ?? undefined);
setCurrentPage(1);
}}
style={{ width: 75 }}
/>
<Button
size="small"
type="dashed"
style={{ fontSize: 11, padding: '0 6px' }}
onClick={() => {
setMinPoints(300);
setCurrentPage(1);
}}
>
≥300
</Button>
<Button
size="small"
type="dashed"
style={{ fontSize: 11, padding: '0 6px' }}
onClick={() => {
setMinPoints(600);
setCurrentPage(1);
}}
>
≥600
</Button>
</Space>
</Col>
<Col>
<Space size={4} align="center">
<Text type="secondary" style={{ fontSize: 13 }}>
鱼翅余额:
</Text>
<InputNumber
size="small"
placeholder="最小"
min={0}
step={1}
value={minGold}
onChange={(v) => {
setMinGold(v ?? undefined);
setCurrentPage(1);
}}
style={{ width: 75 }}
/>
<span>~</span>
<InputNumber
size="small"
placeholder="最大"
min={0}
step={1}
value={maxGold}
onChange={(v) => {
setMaxGold(v ?? undefined);
setCurrentPage(1);
}}
style={{ width: 75 }}
/>
<Button
size="small"
type="dashed"
style={{ fontSize: 11, padding: '0 6px' }}
onClick={() => {
setMinGold(0.01);
setCurrentPage(1);
}}
>
&gt;0
</Button>
<Button
size="small"
type="dashed"
style={{ fontSize: 11, padding: '0 6px' }}
onClick={() => {
setMinGold(6);
setCurrentPage(1);
}}
>
≥6
</Button>
</Space>
</Col>
<Col>
<Space size={6} align="center">
<Text type="secondary" style={{ fontSize: 13 }}>
宝典:
</Text>
<Select
size="small"
allowClear
placeholder="全部"
style={{ width: 95 }}
value={eliteOpened === undefined ? undefined : String(eliteOpened)}
onChange={(val) => {
setEliteOpened(val === undefined ? undefined : val === 'true');
setCurrentPage(1);
}}
options={[
{ value: 'true', label: '宝典已开' },
{ value: 'false', label: '宝典未开' },
]}
/>
</Space>
</Col>
<Col>
<Space size={6} align="center">
<Text type="secondary" style={{ fontSize: 13 }}>
电竞:
</Text>
<Select
size="small"
allowClear
placeholder="全部"
style={{ width: 95 }}
value={esportsOpened === undefined ? undefined : String(esportsOpened)}
onChange={(val) => {
setEsportsOpened(val === undefined ? undefined : val === 'true');
setCurrentPage(1);
}}
options={[
{ value: 'true', label: '电竞已开' },
{ value: 'false', label: '电竞未开' },
]}
/>
</Space>
</Col>
<Col>
<Space size={6} align="center">
<Text type="secondary" style={{ fontSize: 13 }}>
角色绑定:
</Text>
<Select
size="small"
allowClear
placeholder="全部"
style={{ width: 100 }}
value={roleBindStatus || undefined}
onChange={(val) => {
setRoleBindStatus(val || '');
setCurrentPage(1);
}}
options={BIND_OPTIONS}
/>
</Space>
</Col>
<Col>
<Button
size="small"
icon={<ClearOutlined />}
onClick={onResetAdvancedFilters}
disabled={!hasCustomFilters}
>
重置自定义条件
</Button>
</Col>
</Row>
</div>
)}
</Card>
);
}
@@ -0,0 +1,57 @@
import { Row, Col, Card, Statistic } from 'antd';
import type { BasicSummary } from '../../../api/modules';
import { STATUS_CARDS } from '../types';
interface StatusCardsProps {
summary: BasicSummary;
statusFilter: string;
ckFilter: string;
onSelectStatus: (status: string) => void;
onClearAllStatus: () => void;
}
export function StatusCards({
summary,
statusFilter,
ckFilter,
onSelectStatus,
onClearAllStatus,
}: StatusCardsProps) {
return (
<Row gutter={12} style={{ marginBottom: 12 }}>
<Col flex="120px">
<Card
size="small"
hoverable
onClick={onClearAllStatus}
style={{ borderColor: statusFilter || ckFilter ? undefined : '#1677ff' }}
>
<Statistic title="账号总数" value={summary.visible_total ?? summary.total} />
</Card>
</Col>
{STATUS_CARDS.map((card) => {
const count = summary.by_status?.[card.value] ?? 0;
const active = statusFilter === card.value;
return (
<Col flex="120px" key={card.value}>
<Card
size="small"
hoverable
onClick={() => onSelectStatus(active ? '' : card.value)}
style={{
borderColor: active ? card.color : undefined,
opacity: count === 0 && !active ? 0.55 : 1,
}}
>
<Statistic
title={card.label}
value={count}
valueStyle={{ color: count > 0 ? card.color : undefined, fontSize: 20 }}
/>
</Card>
</Col>
);
})}
</Row>
);
}
@@ -0,0 +1,34 @@
import type { AccountsFilterState } from './types';
export const FILTER_STORAGE_KEY = 'accounts_page_filters_v1';
export function loadStoredFilters(): Partial<AccountsFilterState> {
try {
const raw = sessionStorage.getItem(FILTER_STORAGE_KEY) || localStorage.getItem(FILTER_STORAGE_KEY);
if (raw) {
return JSON.parse(raw);
}
} catch {
// 容错:解析失败回退空
}
return {};
}
export function saveStoredFilters(state: AccountsFilterState) {
try {
const json = JSON.stringify(state);
sessionStorage.setItem(FILTER_STORAGE_KEY, json);
localStorage.setItem(FILTER_STORAGE_KEY, json);
} catch {
// 容错
}
}
export function clearStoredFilters() {
try {
sessionStorage.removeItem(FILTER_STORAGE_KEY);
localStorage.removeItem(FILTER_STORAGE_KEY);
} catch {
// 容错
}
}
+144
View File
@@ -0,0 +1,144 @@
import type { TableProps } from 'antd';
import type { AccountExchangeRecord } from '../../api/modules';
import { formatTime } from '../../utils/time';
export const TAG_COLORS = [
'blue', 'green', 'cyan', 'geekblue', 'purple', 'orange', 'magenta', 'volcano',
];
export const FAILURE_KIND_OPTIONS = [
{ value: 'must_bind_mobile', label: '📱 必须绑定手机号' },
{ value: 'captcha', label: '🧩 极验/验证码拦截' },
{ value: 'credential', label: '🔑 账号凭证问题' },
{ value: 'email_code', label: '✉️ 邮箱取码失败' },
{ value: 'email_quota', label: '📫 邮箱配额已满' },
{ value: 'network', label: '🌐 网络/未知异常' },
];
export const FAILURE_KIND_LABELS: Record<string, { label: string; color: string }> = {
must_bind_mobile: { label: '必须绑定手机号', color: 'red' },
captcha: { label: '极验滑块', color: 'orange' },
credential: { label: '凭证错误', color: 'error' },
email_code: { label: '邮箱取码失败', color: 'processing' },
email_quota: { label: '邮箱配额已满', color: 'purple' },
network: { label: '网络异常', color: 'default' },
interrupted: { label: '被中断', color: 'default' },
};
export type AccountSortKey =
| 'username'
| 'status'
| 'bind'
| 'points'
| 'high_value'
| 'exchange'
| 'tag';
export const ACCOUNT_SORT_KEYS = new Set<string>([
'username',
'status',
'bind',
'points',
'high_value',
'exchange',
'tag',
]);
export const STATUS_TONES: Record<string, string> = {
imported: 'default',
active: 'green',
invalid: 'red',
manual: 'orange',
disabled: 'default',
archived: 'default',
};
export const CK_OPTIONS = [
{ value: 'invalid', label: 'CK 失效' },
{ value: 'valid', label: 'CK 正常' },
{ value: 'error', label: '检测异常' },
];
export const BIND_OPTIONS = [
{ value: 'bound', label: '已绑定' },
{ value: 'pending', label: '待确认' },
{ value: 'unbound', label: '未绑定' },
{ value: 'unknown', label: '绑定未知' },
];
export const STATUS_CARDS = [
{ value: 'active', label: '正常', color: '#52c41a' },
{ value: 'invalid', label: 'CK 失效', color: '#ff4d4f' },
{ value: 'manual', label: '待人工', color: '#fa8c16' },
{ value: 'imported', label: '未登录', color: '#8c8c8c' },
{ value: 'disabled', label: '已停用', color: '#8c8c8c' },
];
export const HIGH_VALUE_OPTIONS = [
{ value: 'both_available', label: '🌟 双套均可换 (高价值)' },
{ value: 'can_bairimeng', label: '👗 可换白日梦爱丽丝' },
{ value: 'can_mengtu', label: '🐰 可换狂战萌兔' },
{ value: 'owned_bairimeng', label: '✓ 已拥有白日梦' },
{ value: 'owned_mengtu', label: '✓ 已拥有萌兔' },
{ value: 'both_owned', label: '✓ 两套均已拥有' },
{ value: 'high_value_broken', label: '⚠️ 高价值但CK失效' },
{ value: 'unqueried', label: '❓ 未查过资料' },
];
export const EXCHANGE_SCOPES: Array<{ key: string; label: string }> = [
{ key: 'elite', label: '精英宝典' },
{ key: 'esports', label: '电竞手册' },
{ key: 'peace', label: '和平小店' },
];
export 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 interface AccountsFilterState {
tagFilter: string;
statusFilter: string;
ckFilter: string;
failureKindFilter: string;
bindFilter: string;
assignFilter: string;
searchText: string;
highValueFilter: string;
minPoints?: number;
maxPoints?: number;
minGold?: number;
maxGold?: number;
eliteOpened?: boolean;
esportsOpened?: boolean;
roleBindStatus: string;
currentPage: number;
pageSize: number;
sortKey: AccountSortKey | '';
sortOrder: 'ascend' | 'descend' | null;
advFilterOpen?: boolean;
}