feat: Auto-Verify闭环 — verify API+定时验证+OKR联动+周报

This commit is contained in:
Hermes CI Fix
2026-08-10 23:15:19 +08:00
parent 7fed66d58c
commit e1ea5cd14d
9 changed files with 601 additions and 6 deletions
+54 -3
View File
@@ -9,12 +9,12 @@ import os
import re
import json
import logging
from datetime import datetime
from datetime import datetime, timedelta
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from app.database import get_session_local
from app.models import KPIDefinition, KPIValue, KPIAlert
from app.models import KPIDefinition, KPIValue, KPIAlert, ActionPlan
logger = logging.getLogger("cma.alert_gen")
@@ -33,6 +33,24 @@ def _parse_threshold(expr: str) -> tuple:
return None, None
def cleanup_green_alerts(db_session) -> int:
"""Bug1修复: 清理历史遗留的green级别pending预警(正常值不应出现在待办)"""
greens = db_session.query(KPIAlert).filter(
KPIAlert.alert_level == "green",
KPIAlert.status.in_(["pending", "processing"]),
).all()
count = 0
for g in greens:
g.status = "resolved"
g.resolution = "自动清理: green(正常)级别不生成待处理预警"
g.resolved_at = datetime.now()
count += 1
if count:
db_session.commit()
logger.info(f" 清理历史green预警 {count} 条 → resolved")
return count
def _check_threshold(actual: float, threshold_expr: str, level: str) -> tuple:
"""检查实际值是否触发阈值,返回 (触发, 消息)"""
if not threshold_expr or actual is None:
@@ -95,12 +113,16 @@ def run_alert_check(db_session, period: str = None) -> int:
actual = latest.actual_value
# 从绿到红检查(绿灯最高优先级——满足即止)
# Bug1修复: green(正常)不生成pending预警,只对yellow/red落库
for level in ["green", "yellow", "red"]:
expr = thr[level]
if not expr:
continue
triggered, msg = _check_threshold(actual, expr, level)
if triggered:
if level == "green":
# 正常状态:不生成待处理预警(如有旧的red/yellow预警自动解除)
break
# 检查是否已有该期间该KPI同级别的预警
existing = db_session.query(KPIAlert).filter(
KPIAlert.kpi_id == kpi.id,
@@ -121,8 +143,34 @@ def run_alert_check(db_session, period: str = None) -> int:
status="pending",
)
db_session.add(alert)
db_session.flush() # 获取alert.id
new_count += 1
logger.info(f" 新增预警 [{level}] {kpi.kpi_name}: {msg}")
# Bug2修复: red/yellow预警自动创建行动计划(预警→行动闭环)
if level in ("red", "yellow"):
plan_title = f"改善: {kpi.kpi_name} {msg}"
if kpi.kpi_name and "现金" in kpi.kpi_name or kpi.kpi_code == "F_OP_CFLOW":
plan_title = f"资金缺口应对: {msg} —— 催收应收+安排融资"
elif kpi.kpi_code == "F_AR_DAYS":
plan_title = f"应收催收: {msg} —— 逾期客户专项跟进"
elif kpi.kpi_code == "C_REBATE_RATE":
plan_title = f"渠补谈判: {msg} —— 下游渠道返利谈判"
elif kpi.kpi_code == "F_COST_RATIO":
plan_title = f"费用压缩: {msg} —— 管理费削减计划"
plan = ActionPlan(
alert_id=alert.id,
kpi_id=kpi.id,
title=plan_title,
assignee="财务部",
priority="high" if level == "red" else "medium",
due_date=datetime.now().date() + timedelta(days=3 if level == "red" else 7),
created_by="alert_generator",
)
db_session.add(plan)
db_session.flush()
alert.action_plan_linked_id = plan.id
logger.info(f" ↳ 自动创建行动计划 #{plan.id}: {plan_title}")
break # 只取最高级别
elif level == "red" and not triggered:
# 红没触发,如果已有红色预警但当前不满足,自动降级或关闭
@@ -146,6 +194,9 @@ def generate_and_push(db_session) -> dict:
"""生成预警并推送,返回统计"""
period = datetime.now().strftime("%Y-%m")
# 0. Bug1修复: 先清理历史green预警
cleaned = cleanup_green_alerts(db_session)
# 1. 生成预警
logger.info(f"开始预警检查 ({period})...")
new_count = run_alert_check(db_session, period)
@@ -161,7 +212,7 @@ def generate_and_push(db_session) -> dict:
except Exception as e:
logger.error(f"推送失败: {e}")
return {"period": period, "new_alerts": new_count, "pushed": pushed}
return {"period": period, "new_alerts": new_count, "pushed": pushed, "cleaned_green": cleaned}
if __name__ == "__main__":