diff --git a/api/monitor/service.py b/api/monitor/service.py index ae852f0..e172812 100644 --- a/api/monitor/service.py +++ b/api/monitor/service.py @@ -1532,10 +1532,11 @@ async def daily_tag_matrix( # 标签一次取完,按 note_id 归组;顺序跟词表里的 sort_order 一致。 tags_by_note: Dict[str, List[str]] = {} + tag_order: Dict[str, int] = {} if note_ids: tag_rows = ( await session.execute( - select(MonitorNoteTag.note_id, MonitorTag.name) + select(MonitorNoteTag.note_id, MonitorTag.name, MonitorTag.sort_order) .join(MonitorTag, MonitorTag.id == MonitorNoteTag.tag_id) .where( MonitorNoteTag.platform == platform, @@ -1544,8 +1545,9 @@ async def daily_tag_matrix( .order_by(MonitorTag.sort_order, MonitorTag.id) ) ).all() - for note_id, name in tag_rows: + for note_id, name, sort_order in tag_rows: tags_by_note.setdefault(note_id, []).append(name) + tag_order.setdefault(name, sort_order) # 指标:每篇作品取**最近一轮**(run_id 最大)。没有指标行的作品不参与求和 —— # 未知和 0 是两回事,格子的提示里会显示成「—」而不是「0」。 @@ -1642,6 +1644,12 @@ async def daily_tag_matrix( if value is not None: bucket[key] = (bucket[key] or 0) + value + # 一个格子可能合并了多天里的多条作品、多个标签。统一按**词表顺序**排 —— + # 否则同样的数据,换个遍历顺序就换了标签顺序,看起来像数据变了。 + for day_cells in cells.values(): + for bucket in day_cells.values(): + bucket["tags"].sort(key=lambda name: tag_order.get(name, 10**6)) + creators = [{"hash": hash_, "name": name} for hash_, name in known.items()] creators.sort(key=lambda item: item["name"]) diff --git a/tests/test_monitor_matrix.py b/tests/test_monitor_matrix.py index 0c1e42b..34154d2 100644 --- a/tests/test_monitor_matrix.py +++ b/tests/test_monitor_matrix.py @@ -162,6 +162,31 @@ async def test_same_day_notes_collapse_with_tags_union(db): assert cell["tags"] == ["大字报", "养号"] +@pytest.mark.asyncio +async def test_two_notes_with_different_tags_merge_into_one_cell(db): + """同一天两条不同标签:合成一格,计数相加,标签取并集。 + + 注意并集**按词表顺序**排,不是按作品先后 —— 否则同样的数据换个遍历顺序就会 + 看起来不一样。代价是「哪个标签属于哪条视频」这个信息在这一格里没有了。 + """ + task_id = await _task() + now = get_current_timestamp() + await _note(task_id, "older", "博主A", now - 2000) + await _note(task_id, "newer", "博主A", now - 1000) + + dazibao = await _tag("大字报", 1) + yanghao = await _tag("养号", 2) + await _attach("dy", "older", dazibao) + await _attach("dy", "newer", yanghao) + + async with monitor_db.get_session() as session: + data = await service.daily_tag_matrix(session, "dy", days=7) + + cell = data["cells"][_day(now)]["hash-a"] + assert cell["count"] == 2 + assert cell["tags"] == ["大字报", "养号"] + + @pytest.mark.asyncio async def test_dates_newest_first_and_creators_sorted(db): task_id = await _task()