From 20f25d0e7ab745a68b36e3c4a46d5824300adcd1 Mon Sep 17 00:00:00 2001 From: timeance <30307526+timeance@users.noreply.github.com> Date: Wed, 18 Nov 2026 00:35:15 +0800 Subject: [PATCH] fix: align report layout and default to light theme --- CHANGELOG.md | 6 ++ README.md | 2 +- _conf_schema.json | 10 +-- assets/github-mark-black.svg | 10 +++ assets/github-mark-white.svg | 10 +++ docs/API_NOTES.md | 4 +- docs/THIRD_PARTY.md | 2 +- docs/VALIDATION.md | 35 +++++----- main.py | 4 +- metadata.yaml | 2 +- render.py | 88 +++++++++++++++++++----- service.py | 4 +- settings.py | 4 +- templates/base.html | 68 ++++++++++++++++--- templates/match.html | 49 ++++++++++---- tests/test_config.py | 11 +++ tests/test_render.py | 126 +++++++++++++++++++++++++++++++++-- tests/test_report_data.py | 28 +++++++- tests/test_web_settings.py | 24 ++++++- tools/check_settings_view.py | 18 +++++ tools/render_previews.py | 21 ++++-- 21 files changed, 441 insertions(+), 85 deletions(-) create mode 100644 assets/github-mark-black.svg create mode 100644 assets/github-mark-white.svg diff --git a/CHANGELOG.md b/CHANGELOG.md index 0018bc3..3940ea6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,11 @@ # 更新日志 +## 0.1.4 · 2026-11-18 + +- 图片页脚改用 GitHub Logo。 +- 单局战报顶部补充双方队伍摘要,对比和兵种构成改用比例横条展示。 +- 图片默认使用浅色,可在设置中切换深色;保留已保存的主题选择。 + ## 0.1.3 · 2026-11-17 - 图片发送方式新增 Base64(默认)、本地文件(NapCat 直读)和图片链接(NapCat 下载);发送失败时记录 ERROR 并回复原文字战报,不自动切换方式。 diff --git a/README.md b/README.md index bc397b5..287ebbd 100644 --- a/README.md +++ b/README.md @@ -70,7 +70,7 @@ ba stats @群友 - **数据源接入**:在线查询开关、API 地址,无需填写客户端标识或令牌。 - **查询与命令**:默认/最大近期场数(5 / 20)、用户冷却(3 秒)、中文子命令别名开关。 - **每日请求额度**:每用户默认 20 次、每群默认 100 次(可在 `0–100` 间调整,`0` 表示不单独限制);**全插件每日总上限固定为 100 次不可调整**。所有额度于北京时间每天 0 点重置,按上游 HTTP 请求计数,失败与重试也计入;命中缓存及本地命令不扣额。 -- **战报显示**:图片战报开关(渲染或发送未成功时回复同内容文字)、深浅主题(默认深色)、显示时区(默认 `Asia/Shanghai`)。 +- **战报显示**:图片默认浅色,可在「图片主题」中切换深色;支持图片战报开关(渲染或发送未成功时回复同内容文字)和显示时区(默认 `Asia/Shanghai`)。 - **维护与缓存**:请求间隔、并发、超时、重试及缓存容量/旧缓存回退时间,设置中心中默认折叠。 - **诊断日志**:诊断开关、日志状态和 ZIP 下载集中显示,内容默认折叠;总容量上限 30 MB,旧日志自动轮换。 diff --git a/_conf_schema.json b/_conf_schema.json index a78849d..757f283 100644 --- a/_conf_schema.json +++ b/_conf_schema.json @@ -97,14 +97,14 @@ "theme": { "description": "图片主题", "type": "string", - "default": "dark", + "default": "light", "options": [ - "dark", - "light" + "light", + "dark" ], "labels": [ - "深色", - "浅色" + "浅色", + "深色" ] }, "timezone": { diff --git a/assets/github-mark-black.svg b/assets/github-mark-black.svg new file mode 100644 index 0000000..4f46bf3 --- /dev/null +++ b/assets/github-mark-black.svg @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/assets/github-mark-white.svg b/assets/github-mark-white.svg new file mode 100644 index 0000000..527ba11 --- /dev/null +++ b/assets/github-mark-white.svg @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/docs/API_NOTES.md b/docs/API_NOTES.md index 75e703f..6a95780 100644 --- a/docs/API_NOTES.md +++ b/docs/API_NOTES.md @@ -85,9 +85,9 @@ SteamID64 与 STB ID 均保持字符串;**未找到可靠的 Steam→STB 映 `scoring.py` 使用 `assets/scoring-model.json`,移植 ba-dragon 固定提交的逐局评分逻辑与参数。近期战绩首列统一命名「评分」,按分数段着色,不显示称号。缺少必要数据时返回 `None` 并显示「暂无」,不补零。它与来源 ELO 分别展示,不是完整生涯评价,也不引入时间线或 Kalman 聚合算法。 -`ba last` 的单局图片顶部展示基于双方赛前 ELO 的赛前预测;中部左右排列双方数据对比与兵种构成;底部展示玩家数据。预测是模型估算,不表示实际赛果。兵种构成按模型的单位角色与基础价格估算出动花费,缺少单位价格或记录时保留不完整说明,不冒充实际结算。 +`ba last` 的单局图片顶部展示基于双方赛前 ELO 的赛前预测及双队摘要;中部左侧兵种构成、右侧双方对比;底部展示队伍玩家数据。摘要区分赛前平均 ELO(`OldRating`)与赛后平均 ELO(`NewRating`)。预测是模型估算,不表示实际赛果。兵种构成按模型的单位角色与基础价格估算出动花费,缺少单位价格或记录时保留不完整说明,不冒充实际结算。 -所有战报图片页脚包含 `assets/github-avatar.png`、`timeance/astrbot_plugin_BA_stats` 与固定文字「数据来源 BATracer」。设置提示仍原样保留「数据来源 BATrace ,如有帮助请支持该平台」。 +所有战报图片页脚内嵌 `assets/github-mark-black.svg` 或 `assets/github-mark-white.svg`,并包含 `timeance/astrbot_plugin_BA_stats` 与固定文字「数据来源 BATracer」。设置提示仍原样保留「数据来源 BATrace ,如有帮助请支持该平台」。 ## 设置中心与诊断日志 diff --git a/docs/THIRD_PARTY.md b/docs/THIRD_PARTY.md index aed33a5..3866f57 100644 --- a/docs/THIRD_PARTY.md +++ b/docs/THIRD_PARTY.md @@ -29,6 +29,6 @@ 依赖由宿主环境安装,安装 ZIP 不附带第三方库;各依赖许可证以其发布包为准。预览工具使用本地 Playwright/Chromium,仅用于开发验收,运行插件不需要安装它们。 -`assets/github-avatar.png` 用于图片页脚的 GitHub 作者标识,与 `timeance/astrbot_plugin_BA_stats` 及「数据来源 BATracer」一同显示;不属于 ba-dragon 评分模型素材。 +`assets/github-mark-black.svg` 与 `assets/github-mark-white.svg` 来自 GitHub 官方 [Logo 素材包](https://brand.github.com/GitHub_Logos.zip),用于图片页脚的项目链接。按主题内嵌对应黑白版本,与 `timeance/astrbot_plugin_BA_stats` 及「数据来源 BATracer」一同显示。 `logo.png` 与 `assets/readme-logo.png` 原样来自用户交接包,交付时核对 SHA-256 一致。它们的授权与来源由交接提供方负责说明,本项目没有代替权利人作版权声明。 diff --git a/docs/VALIDATION.md b/docs/VALIDATION.md index 4a25208..d56981c 100644 --- a/docs/VALIDATION.md +++ b/docs/VALIDATION.md @@ -1,16 +1,16 @@ # 验证记录 -验证日期:2026-11-17(Asia/Hong_Kong)。版本:v0.1.3。 +验证日期:2026-11-18(Asia/Hong_Kong)。版本:v0.1.4。 ## 本次结果 | 项目 | 结果 | | --- | --- | -| 完整离线测试 | **695 passed,33.35 秒** | +| 完整离线测试 | **723 passed,31.67 秒** | | 评分与固定上游 TypeScript 对照 | **320 个合成样本一致**;中间值误差小于 1e-12 | -| 三类战报本地渲染 | 沿用 v0.1.2 的 18 组 HTML/文字、36 张 PNG;本轮未修改战报版式 | -| 设置中心本地交互 | 深色 390px、浅色 1100px 两组通过;4 张预览;新增发送方式保存检查 | -| 依赖兼容性 | `uv pip check`:30 个已安装包兼容 | +| 三类战报本地渲染 | 18 组 HTML/文字、36 张 PNG;无布局越界或外部请求 | +| 设置中心本地交互 | 深色 390px、浅色 1100px 两组通过;4 张预览;验证浅色默认值及已保存深色配置 | +| 依赖兼容性 | 依赖未变;沿用 v0.1.3 的 `uv pip check` 结果:30 个已安装包兼容 | | 完整 AstrBot 服务、真实渲染服务 | 未启动;按 v4.29.4 固定源码核对 API,使用事件与桥接桩验证 | | BATrace / QQ 实际联调 | 开发环境未调用;用户已提供候选结果和图片超时日志 | | 远端 PR / CI | 以对应 PR 的实时结果为准;本记录不表示已合并或部署 | @@ -24,8 +24,11 @@ - 「评分」移植固定 ba-dragon 模型的逐局 career 计算,按分数着色,不展示称号。保留 MIT 来源与完整许可。 - Oracle 包含原始 160 个样本,以及逐个删除 `StartTime` 的 160 个边界样本。开始/结束时间分别保留;不以结束时间减时长反推开始时间。近期列表按真实结束时间、缺少时按真实开始时间排序,两者都缺少才放最后。 - 赛前预测使用 A/B 队全部必要赛前 ELO;兵种构成按已收录单位基础价格估算。缺少成员单位数据或存在未知价格时,不把已识别部分重新归一化为完整构成。 -- 单局图片按 900 CSS 像素渲染:顶部预测,中部左右对比/构成,底部玩家。其他卡片为 390 CSS 像素;运行仍使用 JPEG 85、ultra 像素比。 -- 所有图片页脚为本地内嵌 GitHub 头像、`timeance/astrbot_plugin_BA_stats` 和「数据来源 BATracer」。不在运行时请求头像。 +- 队伍摘要的赛前平均 ELO 使用传递到展示层的赛前值;本局 `NewRating` 标明为赛后平均 ELO,不将历史对局的赛后值称为当前值。 +- 单局图片按 900 CSS 像素渲染:顶部预测及 A/B 队伍摘要,中部左侧兵种构成、右侧双方对比,底部玩家。其他卡片为 390 CSS 像素;运行仍使用 JPEG 85、ultra 像素比。 +- 双方对比与逐兵种构成都共用左 A、右 B 的横条;兵种使用对应类别的同色系深浅色(A 深、B 浅)。构成数值保持双方各自占比,横条按这两个占比划分;缺失值与 0/0 不生成虚假的比例。 +- 所有图片页脚为本地内嵌 GitHub Logo、`timeance/astrbot_plugin_BA_stats` 和「数据来源 BATracer」。深浅主题分别使用官方白色与黑色 Logo,不在运行时请求素材。 +- 图片默认浅色;原生配置、独立设置中心和渲染器默认值一致,已保存的深色选择保持有效。图片缓存摘要包含完整 HTML,样式、主题和 Logo 变更会生成新缓存。 ## 设置中心与诊断 @@ -35,7 +38,7 @@ - API 使用 AstrBot 登录鉴权,插件额外检查用户名。未登录、已关闭、无效 JSON、非法类型/范围、保存失败及旧实例卸载有回归测试。下载不通过公开静态目录。 - 诊断仅记录允许的事件与字段:请求耗时/状态、渲染及图片发送阶段、文件类型/大小、受控错误分类等。日志上限为 `30 * 1024 * 1024` 字节,旧段自动淘汰;关闭后可下载既有日志。 - 记录器覆盖轮换、并发导出、关闭、磁盘失败及脱敏;不记录令牌、请求头、完整响应、聊天正文或图片内容。导出为 ZIP,不清空原日志。 -- 本地浏览器验证保存开关、下载路由、409 草稿保留、重新读取后保留草稿、待重载提示及固定总额度;新增验证 Base64 默认值,以及 file/url 保存后等待重载。合成桥接不替代真实宿主收发;常用设置全页预览将悬浮保存栏放到文档末尾,交互测试使用原样 CSS。 +- 本地浏览器验证保存开关、下载路由、409 草稿保留、重新读取后保留草稿、待重载提示及固定总额度;验证 Base64 默认值,以及 file/url 保存后等待重载。本轮增加图片浅色默认值、切换主题和保留已保存深色的检查。合成桥接不替代真实宿主收发;常用设置全页预览将悬浮保存栏放到文档末尾,交互测试使用原样 CSS。 ## 图片发送与损坏缓存 @@ -55,21 +58,21 @@ v0.1.3 共用图片下载与验证流程:检查 HTTP 状态,限制下载大 ## 执行与证据 ```powershell -& ../.venv/Scripts/python.exe -X utf8 -m pytest -q --basetemp=../tmp/pytest-v013-portable --junitxml=../validation/pytest-v0.1.3.xml -# 695 passed in 33.35s +& ../.venv/Scripts/python.exe -X utf8 -m pytest -q --basetemp=../tmp/pytest-v014-reviewed --junitxml=../validation/pytest-v0.1.4.xml +# 723 passed in 31.67s -& ../.venv/Scripts/python.exe -X utf8 -B tools/render_previews.py --screenshots -# v0.1.2 记录:18 HTML/text pairs; 36 screenshots; 0 layout/network failures -# 本轮未修改战报版式,沿用对应预览,未重复运行此命令。 +& ../.venv/Scripts/python.exe -X utf8 -B tools/render_previews.py --screenshots --output ../tmp/report-visual-v014/previews +# 18 HTML/text pairs; 36 screenshots; 0 layout/network failures & ../.venv/Scripts/python.exe -X utf8 -B tools/check_settings_view.py # 2 local browser scenarios passed; 4 screenshots; no external requests -uv --cache-dir ../tmp/uv-cache pip check --python ../.venv/Scripts/python.exe -# All installed packages are compatible +# 依赖未变,沿用 v0.1.3:uv pip check,30 个已安装包兼容。 ``` -主代理目视检查了近期浅色手机卡、玩家概览、单局深色宽图、常用设置浅色桌面页和诊断深色手机页。卡片矩阵含正常、长昵称、缺失数据三组,深浅两色,900/390px;预览均标明合成样本。浏览器拦截外部请求,只使用本地生成内容,没有使用外部账号或登录态。 +主代理目视检查了单局深浅两色宽图、单局缺失数据手机卡、近期浅色手机卡、玩家概览深色手机卡和常用设置浅色桌面页。卡片矩阵含正常、长昵称、缺失数据三组,深浅两色,900/390px;预览均标明合成样本。浏览器拦截外部请求,只使用本地生成内容,没有使用外部账号或登录态。 + +本轮战报预览保存在会话目录的 `tmp/report-visual-v014/previews/`;设置中心预览位于 `previews/settings-*.png`。本地预览不随插件发布。 会话目录:`H:/Codex/01a1e923-f766-7562-b804-35854a994fc4`。Python 3.11.4;Playwright 1.65.2,本地 Chromium 159.0.8154.6。主测试使用 httpx.MockTransport、临时 SQLite 和 AstrBot 桩;没有访问真实战绩、QQ 账号、数据库或运行配置。 diff --git a/main.py b/main.py index 4367636..548f0e0 100644 --- a/main.py +++ b/main.py @@ -155,7 +155,7 @@ async def initialize(self): await self.storage.open() self._images.mkdir(parents=True, exist_ok=True) self._prune_images() - self.diagnostics.record("plugin_start", status="0.1.3") + self.diagnostics.record("plugin_start", status="0.1.4") async def _run(self, awaitable, *, timed=True): if self._closed: @@ -304,7 +304,7 @@ async def _status(self): "schema": "响应结构变化", "identity_mismatch": "身份校验失败", "no_data": "暂无收录", "upstream": "上游暂不可用", "queue_full": "队列已满", "not_configured": "接入未配置", "closed": "客户端已关闭", "daily_quota": "每日额度已用完"} - return (f"断箭战报 v0.1.3\n在线查询:{'已启用' if status['configured'] else '未启用或 API 地址无效'}\n" + return (f"断箭战报 v0.1.4\n在线查询:{'已启用' if status['configured'] else '未启用或 API 地址无效'}\n" f"今日总请求:{usage['global']}/{GLOBAL_DAILY_LIMIT}(固定上限);北京时间 0 点重置\n" f"本次运行请求:{status['requests']};进行中:{status['inflight']}\n" f"API 缓存:{await self.storage.cache_count()} 条;命中:{status['cache_hits']};旧缓存:{status['stale_hits']}\n" diff --git a/metadata.yaml b/metadata.yaml index 9f34898..3469028 100644 --- a/metadata.yaml +++ b/metadata.yaml @@ -2,7 +2,7 @@ name: astrbot_plugin_ba_stats display_name: 断箭战报 short_desc: "《断箭》战绩查询,支持逐局评分、赛前预测与图片战报。" desc: "查询《断箭》(Broken Arrow)玩家概览、近期战绩和单局战报,展示逐局评分、赛前预测、双方对比与兵种构成,支持账号绑定、群友查询及图片或文字展示。在设置中心或原生插件配置中开启在线查询后使用。" -version: "0.1.3" +version: "0.1.4" author: timeance repo: https://github.com/timeance/astrbot_plugin_BA_stats astrbot_version: ">=4.29.4" diff --git a/render.py b/render.py index cdd2537..b12a3a5 100644 --- a/render.py +++ b/render.py @@ -5,13 +5,13 @@ player: {id: str, name: str, source_url?: str}; required for player cards. metrics: [{label: str, value: number | str | None, unit?: str, format?: "integer" | "decimal" | "percent" | "signed", note?: str}]. - Numbers default to two decimals; counts use integer. Percent values are + Numbers use two decimals, omitting .00 for exact integers; counts use integer. Percent values are already on the 0..100 scale. Strings are display text, never HTML. rows (recent): [{id, started_at, map_name, mode, outcome, duration_seconds, elo_delta, kills, losses, destroyed_value, lost_value, unit_exchange, value_exchange, source_url}]. Every field except id may be absent. match (match): {id, map_name, mode, started_at, duration_seconds, winner}. - teams (match): [{name, outcome, players: [{id, name, elo, elo_delta, kills, + teams (match): [{name, outcome, players: [{id, name, elo, elo_before, elo_delta, kills, losses, destroyed_value, lost_value, unit_exchange, value_exchange}]}]. Team sizes are unrestricted; never pad absent players with dummy rows. common_units (overview, optional): [{name: str, count?: int}]. @@ -22,11 +22,13 @@ Outcome: win/loss/unknown; mode: ranked/custom/unknown (other labels preserved). Unit counts (kills/losses) and values (destroyed_value/lost_value) are displayed -separately. Renderer does not derive statistics, coverage, ratios, or winners. +separately. Renderer does not infer coverage, exchange ratios, or winners. +Team summaries average supplied ratings only when every member has that field; +bar widths use the original numeric values, never their rounded display text. None, blank, nonfinite, and absent values display as 暂无; real zero stays zero. Missing/naive timestamps display as 暂无, rather than guessing a timezone. -Renderer(theme='dark', timezone='Asia/Shanghai').template(view) returns final +Renderer(theme='light', timezone='Asia/Shanghai').template(view) returns final escaped HTML. For AstrBot use the FIXED template '{{ body | safe }}' with data={'body': html}; never pass the generated HTML as another Jinja template. This preserves nicknames containing literal Jinja tags. text(view) uses exactly @@ -53,6 +55,8 @@ _TITLES = {"overview": "玩家概览", "recent": "近期战绩", "match": "单局战报"} _OUTCOMES = {"win": "胜利", "loss": "失利", "unknown": "胜负暂无"} _MODES = {"ranked": "排位", "custom": "自定义", "unknown": "暂无"} +_ROLES = {"装甲": "armor", "步兵": "infantry", "侦察": "recon", "炮兵": "artillery", + "防空": "air-defense", "直升机": "helicopter", "固定翼": "aircraft", "后勤/运输": "logistics"} def _plain(value, default=MISSING) -> str: @@ -79,9 +83,18 @@ def _numeric(value, style="decimal") -> str: return MISSING if style == "integer": return str(int(parsed)) if parsed == parsed.to_integral_value() else MISSING + if style == "decimal" and parsed == parsed.to_integral_value(): + return str(int(parsed)) return format(parsed, "+.2f" if style == "signed" else ".2f") +def _split_width(values) -> float | None: + numbers = [_number(value) for value in values] + if len(numbers) != 2 or any(value is None or value < 0 for value in numbers) or sum(numbers) == 0: + return None + return float(numbers[0] / sum(numbers) * 100) + + def _safe_url(value) -> str: if not isinstance(value, str) or not value: return "" @@ -119,13 +132,14 @@ def _outcome(value) -> dict: class Renderer: """Render self-contained cards without network access or model imports.""" - def __init__(self, theme: str = "dark", timezone: str = "Asia/Shanghai"): + def __init__(self, theme: str = "light", timezone: str = "Asia/Shanghai"): if theme not in {"dark", "light"}: raise ValueError("theme must be dark or light") self.theme = theme self.timezone = ZoneInfo(timezone) - self._avatar = "data:image/png;base64," + base64.b64encode( - (Path(__file__).parent / "assets" / "github-avatar.png").read_bytes()).decode("ascii") + logo = "github-mark-white.svg" if theme == "dark" else "github-mark-black.svg" + self._github_logo = "data:image/svg+xml;base64," + base64.b64encode( + (Path(__file__).parent / "assets" / logo).read_bytes()).decode("ascii") self._environment = Environment( loader=FileSystemLoader(Path(__file__).with_name("templates")), autoescape=select_autoescape(("html",)), @@ -234,7 +248,7 @@ def _prepare(self, view: dict) -> dict: match = _mapping(view.get("match")) prepared = { "kind": kind, - "avatar": self._avatar, + "github_logo": self._github_logo, "title": _plain(view.get("title"), _TITLES[kind]), "theme": self.theme, "player": { @@ -289,25 +303,51 @@ def _prepare(self, view: dict) -> dict: "winner": _plain(match.get("winner")), "target_outcome": _outcome(match.get("target_outcome")), } - for team in _records(view.get("teams")): + raw_teams = _records(view.get("teams")) + for team in raw_teams: + members = _records(team.get("players")) + team_metrics = [self._metric(item) for item in _records(team.get("metrics"))] + summary = [] + # The service's mean ELO is the post-match value, not the prediction's + # pre-match input. Never reconstruct a missing pre-match rating. + for label, field in (("赛前平均 ELO", "elo_before"), ("平均 ELO 变化", "elo_delta")): + values = [_number(item.get(field)) for item in members] + complete = bool(values) and all(value is not None for value in values) + summary.append(self._metric({"label": label, "value": sum(values) / len(values) if complete else None, + "format": "signed" if field == "elo_delta" else "decimal"})) + for label in ("赛后平均 ELO", "摧毁分"): + metric = next((item for item in team_metrics if item["label"] == label), self._metric({"label": label})) + summary.append(metric) + composition = [] + for item in _records(team.get("composition")): + percentage = _number(item.get("percentage")) + composition.append({"name": _plain(item.get("name")), "percentage": _numeric(percentage, "percent"), + "number": percentage if percentage is not None and 0 <= percentage <= 100 else None, + "role": _ROLES.get(item.get("name"), "other")}) + total = sum((item["number"] or 0) for item in composition) + # Service omits zero-spend roles from a complete composition. Only + # a full, unqualified 100% distribution makes that omission zero. + composition_complete = (bool(composition) and all(item["number"] is not None for item in composition) + and abs(total - 100) <= Decimal("0.01") and not team.get("composition_note")) prepared["teams"].append({ "name": _plain(team.get("name")), + "side": "a" if team.get("name") == "A 队" else "b" if team.get("name") == "B 队" else "neutral", "outcome": _outcome(team.get("outcome")), - "metrics": [self._metric(item) for item in _records(team.get("metrics"))], - "composition": [{"name": _plain(item.get("name")), "percentage": _numeric(item.get("percentage")), - "width": float(max(0, min(100, _number(item.get("percentage")) or 0)))} - for item in _records(team.get("composition"))], + "metrics": team_metrics, + "summary": [summary[index] for index in (0, 2, 1, 3)], + "composition": composition, + "composition_complete": composition_complete, "composition_note": _plain(team.get("composition_note"), ""), "players": [ {"id": _plain(item.get("id")), "name": _plain(item.get("name")), "is_target": bool(player.get("id")) and item.get("id") == player.get("id"), "metrics": self._exchange(item, elo=True)} - for item in _records(team.get("players")) + for item in members ], }) prediction = _mapping(view.get("prediction")) a, b = _number(prediction.get("a")), _number(prediction.get("b")) - prepared["prediction"] = ({"a": _numeric(a), "b": _numeric(b), "width": float(a)} + prepared["prediction"] = ({"a": _numeric(a, "percent"), "b": _numeric(b, "percent"), "width": float(a)} if a is not None and b is not None and 0 <= a <= 100 and 0 <= b <= 100 else None) # Each comparison row keeps the actual team order and both denominators. labels = list(dict.fromkeys(m["label"] for team in prepared["teams"][:2] for m in team["metrics"])) @@ -315,8 +355,22 @@ def _prepare(self, view: dict) -> dict: for label in labels: pair = [next((m for m in team["metrics"] if m["label"] == label), None) for team in prepared["teams"][:2]] if len(pair) == 2: - prepared["comparisons"].append({"label": label, "values": [m["display"] if m else MISSING for m in pair], - "notes": [m["note"] if m else "" for m in pair]}) + numbers = [_number(next((m.get("value") for m in _records(team.get("metrics")) + if _plain(m.get("label")) == label), None)) for team in raw_teams[:2]] + prepared["comparisons"].append({"label": label, + "values": [m["display"] if m else MISSING for m in pair], + "notes": [m["note"] if m else "" for m in pair], "width": _split_width(numbers)}) + category_names = list(dict.fromkeys(category["name"] for team in prepared["teams"][:2] + for category in team["composition"])) + category_names.sort(key=lambda name: list(_ROLES).index(name) if name in _ROLES else len(_ROLES)) + prepared["composition_rows"] = [] + if len(prepared["teams"]) >= 2: + for name in category_names: + values = [next((category["number"] for category in team["composition"] if category["name"] == name), + Decimal(0) if team["composition_complete"] else None) for team in prepared["teams"][:2]] + prepared["composition_rows"].append({"label": name, "role": _ROLES.get(name, "other"), + "values": [_numeric(value, "percent") + "%" if value is not None else MISSING for value in values], + "width": _split_width(values)}) page = _number(view.get("page")) page_count = _number(view.get("page_count")) row_total = _number(view.get("row_total")) diff --git a/service.py b/service.py index 574e351..4a0e59b 100644 --- a/service.py +++ b/service.py @@ -52,7 +52,7 @@ def freshness(*results): def participant_view(p: Participant): - return dict(id=p.player_id, name=p.name, elo=p.elo, elo_delta=p.elo_delta, + return dict(id=p.player_id, name=p.name, elo=p.elo, elo_before=p.elo_before, elo_delta=p.elo_delta, kills=p.kills, losses=p.losses, destroyed_value=p.destroyed_value, lost_value=p.lost_value, unit_exchange=ratio(p.kills, p.losses), value_exchange=ratio(p.destroyed_value, p.lost_value), @@ -106,7 +106,7 @@ def team_metrics(players): metrics = [] for field, label, style in ( ("destroyed_value", "摧毁分", "decimal"), ("lost_value", "损失分", "decimal"), - ("elo", "平均 ELO", "decimal"), ("kills", "击杀", "integer"), + ("elo", "赛后平均 ELO", "decimal"), ("kills", "击杀", "integer"), ("losses", "阵亡", "integer"), ("damage_dealt", "伤害", "decimal"), ("spawned_value", "出兵花费", "decimal"), ("objectives", "占点", "integer"), ("supply", "补给", "decimal"), diff --git a/settings.py b/settings.py index 50d87fa..15378ac 100644 --- a/settings.py +++ b/settings.py @@ -47,7 +47,7 @@ class Settings: chinese_aliases: bool = True image_enabled: bool = True image_send_mode: str = "base64" - theme: str = "dark" + theme: str = "light" timezone: str = "Asia/Shanghai" request_interval: float = 1 concurrency: int = 2 @@ -75,7 +75,7 @@ def from_config(cls, config): ZoneInfo(timezone) except (ZoneInfoNotFoundError, ValueError): raise ValueError("时区无效,请填写 Asia/Shanghai 等 IANA 时区名。") from None - theme = output.get("theme", "dark") + theme = output.get("theme", "light") if theme not in {"dark", "light"}: raise ValueError("主题必须为 dark 或 light。") image_send_mode = output.get("image_send_mode", "base64") diff --git a/templates/base.html b/templates/base.html index 2a3d053..f9e64aa 100644 --- a/templates/base.html +++ b/templates/base.html @@ -12,6 +12,8 @@ --ink: #eff5ff; --muted: #b1bfd0; --line: #31445d; --accent: #79bfff; --win: #73deb5; --loss: #ffa5ae; --warning: #ffce80; + --team-a: #69adf0; --team-b: #f18477; + --team-a-panel: #102336; --team-b-panel: #302025; } [data-theme="light"] { color-scheme: light; @@ -19,6 +21,8 @@ --ink: #152944; --muted: #52647d; --line: #c3cfdd; --accent: #145d9c; --win: #07694d; --loss: #ab263d; --warning: #7a4b00; + --team-a: #2169b3; --team-b: #b83931; + --team-a-panel: #e6effa; --team-b-panel: #fbeceb; } * { box-sizing: border-box; } body { @@ -89,21 +93,59 @@ .score small { font-size: 11px; color: var(--muted); font-weight: 400; margin-bottom: 4px; } .score.low { color: var(--loss); } .score.medium { color: var(--ink); } .score.high { color: var(--warning); } .prediction { border: 1px solid var(--line); padding: 18px; background: var(--panel); } - .prediction-values { display: flex; justify-content: space-between; gap: 10px; margin: 12px 0; color: var(--accent); font-size: 24px; } - .prediction-values b:last-child { color: var(--loss); } - .prediction-bar { height: 9px; background: var(--loss); } .prediction-bar i { display: block; height: 100%; background: var(--accent); } + .prediction-values { display: flex; justify-content: space-between; gap: 10px; margin: 12px 0; color: var(--team-a); font-size: 24px; } + .prediction-values b:last-child { color: var(--team-b); } + .prediction-bar { height: 9px; background: var(--team-b); } .prediction-bar i { display: block; height: 100%; background: var(--team-a); } + .side-a { --side: var(--team-a); color: var(--team-a); } + .side-b { --side: var(--team-b); color: var(--team-b); } + .side-neutral { --side: var(--muted); } + .team-summaries { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); border: 1px solid var(--line); border-top: 0; } + .team-summary { min-width: 0; padding: 14px 18px 16px; border-top: 3px solid var(--side); background: var(--panel); } + .team-summary.side-a { background: var(--team-a-panel); } + .team-summary.side-b { background: var(--team-b-panel); } + .team-summary + .team-summary { border-left: 1px solid var(--line); } + .summary-heading { display: flex; align-items: baseline; justify-content: space-between; gap: 10px; } + .summary-heading h2 { min-width: 0; overflow-wrap: anywhere; } + .summary-metrics { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 10px 14px; margin: 12px 0 0; color: var(--ink); } + .summary-metrics div { min-width: 0; } + .summary-metrics dt { color: var(--muted); font-size: 12px; } + .summary-metrics dd { margin: 2px 0 0; font-size: 21px; font-weight: 650; overflow-wrap: anywhere; } .match-columns { display: grid; grid-template-columns: minmax(0,1fr) minmax(0,1fr); gap: 20px; } .match-columns > section { min-width: 0; } - .composition-heading { font-size: 16px; margin: 15px 0 8px; } - .role-row { display: grid; grid-template-columns: 4em 1fr 4em; gap: 6px; font-size: 13px; align-items: center; margin: 6px 0; } - .role-row b { font-weight: 400; text-align: right; } - .role-track { background: var(--subtle); height: 6px; } .role-track i { display: block; height: 100%; background: var(--accent); } + .comparison-key, .comparison-values, .comparison-notes { display: flex; justify-content: space-between; gap: 12px; } + .comparison-key { margin: 0 0 16px; } + .comparison-key > span { flex: 1 1 0; min-width: 0; overflow-wrap: anywhere; } + .comparison-key > span:last-child { text-align: right; } + .comparison-list { margin: 0; } + .comparison-row { margin: 0 0 13px; } + .comparison-row dt { font-size: 13px; color: var(--muted); } + .comparison-row dd { margin: 2px 0 0; } + .comparison-values b { font-size: 16px; font-weight: 600; overflow-wrap: anywhere; min-width: 0; } + .comparison-values b:last-child { text-align: right; } + .comparison-track { display: flex; height: 9px; margin-top: 5px; background: var(--subtle); } + .comparison-track .segment { display: block; height: 100%; background: var(--side); } + .comparison-track.no-comparison { background: transparent; border-bottom: 1px solid var(--line); } + .comparison-notes { color: var(--muted); font-size: 12px; margin-top: 3px; } + .comparison-notes > :last-child { text-align: right; } + .composition-key { margin: 7px 0 16px; } + .composition-row { margin-bottom: 16px; } + .composition-row .comparison-track { height: 14px; } + .role-armor { --role: #8f9460; --role-light: #bec1a2; } + .role-infantry { --role: #6f9a79; --role-light: #adc7b3; } + .role-recon { --role: #4fa3a0; --role-light: #9dcfcd; } + .role-artillery { --role: #b07a4a; --role-light: #d3b394; } + .role-air-defense { --role: #8c7bb8; --role-light: #beb4d7; } + .role-helicopter { --role: #c08bb0; --role-light: #dbbdd1; } + .role-aircraft { --role: #9aa3ad; --role-light: #c4c9cf; } + .role-logistics, .role-other { --role: #898f97; --role-light: #bdc1c6; } + .comparison-track .role-a { background: var(--role); } + .comparison-track .role-b { background: var(--role-light); } .notes { margin-top: 20px; padding-left: 18px; color: var(--muted); font-size: 14px; overflow-wrap: anywhere; } footer { border-top: 1px solid var(--line); margin-top: 26px; padding-top: 14px; color: var(--muted); font-size: 13px; } footer p + p { margin-top: 5px; } footer p { overflow-wrap: anywhere; } .attribution { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 10px; } - .attribution img { width: 24px; height: 24px; border-radius: 50%; } + .attribution img { width: 24px; height: 24px; object-fit: contain; } .attribution a { color: var(--muted); font-size: 12px; } .stale { color: var(--warning); font-weight: 650; margin-bottom: 8px; } @media (max-width: 680px) { @@ -120,6 +162,14 @@ .participant .exchange { grid-template-columns: repeat(2, minmax(0, 1fr)); } .match-meta { padding: 14px; grid-template-columns: 1fr; gap: 10px; } .metric-label, .row-id, .participant-id, .metric-note, footer { font-size: 14px; } + .match-columns { grid-template-columns: 1fr; } + .team-summary { padding: 12px 10px; } + .summary-heading { flex-wrap: wrap; gap: 4px; } + .summary-heading h2 { font-size: 16px; } + .summary-heading .team-size { margin-left: 5px; font-size: 12px; } + .summary-metrics { grid-template-columns: 1fr; gap: 8px; } + .summary-metrics dd { font-size: 20px; } + .prediction-values { font-size: 20px; } } @@ -150,7 +200,7 @@

{{ view.player.name }}

{% if view.notes %}{% endif %} diff --git a/templates/match.html b/templates/match.html index 240c75f..414d4b0 100644 --- a/templates/match.html +++ b/templates/match.html @@ -8,27 +8,52 @@

{{ view.match.map_name }}

{% endblock %} {% block content %} -
+
+

赛前预测

{% if view.prediction %}
A 队 {{ view.prediction.a }}%B 队 {{ view.prediction.b }}%

按赛前 ELO 估算

{% else %}

暂无完整赛前 ELO

{% endif %} +
+
+ {% for team in view.teams %} +
+

{{ team.name }}{{ team.players | length }} 人

{{ outcome(team.outcome) }}
+
{% for metric in team.summary %}
{{ metric.label }}
{{ metric.display }}
{% if metric.note %}{{ metric.note }}{% endif %}
{% endfor %}
+
+ {% endfor %} +
-

双方对比

- {% if view.comparisons %}{% for team in view.teams[:2] %}{% endfor %} - {% for row in view.comparisons %}{% for value in row['values'] %}{% endfor %}{% endfor %} -
指标{{ team.name }}
{{ row.label }}{{ value }}{% if row.notes[loop.index0] %}{{ row.notes[loop.index0] }}{% endif %}
{% else %}

暂无对比数据

{% endif %} -

兵种构成

按基础花费估算

- {% for team in view.teams %}

{{ team.name }}

- {% for category in team.composition %}
{{ category.name }}
{{ category.percentage }}%
- {% else %}

暂无单位数据

{% endfor %} - {% if team.composition_note %}

{{ team.composition_note }}

{% endif %} - {% endfor %} + {% if view.composition_rows %} +

左 {{ view.teams[0].name }}(深)· 右 {{ view.teams[1].name }}(浅)

+
+ {% for row in view.composition_rows %}
{{ row.label }}
+
{{ row['values'][0] }}{{ row['values'][1] }}
+ +
{% endfor %} +
+ {% else %}

暂无完整兵种构成

{% endif %} + {% for team in view.teams %}{% if team.composition_note %}

{{ team.name }}:{{ team.composition_note }}

{% endif %}{% endfor %} +
+

双方对比

+ {% if view.comparisons %} +

左 {{ view.teams[0].name }}右 {{ view.teams[1].name }}

+
+ {% for row in view.comparisons %}
{{ row.label }}
+
{{ row['values'][0] }}{{ row['values'][1] }}
+ + {% if row.notes[0] or row.notes[1] %}
{{ row.notes[0] }}{{ row.notes[1] }}
{% endif %} +
{% endfor %} +
{% else %}

暂无对比数据

{% endif %}
-

玩家

+

队伍玩家

{% for team in view.teams %}

{{ team.name }}{{ team.players | length }} 人

{% if team.outcome.key != 'unknown' %}{{ outcome(team.outcome) }}{% endif %}
diff --git a/tests/test_config.py b/tests/test_config.py index d8d90a8..f143792 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -4,6 +4,17 @@ from settings import Settings +def test_image_theme_defaults_to_light(): + assert Settings().theme == "light" + assert Settings.from_config({}).theme == "light" + assert Settings.from_config({"output": {}}).theme == "light" + + +@pytest.mark.parametrize("theme", ["light", "dark"]) +def test_image_theme_preserves_explicit_saved_value(theme): + assert Settings.from_config({"output": {"theme": theme}}).theme == theme + + def test_image_send_mode_defaults_to_base64(): assert Settings().image_send_mode == "base64" assert Settings.from_config({}).image_send_mode == "base64" diff --git a/tests/test_render.py b/tests/test_render.py index e4d52e3..9f4431a 100644 --- a/tests/test_render.py +++ b/tests/test_render.py @@ -1,8 +1,10 @@ """Presentation/security behavior; fixed synthetic values, no browser or API.""" from copy import deepcopy +import base64 from datetime import datetime, timezone from html.parser import HTMLParser +from pathlib import Path import re from jinja2 import Environment @@ -93,7 +95,7 @@ def test_external_text_is_escaped_in_every_card(view, kind): html = renderer.template(view) visible = VisibleHTML(html) assert "<img" in html - assert not any(tag in {"script", "iframe"} or (tag == "img" and not attrs.get("src", "").startswith("data:image/png;base64,")) for tag, attrs in visible.tags) + assert not any(tag in {"script", "iframe"} or (tag == "img" and not attrs.get("src", "").startswith("data:image/svg+xml;base64,")) for tag, attrs in visible.tags) assert attack in visible.text assert attack in renderer.text(view) @@ -153,7 +155,7 @@ def test_real_zero_and_unknown_stay_distinct(view): }]) text = Renderer().text(view) assert "击杀 / 阵亡 0 / 暂无" in text - assert "摧毁 / 损失 0.00 / 暂无" in text + assert "摧毁 / 损失 0 / 暂无" in text assert "分值 K/D 暂无" in text assert "胜负暂无" in text assert "0分00秒" in text @@ -268,7 +270,7 @@ def test_analysis_units_maps_and_categories_share_values(view): map_stats=[{"name": "Coast", "count": 8, "win_rate": 50}]) renderer = Renderer() for output in (renderer.text(view), VisibleHTML(renderer.template(view)).text): - for value in ("分析样本 100 场", "固定翼", "31.00%", "Tu-95", "72", "11683.00", "1.62", "Coast", "50.00%"): + for value in ("分析样本 100 场", "固定翼", "31%", "Tu-95", "72", "11683", "1.62", "Coast", "50%"): assert compact(value) in compact(output) @@ -302,10 +304,124 @@ def test_match_sections_and_footer_are_shared_across_cards(view): ]) renderer = Renderer() html = renderer.template(view) - assert html.index("赛前预测") < html.index("双方对比") < html.index("兵种构成") < html.index('class="team"') + assert html.index("赛前预测") < html.index("兵种构成") < html.index("双方对比") < html.index("队伍玩家") < html.index('class="team"') assert 'class="match-columns"' in html for output in (renderer.text(view), VisibleHTML(html).text): for value in ("64.00%", "36.00%", "234", "227", "步兵", "60.00%", "甲", "乙"): assert value in output assert "timeance/astrbot_plugin_BA_stats" in html and "数据来源 BATracer" in html - assert "data:image/png;base64," in html + assert "data:image/svg+xml;base64," in html + + +@pytest.mark.parametrize("kind", ["overview", "recent", "match"]) +@pytest.mark.parametrize("theme,color", [("light", "black"), ("dark", "white")]) +def test_official_github_mark_is_embedded_in_every_card(view, kind, theme, color): + view["kind"] = kind + html = Renderer(theme=theme).template(view) + images = [attrs for tag, attrs in VisibleHTML(html).tags if tag == "img"] + assert len(images) == 1 and images[0]["alt"] == "GitHub Logo" + logo = base64.b64decode(images[0]["src"].split(",", 1)[1]) + assert logo == (Path(__file__).parents[1] / "assets" / f"github-mark-{color}.svg").read_bytes() + assert "timeance/astrbot_plugin_BA_stats" in html and "数据来源 BATracer" in html + + +def test_renderer_defaults_to_light(): + assert 'data-theme="light"' in Renderer().template({"kind": "overview"}) + + +@pytest.mark.parametrize("values,expected", [ + ((3, 1), 75), ((0, 3), 0), ((3, 0), 100), + ((1.005, 1.004), 1.005 / 2.009 * 100), + ((0, 0), None), ((None, 3), None), ((3, None), None), +]) +def test_comparison_uses_one_continuous_bar_and_raw_denominator(view, values, expected): + view.update(kind="match", teams=[ + {"name": name, "metrics": [{"label": "伤害", "value": value}]} + for name, value in zip(("A 队", "B 队"), values) + ]) + html = Renderer().template(view) + tags = VisibleHTML(html).tags + tracks = [attrs for tag, attrs in tags if "comparison-track" in attrs.get("class", "").split()] + segments = [attrs for tag, attrs in tags if "segment" in attrs.get("class", "").split()] + assert len(tracks) == 1 + if expected is None: + assert segments == [] and "no-comparison" in tracks[0]["class"] + else: + widths = [float(attrs["style"].removeprefix("width:").removesuffix("%")) for attrs in segments] + assert widths == pytest.approx([expected, 100 - expected]) + assert [attrs["class"] for attrs in segments] == ["segment side-a", "segment side-b"] + if None in values: + assert "暂无" in tracks[0]["aria-label"] + elif values == (0, 0): + assert "A 队 0,B 队 0" in tracks[0]["aria-label"] + + +def test_composition_compares_each_original_share_with_one_shared_bar(view): + view.update(kind="match", teams=[ + {"name": "A 队", "composition": [{"name": "装甲", "percentage": 40}, {"name": "步兵", "percentage": 60}]}, + {"name": "B 队", "composition": [{"name": "装甲", "percentage": 20}, {"name": "步兵", "percentage": 30}]}, + ]) + html = Renderer().template(view) + tags = VisibleHTML(html).tags + tracks = [attrs for _, attrs in tags if attrs.get("role") == "img"] + segments = [attrs for _, attrs in tags if "role-a" in attrs.get("class", "") or "role-b" in attrs.get("class", "")] + assert len(tracks) == 2 and len(segments) == 4 + assert [attrs["class"] for attrs in segments] == ["segment role-armor role-a", "segment role-armor role-b", + "segment role-infantry role-a", "segment role-infantry role-b"] + widths = [float(attrs["style"].removeprefix("width:").removesuffix("%")) for attrs in segments] + assert widths == pytest.approx([100 * 40 / 60, 100 * 20 / 60, 100 * 60 / 90, 100 * 30 / 90]) + assert "A 队 40.00%,B 队 20.00%" in tracks[0]["aria-label"] + assert "A 队 60.00%,B 队 30.00%" in tracks[1]["aria-label"] + assert "左 A 队(深)· 右 B 队(浅)" in VisibleHTML(html).text + assert "composition-stack" not in html + + +@pytest.mark.parametrize("a,b,expected", [(0, 0, None), (None, 20, None), (20, None, None), (0, 20, 0)]) +def test_composition_distinguishes_zero_and_missing_share(view, a, b, expected): + view.update(kind="match", teams=[ + {"name": name, "composition": [{"name": "装甲", "percentage": value}]} + for name, value in zip(("A 队", "B 队"), (a, b)) + ]) + tags = VisibleHTML(Renderer().template(view)).tags + segments = [attrs for _, attrs in tags if "segment" in attrs.get("class", "").split()] + track = next(attrs for _, attrs in tags if attrs.get("role") == "img") + if expected is None: + assert not segments and "no-comparison" in track["class"] + else: + assert float(segments[0]["style"].removeprefix("width:").removesuffix("%")) == expected + assert ("暂无" in track["aria-label"]) is (a is None or b is None) + if a == b == 0: + assert "A 队 0.00%,B 队 0.00%" in track["aria-label"] + + +def test_only_complete_composition_can_supply_an_omitted_zero_category(view): + view.update(kind="match", teams=[ + {"name": "A 队", "composition": [{"name": "步兵", "percentage": 100}]}, + {"name": "B 队", "composition": [{"name": "装甲", "percentage": 30}]}, + ]) + tracks = [attrs for _, attrs in VisibleHTML(Renderer().template(view)).tags if attrs.get("role") == "img"] + assert "A 队 0.00%,B 队 30.00%" in tracks[0]["aria-label"] + assert "A 队 100.00%,B 队 暂无" in tracks[1]["aria-label"] + + +def test_unknown_composition_is_not_rendered_as_zero_or_renormalized(view): + view.update(kind="match", teams=[{"name": "A 队", "composition": [], "composition_note": "1 人缺单位数据,构成暂无"}]) + html = Renderer().template(view) + assert not any(attrs.get("role") == "img" for _, attrs in VisibleHTML(html).tags) + assert "暂无完整兵种构成" in VisibleHTML(html).text + assert "1 人缺单位数据" in VisibleHTML(html).text + + +def test_team_summary_distinguishes_post_match_elo_and_preserves_unknown_result(view): + view.update(kind="match", prediction={"a": 60, "b": 40}, teams=[ + {"name": "A 队", "outcome": "win", "metrics": [{"label": "赛后平均 ELO", "value": 1500}, {"label": "摧毁分", "value": 5000}], + "players": [{"elo": 1400, "elo_delta": 10}, {"elo": 1600, "elo_delta": None}]}, + {"name": "B 队", "outcome": "unknown", "players": [{"elo": 1500, "elo_delta": 20}]}, + ]) + html = Renderer().template(view) + summary = html.split('
', 1)[1].split('
', 1)[0] + text = compact(VisibleHTML('' + summary + '').text) + assert "赛前平均ELO暂无" in text and "赛后平均ELO1500" in text + assert "平均ELO变化暂无" in text and "平均ELO变化+20.00" in text + assert "胜负暂无" in text and text.count("胜利") == 1 + assert html.index('class="prediction"') < html.index('class="team-summaries"') < html.index('class="match-columns"') diff --git a/tests/test_report_data.py b/tests/test_report_data.py index fb427c1..8f6eb27 100644 --- a/tests/test_report_data.py +++ b/tests/test_report_data.py @@ -192,7 +192,7 @@ def test_match_team_metrics_sum_known_values_show_coverage_and_leave_missing_out view = report.s.match_view(report.result(match)) first = {item["label"]: item for item in view["teams"][0]["metrics"]} assert {key: item["value"] for key, item in first.items()} == { - "摧毁分": 350, "损失分": 100, "平均 ELO": 1100, "击杀": 5, "阵亡": 1, "伤害": 500, + "摧毁分": 350, "损失分": 100, "赛后平均 ELO": 1100, "击杀": 5, "阵亡": 1, "伤害": 500, "出兵花费": 1000, "占点": 0, "补给": 10, } assert first["伤害"]["note"] == "1/2 人有数据" @@ -278,6 +278,32 @@ def test_match_prediction_composition_and_a_b_order_reach_both_renderers(report) assert match == before +@pytest.mark.parametrize("a_before", [1600, None]) +def test_match_rating_times_reach_summary_from_real_payload(report, a_before): + from render import Renderer + + match = report.m.parse_match({"matchInfo": { + "StartTime": 1700000000, "EndTime": 1700001200, "TotalPlayTimeInSec": 1200, + "Data": { + "a": {"Id": "001", "Name": "A player", "TeamId": 0, "OldRating": a_before, "NewRating": 1620}, + "b": {"Id": "002", "Name": "B player", "TeamId": 1, "OldRating": 1600, "NewRating": 1580}, + }}}, "rating-times") + view = report.s.match_view(report.result(match)) + assert view["teams"][0]["players"][0]["elo_before"] == a_before + assert view["teams"][1]["players"][0]["elo_before"] == 1600 + assert [team["outcome"] for team in view["teams"]] == ["unknown", "unknown"] + assert view["prediction"] == ({"a": 50, "b": 50} if a_before is not None else None) + renderer = Renderer() + html, text = renderer.template(view), renderer.text(view) + summary = html.split('
', 1)[1].split('
', 1)[0] + assert summary.count('
赛前平均 ELO
1600
') == (2 if a_before is not None else 1) + assert ('
赛前平均 ELO
暂无
' in summary) is (a_before is None) + for rating in (1620, 1580): + assert f'
赛后平均 ELO
{rating}
' in summary + assert "赛后平均 ELO:1620 / 1580" in text + assert "当前平均 ELO" not in html + text + + def test_match_unknown_units_and_missing_ratings_stay_unknown_in_service(report): match = scoring_report_match(report) me = next(p for p in match.players if p.player_id == "001") diff --git a/tests/test_web_settings.py b/tests/test_web_settings.py index a33df8b..38a35cf 100644 --- a/tests/test_web_settings.py +++ b/tests/test_web_settings.py @@ -58,7 +58,9 @@ def test_snapshot_is_schema_based_and_never_discloses_legacy_credentials(editor) assert not any(text in public for text in ("PRIVATE_", "api_token", "client_id", "legacy_token")) fields = {field["path"]: field for field in snapshot["fields"]} assert fields["query.default_limit"]["value"] == 5 - assert fields["output.theme"]["options"] == ["dark", "light"] + assert fields["output.theme"]["value"] == fields["output.theme"]["default"] == "light" + assert fields["output.theme"]["options"] == ["light", "dark"] + assert fields["output.theme"]["labels"] == ["浅色", "深色"] assert fields["output.image_send_mode"]["value"] == "base64" assert fields["output.image_send_mode"]["default"] == "base64" assert fields["output.image_send_mode"]["options"] == ["base64", "file", "url"] @@ -68,6 +70,22 @@ def test_snapshot_is_schema_based_and_never_discloses_legacy_credentials(editor) assert not snapshot["reload_required"] and not snapshot["diagnostics"]["enabled"] +def test_saved_dark_theme_survives_unrelated_save(editor, web_module): + editor.config["output"] = {"theme": "dark"} + editor.config.save_config() + current = web_module.WebSettings(editor.config, web_module.Settings.from_config(editor.config), + editor.diagnostics) + snapshot = current.snapshot() + field = next(field for field in snapshot["fields"] if field["path"] == "output.theme") + assert field["value"] == "dark" and field["default"] == "light" + assert not snapshot["reload_required"] + result = save(current, {"diagnostics.enabled": True}) + assert current.config["output"]["theme"] == current._running["output.theme"] == "dark" + assert not result["reload_required"] + stored = json.loads(current.config.config_path.read_text(encoding="utf-8-sig")) + assert stored["output"]["theme"] == "dark" + + @pytest.mark.parametrize("image_send_mode", ["file", "url"]) def test_partial_save_retains_unmodified_values_and_applies_only_diagnostics(editor, image_send_mode): original_settings = editor._running.copy() @@ -122,7 +140,7 @@ def test_revision_detects_changes_from_native_dashboard_and_retains_external_fie revision = editor.snapshot()["revision"] external = dict(editor.config) external.pop("legacy_token") - external["output"] = {"theme": "light"} + external["output"] = {"theme": "dark"} editor.config.config_path.write_text(json.dumps(external), encoding="utf-8") assert editor.snapshot()["revision"] != revision with pytest.raises(web_module.SettingsError) as error: @@ -130,7 +148,7 @@ def test_revision_detects_changes_from_native_dashboard_and_retains_external_fie assert error.value.status_code == 409 assert not editor.diagnostics.enabled result = save(editor, {"diagnostics.enabled": True}) - assert editor.config["output"]["theme"] == "light" + assert editor.config["output"]["theme"] == "dark" assert "legacy_token" not in editor.config assert result["pending_restart"] == ["output.theme"] diff --git a/tools/check_settings_view.py b/tools/check_settings_view.py index 37e1c4d..42b1474 100644 --- a/tools/check_settings_view.py +++ b/tools/check_settings_view.py @@ -86,6 +86,9 @@ async def main(): image_mode = next(field for field in snapshot["fields"] if field["path"] == "output.image_send_mode") assert image_mode["default"] == image_mode["value"] == "base64" assert image_mode["options"] == ["base64", "file", "url"] + image_theme = next(field for field in snapshot["fields"] if field["path"] == "output.theme") + assert image_theme["default"] == image_theme["value"] == "light" + assert image_theme["options"] == ["light", "dark"] checks = [] async with async_playwright() as playwright: browser = await playwright.chromium.launch(headless=True) @@ -118,6 +121,10 @@ async def route(request): assert await image_select.input_value() == "base64" assert await image_select.locator("option").evaluate_all("options => options.map(option => option.value)") == ["base64", "file", "url"] assert await image_select.locator("option:checked").inner_text() == "Base64(默认)" + theme_select = page.locator("#setting-output-theme") + assert await theme_select.input_value() == "light" + assert await theme_select.locator("option").evaluate_all("options => options.map(option => option.value)") == ["light", "dark"] + assert await theme_select.locator("option:checked").inner_text() == "浅色" await page.evaluate("""() => { const p = document.createElement('p'); p.textContent = '合成预览 · 非运行实例'; p.className = 'muted'; document.querySelector('h1').after(p); @@ -156,6 +163,16 @@ async def route(request): assert "手动重载" in await page.locator("#apply-state").inner_text() assert await page.locator("#save").is_disabled() + await theme_select.select_option("dark") + await page.locator("#save").click() + await page.wait_for_function("document.getElementById('save-status').textContent.includes('手动重载')") + post = await page.evaluate("window.__posts.at(-1)") + assert post["payload"]["changes"] == {"output.theme": "dark"} + assert await theme_select.input_value() == "dark" + assert await theme_select.locator("..").get_attribute("data-pending") == "true" + assert await page.locator("html").get_attribute("data-theme") == theme + assert (await page.evaluate("window.__state.pending_restart")) == ["output.image_send_mode", "output.theme"] + await page.locator('[data-section="limits"]').click() await page.locator("#setting-limits-user_daily_limit").fill("21") await page.evaluate("window.__conflict = true") @@ -177,6 +194,7 @@ async def route(request): checks.append({"theme": theme, "viewport": label, **dimensions, "passed": True, "checks": ["host theme", "default collapsed", "diagnostic save", "download route", "image mode defaults to Base64", "file save pending restart", "url save pending restart", + "image theme defaults to light", "dark image theme save pending restart", "conflict preserves draft", "reload preserves draft", "restart indication", "fixed global quota"], "page_errors": errors, "external_requests": external}) await context.close() diff --git a/tools/render_previews.py b/tools/render_previews.py index 1949cea..848a4ee 100644 --- a/tools/render_previews.py +++ b/tools/render_previews.py @@ -32,7 +32,7 @@ def sample_views() -> dict[str, dict]: - """Deterministic synthetic data; deliberately unequal 3v2 team sizes.""" + """Deterministic synthetic data, including long names and missing fields.""" base = { "player": {"id": "sample-000001", "name": "蓝线观察员 · 合成样本"}, "scope": "最近取得 5 场 · 其中排位样本 4 场 · 非完整历史", @@ -72,19 +72,23 @@ def sample_views() -> dict[str, dict]: kind="match", scope="单场记录 · 排位 · 5 对 5 人", match={"id": "sample-match-001", "map_name": "合成港区", "mode": "ranked", "started_at": "2026-11-17T02:20:00Z", "duration_seconds": 2700, "winner": "A 队", "target_outcome": "win"}, - prediction={"a": 64, "b": 36}, + prediction={"a": 50, "b": 50}, teams=[ {"name": name, "outcome": "win" if side == 0 else "loss", - "metrics": [{"label": label, "value": values[side], "format": "integer"} + "metrics": [{"label": label, "value": values[side], "format": "decimal" if label == "赛后平均 ELO" else "integer"} for label, values in [("摧毁分", (32960, 31000)), ("损失分", (31000, 32960)), - ("击杀", (234, 227)), ("阵亡", (227, 234)), + ("赛后平均 ELO", (1833.25, 1816.75)), ("击杀", (234, 227)), ("阵亡", (227, 234)), ("伤害", (4983, 6480)), ("出兵花费", (40200, 43450)), ("占点", (15, 16)), ("补给消耗", (62685, 82319))]], - "composition": [{"name":"装甲", "percentage":40}, {"name":"步兵", "percentage":30}, {"name":"固定翼", "percentage":30}], + "composition": [{"name": role, "percentage": percentages[side]} + for role, percentages in [("装甲", (20, 17)), ("步兵", (13, 13)), ("侦察", (10, 8)), + ("炮兵", (5, 7)), ("防空", (17, 19)), ("直升机", (10, 15)), + ("固定翼", (24, 20)), ("后勤/运输", (1, 1))]], "composition_note":"合成样本", "players": [ {"id": base["player"]["id"] if side == 0 and index == 1 else f"sample-{side}-{index}", "name": base["player"]["name"] if side == 0 and index == 1 else f"合成队员 {side + 1}-{index + 1}", - "elo": 1800 + index * 12.5, "elo_delta": 8.25 if side == 0 else -8.25, + "elo_before": 1800 + index * 12.5, + "elo": 1800 + index * 12.5 + (8.25 if side == 0 else -8.25), "elo_delta": 8.25 if side == 0 else -8.25, "damage_dealt": 1253, "damage_received": 964, "objectives": 3, "spawned_value": 7570, "supply": 6926, "kills": 36, "losses": 24, "unit_exchange": 1.5, @@ -175,9 +179,14 @@ async def screenshots(artifacts: list[dict]) -> list[dict]: def main() -> int: + global OUTPUT parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--screenshots", action="store_true", help="use already installed local headless Chromium") + parser.add_argument("--output", type=Path, default=OUTPUT, help="preview directory inside this session") args = parser.parse_args() + OUTPUT = args.output.resolve() + if not OUTPUT.is_relative_to(SESSION): + parser.error("--output must stay inside this session directory") OUTPUT.mkdir(parents=True, exist_ok=True) artifacts = [] for sample_name, view in sample_views().items():