feat(report): 自带「标签矩阵」报表页,侧边栏一键跳转
不再依赖外部报表工具。`/report/matrix` 是后端直接发的一份静态 HTML(不走 Vite
构建,所以不会被 `api/webui` 的产物清理覆盖),数据来自 `/api/monitor/matrix`
(同一套鉴权,靠同源 cookie)。
形状正是用户要的:行=日期(新到旧),列=博主,格子里是当天发出去的标签。
三种格子语义分开:空白=当天没发、无标签=发了没打标签、标签=实际打上的。
**为什么转置放在前端。** MySQL 5.7 没有 PIVOT,而列数随博主变化;写死昵称的
SQL 一改名就废(上一轮的教训)。所以接口只返回长表结构
`{dates, creators, cells}`,前端按 creator_hash 转置 —— 改名、加博主都不用动
任何 SQL。分组/去重放在 `service.daily_tag_matrix` 里做(Python 侧),这样测试
能跑在 SQLite 上,不用 MySQL 的日期函数。
去重特意处理了两件事:
* 同一天同一个号的多条作品合成一格,计数相加、标签取并集并按词表顺序;
* 同一个作品挂在两个任务下(唯一键是 (task_id, note_id))只算一次,否则计数翻倍。
侧边栏加「标签矩阵」入口,新标签页打开(宽表要占满整屏)。
测试:6 条,覆盖分组/排序/窗口/跨任务去重/空结果/接口形状。
This commit is contained in:
@@ -20,6 +20,7 @@
|
||||
|
||||
import asyncio
|
||||
import re
|
||||
from datetime import datetime
|
||||
from typing import Any, Dict, List, Optional, Sequence, Tuple
|
||||
from urllib.parse import parse_qs, urlparse
|
||||
|
||||
@@ -1443,3 +1444,111 @@ async def mark_events_read(session: AsyncSession, task_id: Optional[int] = None)
|
||||
for row in rows:
|
||||
row.is_read = True
|
||||
return len(rows)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 标签矩阵(日期 × 博主)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
async def daily_tag_matrix(
|
||||
session: AsyncSession, platform: str, days: int
|
||||
) -> Dict[str, Any]:
|
||||
"""日期 × 博主 → 当天发出去的作品标签。给 ``/report/matrix`` 用。
|
||||
|
||||
**为什么分组放在 Python 里做。** MySQL 5.7 没有 PIVOT,而列数随博主变化;用 SQL
|
||||
拼动态列只能靠 PREPARE 拼一整段字符串,既没法参数化,也没法在测试用的 SQLite 上
|
||||
跑。这里只读两次(作品、标签),分组交给 Python —— 一个窗口内的作品量级是几百条,
|
||||
代价可以忽略。
|
||||
|
||||
返回**长表结构**,转置由前端做:
|
||||
|
||||
{"dates": ["2026-10-21", ...], # 新到旧
|
||||
"creators": [{"hash": ..., "name": ...}], # 按昵称排序
|
||||
"cells": {"2026-10-21": {"<hash>": {"count": 2, "tags": ["大字报", "养号"]}}}}
|
||||
"""
|
||||
task_ids = await platform_task_ids(session, platform)
|
||||
empty = {
|
||||
"platform": platform,
|
||||
"days": days,
|
||||
"dates": [],
|
||||
"creators": [],
|
||||
"cells": {},
|
||||
}
|
||||
if not task_ids:
|
||||
return empty
|
||||
|
||||
since = get_current_timestamp() - max(1, days) * 86_400_000
|
||||
notes = (
|
||||
await session.execute(
|
||||
select(
|
||||
MonitorNote.note_id,
|
||||
MonitorNote.creator_hash,
|
||||
MonitorNote.creator_name,
|
||||
MonitorNote.published_at,
|
||||
)
|
||||
.where(
|
||||
MonitorNote.task_id.in_(task_ids),
|
||||
MonitorNote.published_at.is_not(None),
|
||||
MonitorNote.published_at >= since,
|
||||
)
|
||||
.order_by(MonitorNote.published_at.desc())
|
||||
)
|
||||
).all()
|
||||
if not notes:
|
||||
return empty
|
||||
|
||||
# 标签一次取完,按 note_id 归组;顺序跟词表里的 sort_order 一致。
|
||||
note_ids = {row.note_id for row in notes}
|
||||
tag_rows = (
|
||||
await session.execute(
|
||||
select(MonitorNoteTag.note_id, MonitorTag.name)
|
||||
.join(MonitorTag, MonitorTag.id == MonitorNoteTag.tag_id)
|
||||
.where(
|
||||
MonitorNoteTag.platform == platform,
|
||||
MonitorNoteTag.note_id.in_(note_ids),
|
||||
)
|
||||
.order_by(MonitorTag.sort_order, MonitorTag.id)
|
||||
)
|
||||
).all()
|
||||
tags_by_note: Dict[str, List[str]] = {}
|
||||
for note_id, name in tag_rows:
|
||||
tags_by_note.setdefault(note_id, []).append(name)
|
||||
|
||||
cells: Dict[str, Dict[str, Dict[str, Any]]] = {}
|
||||
names: Dict[str, str] = {}
|
||||
# 同一个作品可能挂在多个任务下(monitor_note 的唯一键是 (task_id, note_id)),
|
||||
# 不按 note_id 去重会把计数翻倍。
|
||||
seen: set = set()
|
||||
|
||||
for row in notes:
|
||||
note_key = (row.creator_hash, row.note_id)
|
||||
if note_key in seen:
|
||||
continue
|
||||
seen.add(note_key)
|
||||
|
||||
day = datetime.fromtimestamp((row.published_at or 0) / 1000).strftime("%Y-%m-%d")
|
||||
creator_key = row.creator_hash or f"note:{row.note_id}"
|
||||
names.setdefault(creator_key, row.creator_name or "")
|
||||
|
||||
bucket = cells.setdefault(day, {}).setdefault(
|
||||
creator_key, {"count": 0, "tags": []}
|
||||
)
|
||||
bucket["count"] += 1
|
||||
for tag in tags_by_note.get(row.note_id, []):
|
||||
if tag not in bucket["tags"]:
|
||||
bucket["tags"].append(tag)
|
||||
|
||||
creators = [
|
||||
{"hash": key, "name": name or f"未知({key[:6]})"}
|
||||
for key, name in names.items()
|
||||
]
|
||||
creators.sort(key=lambda item: item["name"])
|
||||
|
||||
return {
|
||||
"platform": platform,
|
||||
"days": days,
|
||||
"dates": sorted(cells, reverse=True),
|
||||
"creators": creators,
|
||||
"cells": cells,
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user