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
+59
View File
@@ -0,0 +1,59 @@
#!/usr/bin/env python3
"""行动计划执行周报 — 每周一08:00推送
统计本周通过/失败/升级/待处理计划数,推送任总
"""
import sys, os
from datetime import datetime, timedelta
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from app.database import get_db
from app.models import ActionPlan
from app.utils.notifier import send_wecom_message
def generate_weekly_report():
db = next(get_db())
try:
week_ago = datetime.now() - timedelta(days=7)
# 本周所有计划(最近7天创建的)
plans = db.query(ActionPlan).filter(ActionPlan.created_at >= week_ago).all()
if not plans:
plans = db.query(ActionPlan).order_by(ActionPlan.created_at.desc()).limit(10).all()
total = len(plans)
passed = sum(1 for p in plans if p.verify_status == "passed")
failed = sum(1 for p in plans if p.verify_status == "failed")
escalated = sum(1 for p in plans if p.verify_status == "escalated")
pending = sum(1 for p in plans if p.verify_status in ("pending", "retrying"))
done = sum(1 for p in plans if p.status == "done")
msg = (
f"📋 行动计划执行周报({datetime.now().strftime('%Y-%m-%d')}\n"
f"统计范围:近7天计划 {total}\n"
f"✅ 验证通过: {passed}\n"
f"❌ 验证失败: {failed}\n"
f"🚨 升级人工: {escalated}\n"
f"⏳ 待验证: {pending}\n"
f"🏁 已完成: {done}\n"
)
# 列出待验证/升级项
urgent = [p for p in plans if p.verify_status in ("escalated", "retrying")]
if urgent:
msg += "\n⚠️ 需关注:\n"
for p in urgent[:5]:
msg += f" #{p.id} {p.title} ({p.verify_status})\n"
try:
send_wecom_message(msg, title="行动计划周报")
except Exception:
pass
print(msg)
return {"total": total, "passed": passed, "failed": failed, "escalated": escalated}
finally:
db.close()
if __name__ == "__main__":
generate_weekly_report()
+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__":
+123
View File
@@ -0,0 +1,123 @@
#!/usr/bin/env python3
"""Auto-Verify 定时验证任务 — 扫描到期pending计划,自动验证执行效果
运行: 30 9 * * * cd /root/cma-management/backend && python3 scripts/auto_verify_cron.py
"""
import sys, os
from datetime import datetime, timedelta
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from app.database import get_db
from app.models import ActionPlan, KPIDefinition, KPIValue, Objective
from app.utils.notifier import send_wecom_message
from app.api.verify import CONDITION_FUNCS
def evaluate_condition(condition, actual, target):
"""按条件判断验证结果(兼容旧表达式)"""
if isinstance(condition, str) and ('<' in condition or '>' in condition):
try:
return eval(condition.replace('value', str(actual)), {"__builtins__": {}})
except Exception:
return False
func = CONDITION_FUNCS.get(condition)
if not func:
return False
return func(actual, target)
def run_auto_verify():
db = next(get_db())
try:
now = datetime.now()
# 扫描到期pending计划(due_date <= now+1天)
plans = db.query(ActionPlan).filter(
ActionPlan.verify_status == "pending",
ActionPlan.status.in_(["pending", "in_progress"]),
ActionPlan.due_date <= now + timedelta(days=1),
).all()
verified_count = 0
escalated_count = 0
messages = []
for plan in plans:
rule = plan.auto_verify_rule
if not rule or not isinstance(rule, dict):
continue
kpi_code = rule.get("kpi_code")
if not kpi_code:
continue
# 查最新KPI值
kpi = db.query(KPIDefinition).filter(
KPIDefinition.kpi_code == kpi_code
).order_by(KPIDefinition.id.desc()).first()
if not kpi:
continue
latest = db.query(KPIValue).filter(
KPIValue.kpi_id == kpi.id
).order_by(KPIValue.calculated_at.desc()).first()
if not latest or latest.actual_value is None:
continue
actual = latest.actual_value
condition = rule.get("condition", "LESS_THAN")
target = rule.get("target_value")
retry_max = rule.get("retry_max", 3)
passed = evaluate_condition(condition, actual, target)
plan.kpi_current_before = rule.get("baseline_value")
plan.kpi_current_after = actual
if passed:
plan.verify_status = "passed"
plan.verified_at = now
plan.status = "done"
# 阶段3: OKR progress更新
update_okr_progress(db, plan, +15)
messages.append(f"✅ 行动计划#{plan.id}验证通过: {plan.title} ({kpi_code}: {rule.get('baseline_value')}{actual})")
verified_count += 1
else:
plan.verify_attempts = (plan.verify_attempts or 0) + 1
if plan.verify_attempts >= retry_max:
plan.verify_status = "escalated"
messages.append(f"🚨 行动计划#{plan.id}连续{retry_max}次验证失败,升级人工: {plan.title}")
escalated_count += 1
else:
plan.verify_status = "retrying"
messages.append(f"⚠️ 行动计划#{plan.id}验证失败(第{plan.verify_attempts}次),待重试: {plan.title}")
db.commit()
# 汇总通知
if messages:
summary = "\n".join(messages)
try:
send_wecom_message(f"📋 行动计划自动验证日报\n{summary}", title="Auto-Verify")
except Exception:
pass
print(f"[{now.strftime('%Y-%m-%d %H:%M')}] 验证通过{verified_count}个,升级{escalated_count}个,共处理{len(plans)}个到期计划")
return {"verified": verified_count, "escalated": escalated_count, "total": len(plans)}
finally:
db.close()
def update_okr_progress(db, plan, delta):
"""验证通过→更新所属OKR progress"""
okr_id = getattr(plan, "okr_id", None) or getattr(plan, "objective_id", None)
if not okr_id:
return
obj = db.query(Objective).filter(Objective.id == okr_id).first()
if obj:
current = obj.progress or 0
obj.progress = min(current + delta, 100)
db.add(obj)
if __name__ == "__main__":
run_auto_verify()
+7 -2
View File
@@ -273,10 +273,15 @@ def fetch_fallback(kpi: KPIDefinition, parsed: dict, db_session, period: str) ->
KPIValue.source_type.in_(["erp", "manual"]),
).order_by(KPIValue.period.desc()).first()
if existing and existing.actual_value is not None:
logger.info(f" [{kpi_code}] Fallback: 沿用最近期 {existing.period}={existing.actual_value}")
if existing and existing.actual_value is not None and existing.data_status == "verified":
logger.info(f" [{kpi_code}] Fallback: 沿用最近期 verified数据 {existing.period}={existing.actual_value}")
return existing.actual_value
# Bug3修复: 不沿用estimated旧值(可能失真,如4800万收入),避免污染当月数据
if existing and existing.actual_value is not None and existing.data_status != "verified":
logger.info(f" [{kpi_code}] Fallback: 最近期 {existing.period} 为estimated({existing.actual_value}),不沿用,返回None")
return None
# 特殊KPI的默认值
DEFAULTS = {
"SALES_TOTAL": 800000,