fix(kpi): 阈值红黄绿读写/填写规则修复 — 统一解析器+红灯优先+建议可解析+前端校验+存量修正 (project-20260911-threshold-fix)
① 新建 app/utils/threshold_parser.py 统一解析/判定(单一事实源):
- 支持负数(>=-100000)、闭区间 A~B、多条件 C1|C2;空串=未设置
- 判定顺序 red→green→yellow:红灯优先(消除宽黄灯遮蔽红灯),
green 先于 yellow(green 是主条件,yellow 是更宽兜底带)
② kpis.py / alert_generator.py 双实现收敛到统一解析器(消除重复维护)
③ thresholds.py suggest 输出可解析表达式(原黄色/适中型生成 `52.33~107.67`、`偏离55%` 等
区间/文字 → 用户点"自动建议"填入后静默失效;另修复大数目标生成 1.6e+06 科学计数法)
④ KPIDetail.vue 三个阈值输入加 placeholder/tooltip/帮助文案 + 保存前格式校验(非法即拒)
⑤ 存量 4 个不可解析表达式修正(id=46 C_REBATE_RATE / id=327 BH_SALES_10),
改前 mysqldump 备份 backend/scripts/backups/kpi_definitions.bak-20260911.sql +
threshold_rows_before_20260911.json(可回滚);不可解析 5→0
⑥ 单测 97 条 + 红黄绿判定回归 367 判定点(旧→新差异 14 条,含差异说明)
This commit is contained in:
@@ -6,7 +6,6 @@
|
||||
|
||||
import sys
|
||||
import os
|
||||
import re
|
||||
import json
|
||||
import logging
|
||||
from datetime import datetime, timedelta
|
||||
@@ -15,22 +14,15 @@ 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, ActionPlan
|
||||
from app.utils.threshold_parser import eval_threshold, LEVEL_PRIORITY
|
||||
|
||||
logger = logging.getLogger("cma.alert_gen")
|
||||
|
||||
|
||||
def _parse_threshold(expr: str) -> tuple:
|
||||
"""解析阈值表达式,返回 (operator, value)
|
||||
示例:
|
||||
>=32000000 -> ('>=', 32000000)
|
||||
<20 -> ('<', 20)
|
||||
<=55 -> ('<=', 55)
|
||||
>60 -> ('>', 60)
|
||||
"""
|
||||
m = re.match(r"(>=|<=|>|<|=|!=)\s*([\d.]+)", str(expr).strip())
|
||||
if m:
|
||||
return m.group(1), float(m.group(2))
|
||||
return None, None
|
||||
"""[兼容保留] 统一委托 app.utils.threshold_parser.parse_threshold"""
|
||||
from app.utils.threshold_parser import parse_threshold as _p
|
||||
return _p(expr)
|
||||
|
||||
|
||||
def cleanup_green_alerts(db_session) -> int:
|
||||
@@ -52,33 +44,16 @@ def cleanup_green_alerts(db_session) -> int:
|
||||
|
||||
|
||||
def _check_threshold(actual: float, threshold_expr: str, level: str) -> tuple:
|
||||
"""检查实际值是否触发阈值,返回 (触发, 消息)"""
|
||||
"""检查实际值是否触发阈值,返回 (触发, 消息)(统一走 app.utils.threshold_parser)"""
|
||||
if not threshold_expr or actual is None:
|
||||
return False, ""
|
||||
|
||||
op, val = _parse_threshold(threshold_expr)
|
||||
if op is None:
|
||||
if not eval_threshold(actual, threshold_expr):
|
||||
return False, ""
|
||||
|
||||
triggered = False
|
||||
if op == ">=" and actual >= val:
|
||||
triggered = True
|
||||
elif op == "<=" and actual <= val:
|
||||
triggered = True
|
||||
elif op == ">" and actual > val:
|
||||
triggered = True
|
||||
elif op == "<" and actual < val:
|
||||
triggered = True
|
||||
elif op == "=" and actual == val:
|
||||
triggered = True
|
||||
|
||||
if triggered:
|
||||
level_names = {"green": "正常", "yellow": "预警", "red": "紧急"}
|
||||
msg = (f"KPI当前值 {actual:.2f},触发{level_names.get(level, level)}阈值 "
|
||||
f"({threshold_expr})")
|
||||
return True, msg
|
||||
|
||||
return False, ""
|
||||
msg = (f"KPI当前值 {actual:.2f},触发{ {'green': '正常', 'yellow': '预警', 'red': '紧急'}.get(level, level) }阈值 "
|
||||
f"({threshold_expr})")
|
||||
return True, msg
|
||||
|
||||
|
||||
def run_alert_check(db_session, period: str = None) -> int:
|
||||
@@ -112,9 +87,12 @@ def run_alert_check(db_session, period: str = None) -> int:
|
||||
|
||||
actual = latest.actual_value
|
||||
|
||||
# 从绿到红检查(绿灯最高优先级——满足即止)
|
||||
# 判定顺序:红灯优先 → 绿灯 → 黄灯(最严重者优先,消除宽黄灯遮蔽红灯)
|
||||
# 2026-09-11 修复「黄灯遮蔽红灯」:原顺序 绿→黄→红命中即止,宽黄灯(如 Y='>76')
|
||||
# 会让红灯(如 R='>91')永远不可达(id=6 实测值 95 被判黄);
|
||||
# green 先于 yellow:green 是主条件,yellow 是更宽的兜底带(id=1 G='>=800' Y='>=700')。
|
||||
# Bug1修复: green(正常)不生成pending预警,只对yellow/red落库
|
||||
for level in ["green", "yellow", "red"]:
|
||||
for level in LEVEL_PRIORITY:
|
||||
expr = thr[level]
|
||||
if not expr:
|
||||
continue
|
||||
@@ -173,7 +151,8 @@ def run_alert_check(db_session, period: str = None) -> int:
|
||||
logger.info(f" ↳ 自动创建行动计划 #{plan.id}: {plan_title}")
|
||||
break # 只取最高级别
|
||||
elif level == "red" and not triggered:
|
||||
# 红没触发,如果已有红色预警但当前不满足,自动降级或关闭
|
||||
# 红没触发(判定顺序中 red 最先)→ 若该期间该KPI已有 pending/processing 红灯,
|
||||
# 说明当前值已不再触发红色阈值,自动解除(保留原有自动降级行为)
|
||||
existing_red = db_session.query(KPIAlert).filter(
|
||||
KPIAlert.kpi_id == kpi.id,
|
||||
KPIAlert.kpi_value_id == latest.id,
|
||||
|
||||
Reference in New Issue
Block a user