diff --git a/app/services/compare_alert_format.py b/app/services/compare_alert_format.py index 661c581..49ed3cc 100644 --- a/app/services/compare_alert_format.py +++ b/app/services/compare_alert_format.py @@ -128,6 +128,18 @@ def _cost_cell(total_ms: int | None, step_count: int | None) -> str: return " / ".join(parts) or "-" +def _build_card(title_text: str, elements: list[dict]) -> dict: + """组装 schema 2.0 红色 header 卡片;三条路径只需决定 elements。""" + return { + "schema": "2.0", + "header": { + "title": {"tag": "plain_text", "content": title_text}, + "template": "red", + }, + "body": {"elements": elements}, + } + + def _build_table_rows( hits: list[AlertHit], *, @@ -137,7 +149,9 @@ def _build_table_rows( """按 _TYPE_ORDER 顺序展开,每类型最多 max_detail_per_type 条。""" grouped: dict[str, list[AlertHit]] = {t: [] for t in _TYPE_ORDER} for h in hits: - grouped.setdefault(h.alert_type, []).append(h) + if h.alert_type in grouped: + grouped[h.alert_type].append(h) + # 非 _TYPE_ORDER 类型静默跳过(与既有行为一致) rows = [] for t in _TYPE_ORDER: @@ -193,16 +207,7 @@ def format_alert_card( # ---------- 空 hits ---------- if total == 0: md_content = f"数据范围:近 {interval_min} 分钟\n本期无异常" - return { - "schema": "2.0", - "header": { - "title": {"tag": "plain_text", "content": title_text}, - "template": "red", - }, - "body": { - "elements": [{"tag": "markdown", "content": md_content}], - }, - } + return _build_card(title_text, [{"tag": "markdown", "content": md_content}]) # ---------- 摘要 ---------- grouped_count: dict[str, int] = {} @@ -221,16 +226,7 @@ def format_alert_card( # ---------- 截断:超 max_total 只出摘要 ---------- if total > max_total: md_content += f"\n超 {max_total} 条仅列计数,明细见分析库 comparison_record" - return { - "schema": "2.0", - "header": { - "title": {"tag": "plain_text", "content": title_text}, - "template": "red", - }, - "body": { - "elements": [{"tag": "markdown", "content": md_content}], - }, - } + return _build_card(title_text, [{"tag": "markdown", "content": md_content}]) # ---------- 常规:摘要 + table ---------- rows = _build_table_rows(hits, phone_map=phone_map, max_detail_per_type=max_detail_per_type) @@ -242,16 +238,4 @@ def format_alert_card( "columns": _TABLE_COLUMNS, "rows": rows, } - return { - "schema": "2.0", - "header": { - "title": {"tag": "plain_text", "content": title_text}, - "template": "red", - }, - "body": { - "elements": [ - {"tag": "markdown", "content": md_content}, - table_element, - ], - }, - } + return _build_card(title_text, [{"tag": "markdown", "content": md_content}, table_element])