feat(report): 日期列补满区间、博主补上「只有资料没有作品」的号、加条件格式
Deploy VitePress site to Pages / build (push) Canceled after 0s
Deploy VitePress site to Pages / Deploy (push) Canceled after 0s

三个问题一起修:

1. **日期列按完整区间生成**。原先只取「有作品的那几天」,某天断更那一列就消失了 ——
   看图的人会以为漏采,而空白本身也是信息。现在固定输出最近 N 个自然日(含今天)。

2. **博主名单改成「账号快照 ∪ 作品」**,和界面一致。线上有 3 个号(昵称是纯数字
   uid、作品数 0)只存在于快照表里,一条作品都没有;名单只从作品里取的话它们整行
   消失。现在它们会占一行,格子里是空的。

3. **条件格式**:头部加「高亮 [指标] ≥ [数值]」。命中的格子换底色 + 粉色描边,
   只在本地重画,不重新请求数据;条件写进地址栏(`cf=likes:1000`)可直接收藏。

细节:
* 计数/指标的去重口径不变(同一作品挂两个任务只算一次);
* 指标未知仍是 None,参与不了条件格式 —— 不会被当成 0 高亮。

测试 11 条(新增:只有资料没有作品的号仍占一行、日期列是完整区间)。
This commit is contained in:
butubb
2026-10-22 14:16:26 +08:00
parent ffafd90073
commit 15c52553d0
3 changed files with 167 additions and 30 deletions
+56 -24
View File
@@ -20,7 +20,7 @@
import asyncio import asyncio
import re import re
from datetime import datetime from datetime import datetime, timedelta
from typing import Any, Dict, List, Optional, Sequence, Tuple from typing import Any, Dict, List, Optional, Sequence, Tuple
from urllib.parse import parse_qs, urlparse from urllib.parse import parse_qs, urlparse
@@ -1499,7 +1499,17 @@ async def daily_tag_matrix(
if not task_ids: if not task_ids:
return empty return empty
since = get_current_timestamp() - max(1, days) * 86_400_000 # 日期列**按完整区间生成**,不是只取「有作品的那几天」。否则某天断更,那一列会
# 悄无声息地消失,看图的人会以为是漏采 —— 空白本身也是信息。
first_day = datetime.now().replace(
hour=0, minute=0, second=0, microsecond=0
) - timedelta(days=max(1, days) - 1)
dates = [
(first_day + timedelta(days=offset)).strftime("%Y-%m-%d")
for offset in range(max(1, days))
][::-1]
since = int(first_day.timestamp() * 1000)
notes = ( notes = (
await session.execute( await session.execute(
select( select(
@@ -1517,26 +1527,25 @@ async def daily_tag_matrix(
.order_by(MonitorNote.published_at.desc()) .order_by(MonitorNote.published_at.desc())
) )
).all() ).all()
if not notes:
return empty
note_ids = {row.note_id for row in notes} note_ids = {row.note_id for row in notes}
# 标签一次取完,按 note_id 归组;顺序跟词表里的 sort_order 一致。 # 标签一次取完,按 note_id 归组;顺序跟词表里的 sort_order 一致。
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]] = {} tags_by_note: Dict[str, List[str]] = {}
for note_id, name in tag_rows: if note_ids:
tags_by_note.setdefault(note_id, []).append(name) 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()
for note_id, name in tag_rows:
tags_by_note.setdefault(note_id, []).append(name)
# 指标:每篇作品取**最近一轮**(run_id 最大)。没有指标行的作品不参与求和 —— # 指标:每篇作品取**最近一轮**(run_id 最大)。没有指标行的作品不参与求和 ——
# 未知和 0 是两回事,格子的提示里会显示成「—」而不是「0」。 # 未知和 0 是两回事,格子的提示里会显示成「—」而不是「0」。
@@ -1563,8 +1572,35 @@ async def daily_tag_matrix(
if current is None or metric.run_id > current.run_id: if current is None or metric.run_id > current.run_id:
latest_metric[key] = metric latest_metric[key] = metric
# 博主名单取**账号快照 ∪ 作品**,和界面一致。只在快照里出现的号也要占一行 ——
# 典型是资料读成纯数字昵称、作品数为 0 的那几个;只从作品里取的话它们会整行消失。
stat_rows = (
await session.execute(
select(
MonitorCreatorStat.creator_hash,
MonitorCreatorStat.nickname,
MonitorCreatorStat.captured_at,
).where(
MonitorCreatorStat.task_id.in_(task_ids),
MonitorCreatorStat.creator_hash != "",
)
)
).all()
latest_nickname: Dict[str, tuple] = {}
for stat in stat_rows:
current = latest_nickname.get(stat.creator_hash)
if current is None or stat.captured_at > current[1]:
latest_nickname[stat.creator_hash] = (stat.nickname or "", stat.captured_at)
known: Dict[str, str] = {
hash_: (name or f"未知({hash_[:6]})")
for hash_, (name, _captured) in latest_nickname.items()
}
for row in notes:
key = row.creator_hash or f"note:{row.note_id}"
known.setdefault(key, row.creator_name or f"未知({key[:6]})")
cells: Dict[str, Dict[str, Dict[str, Any]]] = {} cells: Dict[str, Dict[str, Dict[str, Any]]] = {}
names: Dict[str, str] = {}
# 同一个作品可能挂在多个任务下(monitor_note 的唯一键是 (task_id, note_id)), # 同一个作品可能挂在多个任务下(monitor_note 的唯一键是 (task_id, note_id)),
# 不按 note_id 去重会把计数和指标都翻倍。 # 不按 note_id 去重会把计数和指标都翻倍。
seen: set = set() seen: set = set()
@@ -1577,7 +1613,6 @@ async def daily_tag_matrix(
day = datetime.fromtimestamp((row.published_at or 0) / 1000).strftime("%Y-%m-%d") day = datetime.fromtimestamp((row.published_at or 0) / 1000).strftime("%Y-%m-%d")
creator_key = row.creator_hash or f"note:{row.note_id}" creator_key = row.creator_hash or f"note:{row.note_id}"
names.setdefault(creator_key, row.creator_name or "")
bucket = cells.setdefault(day, {}).setdefault( bucket = cells.setdefault(day, {}).setdefault(
creator_key, creator_key,
@@ -1607,17 +1642,14 @@ async def daily_tag_matrix(
if value is not None: if value is not None:
bucket[key] = (bucket[key] or 0) + value bucket[key] = (bucket[key] or 0) + value
creators = [ creators = [{"hash": hash_, "name": name} for hash_, name in known.items()]
{"hash": key, "name": name or f"未知({key[:6]})"}
for key, name in names.items()
]
creators.sort(key=lambda item: item["name"]) creators.sort(key=lambda item: item["name"])
return { return {
"platform": platform, "platform": platform,
"days": days, "days": days,
"task_id": task_id, "task_id": task_id,
"dates": sorted(cells, reverse=True), "dates": dates,
"creators": creators, "creators": creators,
"cells": cells, "cells": cells,
} }
+68 -2
View File
@@ -46,7 +46,7 @@
h1 span { color: var(--cyan); } h1 span { color: var(--cyan); }
.spacer { flex: 1; } .spacer { flex: 1; }
label { color: var(--muted); font-size: 12px; } label { color: var(--muted); font-size: 12px; }
select, button, a.btn { select, input, button, a.btn {
background: var(--bg-soft); background: var(--bg-soft);
color: var(--text); color: var(--text);
border: 1px solid var(--line); border: 1px solid var(--line);
@@ -58,7 +58,9 @@
text-decoration: none; text-decoration: none;
} }
select { max-width: 200px; } select { max-width: 200px; }
select:hover, button:hover, a.btn:hover { border-color: var(--cyan); } input[type="number"] { width: 78px; cursor: text; }
select:hover, input:hover, button:hover, a.btn:hover { border-color: var(--cyan); }
input:focus { outline: none; border-color: var(--cyan); }
#status { color: var(--muted); font-size: 12px; } #status { color: var(--muted); font-size: 12px; }
#status.error { color: var(--pink); } #status.error { color: var(--pink); }
@@ -133,6 +135,14 @@
} }
.untagged { color: var(--muted); font-size: 11px; } .untagged { color: var(--muted); font-size: 11px; }
.empty { color: #2a3646; } .empty { color: #2a3646; }
/* 条件格式命中的格子。用 inset 描边而不是 box-shadow 扩散:不改变布局,
也不会触发整行重排。 */
tbody td.hit {
background: rgba(244, 114, 182, 0.16);
box-shadow: inset 0 0 0 1px rgba(244, 114, 182, 0.55);
}
tbody tr:hover td.hit { background: rgba(244, 114, 182, 0.24); }
.legend { .legend {
display: flex; display: flex;
gap: 14px; gap: 14px;
@@ -201,6 +211,16 @@
<option value="30">最近 30 天</option> <option value="30">最近 30 天</option>
</select> </select>
</label> </label>
<label title="满足条件的格子会高亮">高亮
<select id="cfMetric">
<option value="likes">点赞</option>
<option value="comments">评论</option>
<option value="collected">收藏</option>
<option value="shares">分享</option>
<option value="count">条数</option>
</select>
≥ <input id="cfValue" type="number" min="0" step="1" placeholder="数值" />
</label>
<button id="refresh">刷新</button> <button id="refresh">刷新</button>
<span id="status"></span> <span id="status"></span>
<span class="spacer"></span> <span class="spacer"></span>
@@ -229,6 +249,10 @@
const wrap = document.getElementById('wrap'); const wrap = document.getElementById('wrap');
const login = document.getElementById('login'); const login = document.getElementById('login');
const tip = document.getElementById('tip'); const tip = document.getElementById('tip');
const cfMetricSel = document.getElementById('cfMetric');
const cfValueInput = document.getElementById('cfValue');
// 条件格式只在本地重渲染,不重新请求 —— 指标已经随格子一起返回了。
let lastData = null;
function setStatus(text, isError) { function setStatus(text, isError) {
statusEl.textContent = text; statusEl.textContent = text;
@@ -244,6 +268,32 @@
tip.style.display = 'none'; tip.style.display = 'none';
} }
function cfThreshold() {
const raw = cfValueInput.value.trim();
if (raw === '') return null;
const value = Number(raw);
return Number.isFinite(value) ? value : null;
}
function cfHit(cell) {
if (!cell) return false;
const threshold = cfThreshold();
if (threshold === null) return false;
const value = cell[cfMetricSel.value];
return value !== null && value !== undefined && value >= threshold;
}
function syncCfUrl() {
const url = new URL(location.href);
const threshold = cfThreshold();
if (threshold === null) {
url.searchParams.delete('cf');
} else {
url.searchParams.set('cf', cfMetricSel.value + ':' + threshold);
}
history.replaceState(null, '', url);
}
function buildTip(cell, day, creatorName) { function buildTip(cell, day, creatorName) {
// 用 DOM 拼,不用 innerHTML —— 昵称是平台来的文本,不能当 HTML 解释。 // 用 DOM 拼,不用 innerHTML —— 昵称是平台来的文本,不能当 HTML 解释。
tip.textContent = ''; tip.textContent = '';
@@ -330,12 +380,14 @@
td._cell = cell; td._cell = cell;
td.dataset.day = day; td.dataset.day = day;
td.dataset.creator = creatorName; td.dataset.creator = creatorName;
if (cfHit(cell)) td.classList.add('hit');
td.addEventListener('mouseenter', showTip); td.addEventListener('mouseenter', showTip);
td.addEventListener('mouseleave', hideTip); td.addEventListener('mouseleave', hideTip);
return td; return td;
} }
function render(data) { function render(data) {
lastData = data;
wrap.innerHTML = ''; wrap.innerHTML = '';
if (!data.dates.length) { if (!data.dates.length) {
setStatus('这个范围内没有作品'); setStatus('这个范围内没有作品');
@@ -444,6 +496,13 @@
if (wanted && Array.from(taskSel.options).some((o) => o.value === wanted)) { if (wanted && Array.from(taskSel.options).some((o) => o.value === wanted)) {
taskSel.value = wanted; taskSel.value = wanted;
} }
const cf = params.get('cf');
if (cf && cf.includes(':')) {
const parts = cf.split(':');
const allowed = ['likes', 'comments', 'collected', 'shares', 'count'];
if (allowed.includes(parts[0])) cfMetricSel.value = parts[0];
cfValueInput.value = parts[1];
}
await load(); await load();
} }
@@ -454,6 +513,13 @@
}); });
taskSel.addEventListener('change', load); taskSel.addEventListener('change', load);
daysSel.addEventListener('change', load); daysSel.addEventListener('change', load);
// 条件格式只重画表格,不重新请求数据。
const rerender = () => {
if (lastData) render(lastData);
syncCfUrl();
};
cfMetricSel.addEventListener('change', rerender);
cfValueInput.addEventListener('input', rerender);
// 表格滚动时把提示收起来,否则它会停在原地、和格子脱节。 // 表格滚动时把提示收起来,否则它会停在原地、和格子脱节。
wrap.addEventListener('scroll', hideTip); wrap.addEventListener('scroll', hideTip);
init(); init();
+43 -4
View File
@@ -21,6 +21,7 @@ from api.monitor import db as monitor_db
from api.monitor import service from api.monitor import service
from api.monitor.models import ( from api.monitor.models import (
MODE_CREATOR, MODE_CREATOR,
MonitorCreatorStat,
MonitorNote, MonitorNote,
MonitorNoteMetric, MonitorNoteMetric,
MonitorNoteTag, MonitorNoteTag,
@@ -150,7 +151,9 @@ async def test_same_day_notes_collapse_with_tags_union(db):
async with monitor_db.get_session() as session: async with monitor_db.get_session() as session:
data = await service.daily_tag_matrix(session, "dy", days=7) data = await service.daily_tag_matrix(session, "dy", days=7)
assert data["dates"] == [_day(today)] # 日期列是**完整区间**(7 天),不是只有有作品的那天
assert len(data["dates"]) == 7
assert data["dates"][0] == _day(today)
assert [c["name"] for c in data["creators"]] == ["博主A"] assert [c["name"] for c in data["creators"]] == ["博主A"]
cell = data["cells"][_day(today)]["hash-a"] cell = data["cells"][_day(today)]["hash-a"]
@@ -183,8 +186,11 @@ async def test_notes_outside_the_window_are_excluded(db):
async with monitor_db.get_session() as session: async with monitor_db.get_session() as session:
data = await service.daily_tag_matrix(session, "dy", days=7) data = await service.daily_tag_matrix(session, "dy", days=7)
assert data["dates"] == [_day(now - 1000)] assert len(data["dates"]) == 7
assert data["cells"][_day(now - 1000)]["hash-a"]["count"] == 1 assert data["dates"][0] == _day(now)
assert data["cells"][_day(now)]["hash-a"]["count"] == 1
# 40 天前那天不该出现在 cells 里
assert _day(now - 40 * DAY_MS) not in data["cells"]
@pytest.mark.asyncio @pytest.mark.asyncio
@@ -217,6 +223,39 @@ async def test_no_tasks_returns_an_empty_shape(db):
} }
async def _stat(task_id: int, creator_hash: str, nickname: str) -> None:
async with monitor_db.get_session() as session:
session.add(
MonitorCreatorStat(
task_id=task_id,
run_id=1,
creator_hash=creator_hash,
nickname=nickname,
creator_id="",
works_count=0,
captured_at=get_current_timestamp(),
)
)
@pytest.mark.asyncio
async def test_creators_without_notes_still_get_a_row(db):
"""只在账号快照里出现的号不能消失。
典型是资料读成纯数字昵称、作品数为 0 的那几个 —— 它们一条作品都没有,如果博主
名单只从作品里取,整行就不见了。日期列也一样:一行数据都没有时,7 个日期还在。
"""
task_id = await _task()
await _stat(task_id, "hash-num", "26828346705")
async with monitor_db.get_session() as session:
data = await service.daily_tag_matrix(session, "dy", days=7)
assert [c["name"] for c in data["creators"]] == ["26828346705"]
assert data["cells"] == {}
assert len(data["dates"]) == 7
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_cell_sums_the_latest_metric_of_each_note(db): async def test_cell_sums_the_latest_metric_of_each_note(db):
task_id = await _task() task_id = await _task()
@@ -292,7 +331,7 @@ async def test_endpoint_returns_the_long_shape(client):
assert response.status_code == 200 assert response.status_code == 200
body = response.json() body = response.json()
assert body["dates"] == [_day(now)] assert _day(now) in body["dates"]
assert body["creators"][0]["name"] == "博主A" assert body["creators"][0]["name"] == "博主A"
cell = body["cells"][_day(now)]["hash-a"] cell = body["cells"][_day(now)]["hash-a"]
assert cell["count"] == 1 assert cell["count"] == 1