diff --git a/api/monitor/service.py b/api/monitor/service.py index 5362dd2..ae852f0 100644 --- a/api/monitor/service.py +++ b/api/monitor/service.py @@ -20,7 +20,7 @@ import asyncio import re -from datetime import datetime +from datetime import datetime, timedelta from typing import Any, Dict, List, Optional, Sequence, Tuple from urllib.parse import parse_qs, urlparse @@ -1499,7 +1499,17 @@ async def daily_tag_matrix( if not task_ids: 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 = ( await session.execute( select( @@ -1517,26 +1527,25 @@ async def daily_tag_matrix( .order_by(MonitorNote.published_at.desc()) ) ).all() - if not notes: - return empty note_ids = {row.note_id for row in notes} # 标签一次取完,按 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]] = {} - for note_id, name in tag_rows: - tags_by_note.setdefault(note_id, []).append(name) + if note_ids: + 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 最大)。没有指标行的作品不参与求和 —— # 未知和 0 是两回事,格子的提示里会显示成「—」而不是「0」。 @@ -1563,8 +1572,35 @@ async def daily_tag_matrix( if current is None or metric.run_id > current.run_id: 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]]] = {} - names: Dict[str, str] = {} # 同一个作品可能挂在多个任务下(monitor_note 的唯一键是 (task_id, note_id)), # 不按 note_id 去重会把计数和指标都翻倍。 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") 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, @@ -1607,17 +1642,14 @@ async def daily_tag_matrix( if value is not None: bucket[key] = (bucket[key] or 0) + value - creators = [ - {"hash": key, "name": name or f"未知({key[:6]})"} - for key, name in names.items() - ] + creators = [{"hash": hash_, "name": name} for hash_, name in known.items()] creators.sort(key=lambda item: item["name"]) return { "platform": platform, "days": days, "task_id": task_id, - "dates": sorted(cells, reverse=True), + "dates": dates, "creators": creators, "cells": cells, } diff --git a/api/reports/matrix.html b/api/reports/matrix.html index c86ff02..cc2cae3 100644 --- a/api/reports/matrix.html +++ b/api/reports/matrix.html @@ -46,7 +46,7 @@ h1 span { color: var(--cyan); } .spacer { flex: 1; } label { color: var(--muted); font-size: 12px; } - select, button, a.btn { + select, input, button, a.btn { background: var(--bg-soft); color: var(--text); border: 1px solid var(--line); @@ -58,7 +58,9 @@ text-decoration: none; } 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.error { color: var(--pink); } @@ -133,6 +135,14 @@ } .untagged { color: var(--muted); font-size: 11px; } .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 { display: flex; gap: 14px; @@ -201,6 +211,16 @@ + @@ -229,6 +249,10 @@ const wrap = document.getElementById('wrap'); const login = document.getElementById('login'); const tip = document.getElementById('tip'); + const cfMetricSel = document.getElementById('cfMetric'); + const cfValueInput = document.getElementById('cfValue'); + // 条件格式只在本地重渲染,不重新请求 —— 指标已经随格子一起返回了。 + let lastData = null; function setStatus(text, isError) { statusEl.textContent = text; @@ -244,6 +268,32 @@ 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) { // 用 DOM 拼,不用 innerHTML —— 昵称是平台来的文本,不能当 HTML 解释。 tip.textContent = ''; @@ -330,12 +380,14 @@ td._cell = cell; td.dataset.day = day; td.dataset.creator = creatorName; + if (cfHit(cell)) td.classList.add('hit'); td.addEventListener('mouseenter', showTip); td.addEventListener('mouseleave', hideTip); return td; } function render(data) { + lastData = data; wrap.innerHTML = ''; if (!data.dates.length) { setStatus('这个范围内没有作品'); @@ -444,6 +496,13 @@ if (wanted && Array.from(taskSel.options).some((o) => o.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(); } @@ -454,6 +513,13 @@ }); taskSel.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); init(); diff --git a/tests/test_monitor_matrix.py b/tests/test_monitor_matrix.py index 6e230c0..0c1e42b 100644 --- a/tests/test_monitor_matrix.py +++ b/tests/test_monitor_matrix.py @@ -21,6 +21,7 @@ from api.monitor import db as monitor_db from api.monitor import service from api.monitor.models import ( MODE_CREATOR, + MonitorCreatorStat, MonitorNote, MonitorNoteMetric, MonitorNoteTag, @@ -150,7 +151,9 @@ async def test_same_day_notes_collapse_with_tags_union(db): async with monitor_db.get_session() as session: 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"] 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: data = await service.daily_tag_matrix(session, "dy", days=7) - assert data["dates"] == [_day(now - 1000)] - assert data["cells"][_day(now - 1000)]["hash-a"]["count"] == 1 + assert len(data["dates"]) == 7 + 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 @@ -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 async def test_cell_sums_the_latest_metric_of_each_note(db): task_id = await _task() @@ -292,7 +331,7 @@ async def test_endpoint_returns_the_long_shape(client): assert response.status_code == 200 body = response.json() - assert body["dates"] == [_day(now)] + assert _day(now) in body["dates"] assert body["creators"][0]["name"] == "博主A" cell = body["cells"][_day(now)]["hash-a"] assert cell["count"] == 1