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:
+16
-1
@@ -39,7 +39,7 @@ from dotenv import load_dotenv
|
||||
load_dotenv(PROJECT_ROOT / ".env")
|
||||
|
||||
import uvicorn
|
||||
from fastapi import Depends, FastAPI
|
||||
from fastapi import Depends, FastAPI, HTTPException
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from fastapi.responses import FileResponse
|
||||
@@ -201,6 +201,21 @@ async def serve_frontend():
|
||||
}
|
||||
|
||||
|
||||
# 独立的报表页。**刻意不放进 api/webui** —— 那个目录是 gitignore 的 Vite 产物,
|
||||
# 每次构建都会把它清掉。这里的文件是仓库里的源码,直接原样发出去。
|
||||
# 页面本身不含数据,数据走 /api/monitor/matrix(带鉴权),所以这个壳不需要再拦一道。
|
||||
REPORTS_DIR = os.path.join(os.path.dirname(__file__), "reports")
|
||||
|
||||
|
||||
@app.get("/report/matrix")
|
||||
async def serve_matrix_report():
|
||||
"""日期 × 博主 的标签矩阵。"""
|
||||
path = os.path.join(REPORTS_DIR, "matrix.html")
|
||||
if not os.path.exists(path):
|
||||
raise HTTPException(status_code=404, detail="报表页面不存在")
|
||||
return FileResponse(path)
|
||||
|
||||
|
||||
@app.get("/api/health")
|
||||
async def health_check():
|
||||
return {"status": "ok"}
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
|
||||
@@ -0,0 +1,316 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>标签矩阵 · 综合采集平台</title>
|
||||
<!--
|
||||
独立的报表页,不走 Vite 构建:这样它不会被前端产物覆盖,也不用为它加一条路由。
|
||||
|
||||
数据来自 /api/monitor/matrix(同一套鉴权,靠同源 cookie)。
|
||||
转置在前端做 —— MySQL 5.7 没有 PIVOT,列数又随博主变化,SQL 里拼不出来。
|
||||
-->
|
||||
<style>
|
||||
:root {
|
||||
--bg: #0a0e14;
|
||||
--bg-soft: #111823;
|
||||
--line: #1e2a3a;
|
||||
--text: #e6f1ff;
|
||||
--muted: #7b8ba3;
|
||||
--cyan: #22d3ee;
|
||||
--green: #34d399;
|
||||
--pink: #f472b6;
|
||||
--orange: #fb923c;
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
body {
|
||||
margin: 0;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
font: 13px/1.5 system-ui, -apple-system, "Segoe UI", "PingFang SC",
|
||||
"Microsoft YaHei", sans-serif;
|
||||
}
|
||||
header {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 20;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
padding: 12px 16px;
|
||||
background: rgba(10, 14, 20, 0.92);
|
||||
backdrop-filter: blur(8px);
|
||||
border-bottom: 1px solid var(--line);
|
||||
}
|
||||
h1 { font-size: 15px; font-weight: 600; margin: 0; }
|
||||
h1 span { color: var(--cyan); }
|
||||
.spacer { flex: 1; }
|
||||
label { color: var(--muted); font-size: 12px; }
|
||||
select, button, a.btn {
|
||||
background: var(--bg-soft);
|
||||
color: var(--text);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 6px;
|
||||
padding: 5px 9px;
|
||||
font: inherit;
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
text-decoration: none;
|
||||
}
|
||||
select:hover, button:hover, a.btn:hover { border-color: var(--cyan); }
|
||||
#status { color: var(--muted); font-size: 12px; }
|
||||
#status.error { color: var(--pink); }
|
||||
|
||||
.wrap { overflow: auto; max-height: calc(100vh - 58px); }
|
||||
table {
|
||||
border-collapse: separate;
|
||||
border-spacing: 0;
|
||||
font-size: 12px;
|
||||
}
|
||||
thead th {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 10;
|
||||
background: #0d131c;
|
||||
border-bottom: 1px solid var(--line);
|
||||
border-right: 1px solid var(--line);
|
||||
padding: 8px 10px;
|
||||
text-align: left;
|
||||
white-space: nowrap;
|
||||
font-weight: 500;
|
||||
color: var(--muted);
|
||||
}
|
||||
/* 左上角那一格要同时钉住两个方向 */
|
||||
thead th:first-child {
|
||||
left: 0;
|
||||
z-index: 15;
|
||||
color: var(--cyan);
|
||||
}
|
||||
tbody th {
|
||||
position: sticky;
|
||||
left: 0;
|
||||
z-index: 5;
|
||||
background: #0d131c;
|
||||
border-right: 1px solid var(--line);
|
||||
border-bottom: 1px solid var(--line);
|
||||
padding: 7px 10px;
|
||||
text-align: left;
|
||||
white-space: nowrap;
|
||||
font-weight: 500;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
tbody td {
|
||||
border-right: 1px solid var(--line);
|
||||
border-bottom: 1px solid var(--line);
|
||||
padding: 5px 8px;
|
||||
white-space: nowrap;
|
||||
vertical-align: top;
|
||||
min-width: 88px;
|
||||
}
|
||||
tbody tr:hover th, tbody tr:hover td { background: #131c28; }
|
||||
|
||||
.count {
|
||||
display: inline-block;
|
||||
min-width: 16px;
|
||||
margin-right: 5px;
|
||||
color: var(--cyan);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.tag {
|
||||
display: inline-block;
|
||||
margin: 1px 3px 1px 0;
|
||||
padding: 1px 6px;
|
||||
border-radius: 999px;
|
||||
border: 1px solid rgba(34, 211, 238, 0.35);
|
||||
background: rgba(34, 211, 238, 0.1);
|
||||
color: var(--cyan);
|
||||
font-size: 11px;
|
||||
}
|
||||
.tag:nth-of-type(2n) {
|
||||
border-color: rgba(244, 114, 182, 0.35);
|
||||
background: rgba(244, 114, 182, 0.1);
|
||||
color: var(--pink);
|
||||
}
|
||||
.untagged { color: var(--muted); font-size: 11px; }
|
||||
.empty { color: #2a3646; }
|
||||
.legend {
|
||||
display: flex;
|
||||
gap: 14px;
|
||||
flex-wrap: wrap;
|
||||
padding: 8px 16px 14px;
|
||||
color: var(--muted);
|
||||
font-size: 11px;
|
||||
border-top: 1px solid var(--line);
|
||||
}
|
||||
.legend b { color: var(--text); font-weight: 500; }
|
||||
#login {
|
||||
display: none;
|
||||
margin: 40px auto;
|
||||
max-width: 360px;
|
||||
padding: 20px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 10px;
|
||||
background: var(--bg-soft);
|
||||
text-align: center;
|
||||
color: var(--muted);
|
||||
}
|
||||
#login a { color: var(--cyan); }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<header>
|
||||
<h1>标签<span>矩阵</span></h1>
|
||||
<label>平台
|
||||
<select id="platform">
|
||||
<option value="dy">抖音</option>
|
||||
<option value="xhs">小红书</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>范围
|
||||
<select id="days">
|
||||
<option value="7">最近 7 天</option>
|
||||
<option value="14">最近 14 天</option>
|
||||
<option value="30">最近 30 天</option>
|
||||
</select>
|
||||
</label>
|
||||
<button id="refresh">刷新</button>
|
||||
<span id="status"></span>
|
||||
<span class="spacer"></span>
|
||||
<a class="btn" href="/">返回控制台</a>
|
||||
</header>
|
||||
|
||||
<div id="login">
|
||||
请先在<a href="/">控制台</a>登录,再回到这个页面。
|
||||
</div>
|
||||
|
||||
<div class="wrap" id="wrap"></div>
|
||||
<div class="legend">
|
||||
<span><b>N</b> = 当天发出的作品条数</span>
|
||||
<span><b>无标签</b> = 发了但没打标签</span>
|
||||
<span><b>空白</b> = 当天没发作品</span>
|
||||
<span>标签按词表里的顺序排列</span>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const params = new URLSearchParams(location.search);
|
||||
const platformSel = document.getElementById('platform');
|
||||
const daysSel = document.getElementById('days');
|
||||
const statusEl = document.getElementById('status');
|
||||
const wrap = document.getElementById('wrap');
|
||||
const login = document.getElementById('login');
|
||||
|
||||
platformSel.value = params.get('platform') || 'dy';
|
||||
daysSel.value = params.get('days') || '14';
|
||||
|
||||
function setStatus(text, isError) {
|
||||
statusEl.textContent = text;
|
||||
statusEl.className = isError ? 'error' : '';
|
||||
}
|
||||
|
||||
function cellNode(cell) {
|
||||
const td = document.createElement('td');
|
||||
if (!cell) {
|
||||
const dot = document.createElement('span');
|
||||
dot.className = 'empty';
|
||||
dot.textContent = '·';
|
||||
td.appendChild(dot);
|
||||
return td;
|
||||
}
|
||||
const count = document.createElement('span');
|
||||
count.className = 'count';
|
||||
count.textContent = cell.count;
|
||||
td.appendChild(count);
|
||||
|
||||
if (!cell.tags || cell.tags.length === 0) {
|
||||
const none = document.createElement('span');
|
||||
none.className = 'untagged';
|
||||
none.textContent = '无标签';
|
||||
td.appendChild(none);
|
||||
return td;
|
||||
}
|
||||
for (const tag of cell.tags) {
|
||||
const chip = document.createElement('span');
|
||||
chip.className = 'tag';
|
||||
chip.textContent = tag;
|
||||
td.appendChild(chip);
|
||||
}
|
||||
return td;
|
||||
}
|
||||
|
||||
function render(data) {
|
||||
wrap.innerHTML = '';
|
||||
if (!data.dates.length) {
|
||||
setStatus('这个范围内没有作品');
|
||||
return;
|
||||
}
|
||||
setStatus(`${data.dates.length} 天 · ${data.creators.length} 个博主`);
|
||||
|
||||
const table = document.createElement('table');
|
||||
const thead = document.createElement('thead');
|
||||
const headRow = document.createElement('tr');
|
||||
const corner = document.createElement('th');
|
||||
corner.textContent = '日期';
|
||||
headRow.appendChild(corner);
|
||||
for (const creator of data.creators) {
|
||||
const th = document.createElement('th');
|
||||
th.textContent = creator.name;
|
||||
headRow.appendChild(th);
|
||||
}
|
||||
thead.appendChild(headRow);
|
||||
table.appendChild(thead);
|
||||
|
||||
const tbody = document.createElement('tbody');
|
||||
for (const day of data.dates) {
|
||||
const tr = document.createElement('tr');
|
||||
const th = document.createElement('th');
|
||||
th.textContent = day;
|
||||
tr.appendChild(th);
|
||||
const rowCells = data.cells[day] || {};
|
||||
for (const creator of data.creators) {
|
||||
tr.appendChild(cellNode(rowCells[creator.hash]));
|
||||
}
|
||||
tbody.appendChild(tr);
|
||||
}
|
||||
table.appendChild(tbody);
|
||||
wrap.appendChild(table);
|
||||
}
|
||||
|
||||
async function load() {
|
||||
const platform = platformSel.value;
|
||||
const days = daysSel.value;
|
||||
// 把当前选择写进地址栏,方便直接收藏/分享到某一组条件
|
||||
const url = new URL(location.href);
|
||||
url.searchParams.set('platform', platform);
|
||||
url.searchParams.set('days', days);
|
||||
history.replaceState(null, '', url);
|
||||
|
||||
setStatus('加载中…');
|
||||
wrap.innerHTML = '';
|
||||
login.style.display = 'none';
|
||||
try {
|
||||
const response = await fetch(
|
||||
`/api/monitor/matrix?platform=${encodeURIComponent(platform)}&days=${days}`,
|
||||
{ credentials: 'same-origin' },
|
||||
);
|
||||
if (response.status === 401) {
|
||||
login.style.display = 'block';
|
||||
setStatus('未登录', true);
|
||||
return;
|
||||
}
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP ${response.status}`);
|
||||
}
|
||||
render(await response.json());
|
||||
} catch (err) {
|
||||
setStatus(`加载失败:${err.message}`, true);
|
||||
}
|
||||
}
|
||||
|
||||
document.getElementById('refresh').addEventListener('click', load);
|
||||
platformSel.addEventListener('change', load);
|
||||
daysSel.addEventListener('change', load);
|
||||
load();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -749,6 +749,20 @@ def _to_xlsx(rows: List[Dict[str, Any]], columns: List[tuple[str, str]], sheet:
|
||||
return output.getvalue()
|
||||
|
||||
|
||||
@router.get("/matrix")
|
||||
async def get_tag_matrix(
|
||||
platform: str = Query(default=PLATFORM_XHS, description="dy / xhs"),
|
||||
days: int = Query(default=14, ge=1, le=90, description="回看多少天"),
|
||||
):
|
||||
"""日期 × 博主 → 当天发出去的作品标签。
|
||||
|
||||
返回**长表结构**(dates / creators / cells),转置交给前端的报表页
|
||||
(``/report/matrix``)。理由见 ``service.daily_tag_matrix`` 的说明。
|
||||
"""
|
||||
async with get_session() as session:
|
||||
return await service.daily_tag_matrix(session, platform, days)
|
||||
|
||||
|
||||
@router.get("/report")
|
||||
async def get_report(
|
||||
task_id: Optional[List[int]] = Query(
|
||||
|
||||
Reference in New Issue
Block a user