399 lines
18 KiB
Python
399 lines
18 KiB
Python
"""阈值规则 -- 「这一格到没到线」由后端判,界面上的红字只是把同一句话再说一遍。
|
||
|
||
为什么不直接把条件写进条件分支:条件引擎的右值只能写字面量(``dicts.compare``
|
||
左边取 ``data[field]``、右边取配置里的常量),比不了两个字段;而阈值最常见的形状
|
||
恰好是「本次申请 > 可用余额」这种两个字段比。所以这里单开一条小链路:比较运算仍
|
||
复用 ``dicts.compare``,只把「右边也可以是一个字段」这一件事补上,不重写第二套 ops。
|
||
|
||
判定结果写进字段上指定的那一格(``flag``):条件分支、``requiredWhen``、界面上的
|
||
红字读的都是同一个结果。**页面上的即时判断只用于提示,提交时后端一定再判一次**,
|
||
否则改一下前端就能绕过阈值——这与「带出值以服务端为准」是同一个分寸。
|
||
|
||
界面配置的形状(挂在字段上)::
|
||
|
||
{ "key": "applyAmount", "type": "money",
|
||
"threshold": {
|
||
"op": "gt", // 本格的值 与 右边比:gt/ge/lt/le/eq/ne...
|
||
"right": "5000", // 常量阈值
|
||
"rightField": "budgetLeft", // 或者取另一个字段,配了就以它为准
|
||
"mode": "warn", // warn 提示 / block 挡提交 / mark 只写标记
|
||
"flag": "overBudget", // 命中写进哪一格,供条件分支与必填联动读
|
||
"message": "本次 {left} 元,超过可用 {right} 元"
|
||
} }
|
||
|
||
明细表多三个键,比的就不再是"填没填过行"这一件事了::
|
||
|
||
{ "key": "offsetItems", "type": "table",
|
||
"threshold": {
|
||
"column": "offsetAmount", // 比哪一列;不写就只问整张表填没填(老配置)
|
||
"scope": "row", // row 任一行到线就算 / sum 那一列加起来再比
|
||
"rightColumn": "loanRemain", // 右边取本表另一列(逐行比才有意义)
|
||
"op": "gt", "mode": "block", "message": "第 {row} 行多冲了 {gap} 元"
|
||
} }
|
||
|
||
方案出处:``docs/integration-master-plan.md`` §4.7 页面三。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
from typing import Any, Iterable, NamedTuple
|
||
|
||
from sqlalchemy.orm import Session
|
||
|
||
from . import dicts, quota
|
||
from .quota import FORM_REF, to_cents
|
||
|
||
#: 字段上挂阈值配置的属性名
|
||
FIELD_PROP = "threshold"
|
||
#: 命中以后的三档下场
|
||
MODE_WARN = "warn"
|
||
MODE_BLOCK = "block"
|
||
MODE_MARK = "mark"
|
||
MODES = (MODE_WARN, MODE_BLOCK, MODE_MARK)
|
||
#: 能用的比较符:就用条件联动那一批,自己另列一份迟早对不上。
|
||
#: 去掉 changed——它比的是"和打开单据时比有没有改过",阈值这一路没有那个基准。
|
||
OPS = tuple(sorted(set(dicts.CONDITION_OPS) - {"changed"}))
|
||
#: 这几档比较的是数,命中时能把"超了多少/差多少"写进标记格
|
||
NUMERIC_OPS = ("gt", "ge", "lt", "le")
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 哪一格比得了什么:口径与前端 ``utils/fieldCapabilities.ts`` 同一份
|
||
# ---------------------------------------------------------------------------
|
||
|
||
#: 全量比较符(``OPS`` 去掉 changed 那一份)——装得下一个数或一句话的格子都能用
|
||
FULL_OPS = OPS
|
||
#: 只有是与不是
|
||
FLAG_OPS = ("eq", "ne", "empty", "notEmpty")
|
||
#: 装的是一串值或一叠行:只问得出"填了没有",比大小、比包含都是糊的
|
||
BAG_OPS = ("empty", "notEmpty")
|
||
#: 装得下一个数
|
||
NUMBER_TYPES = ("money", "number", "formula", "rate")
|
||
#: 比的是先后,能用的比较符与数值同档
|
||
DATE_TYPES = ("date", "datetime", "time")
|
||
#: 装得下一句文本或一个选项值
|
||
TEXT_TYPES = ("text", "textarea", "mobile", "email", "idcard", "url", "select", "radio", "auto", "hidden")
|
||
#: 值是数组/对象的类型:多选、部门、人员、附件、日期区间、明细表……
|
||
BAG_TYPES = ("daterange", "checkbox", "dept", "cascader", "user", "relation", "address",
|
||
"attachment", "image", "signature", "sign", "file", "table")
|
||
FLAG_TYPES = ("switch",)
|
||
|
||
#: 认不出的类型(以后新加的)一律不设限:宁可少说一句,也别把没见过的写法判成毛病。
|
||
OPS_BY_TYPE: dict[str, tuple[str, ...]] = {
|
||
**{kind: FULL_OPS for kind in (*NUMBER_TYPES, *DATE_TYPES, *TEXT_TYPES)},
|
||
**{kind: FLAG_OPS for kind in FLAG_TYPES},
|
||
**{kind: BAG_OPS for kind in BAG_TYPES},
|
||
}
|
||
|
||
|
||
def ops_for(field_type: str) -> tuple[str, ...]:
|
||
"""这一格的类型能用哪些比较符;不认识的回空 tuple 表示"不评判"。"""
|
||
return OPS_BY_TYPE.get(str(field_type or "").strip(), ())
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 明细表怎么比:整张表 / 某一列的任一行 / 某一列加起来
|
||
# ---------------------------------------------------------------------------
|
||
|
||
#: 明细表的两种比法:任一行到线就算,还是把那一列加起来再比
|
||
SCOPE_ROW = "row"
|
||
SCOPE_SUM = "sum"
|
||
SCOPES = (SCOPE_ROW, SCOPE_SUM)
|
||
|
||
|
||
def scope_of(cfg: dict | None) -> str:
|
||
"""明细表这一条按行比还是按合计比;没写就是逐行。"""
|
||
scope = str((cfg or {}).get("scope") or "").strip()
|
||
return scope if scope in SCOPES else SCOPE_ROW
|
||
|
||
|
||
def column_of(cfg: dict | None) -> str:
|
||
"""明细表要比的那一列。空串 = 比整张表(只问得出填没填,与老配置一致)。"""
|
||
return str((cfg or {}).get("column") or "").strip()
|
||
|
||
|
||
def right_column_of(cfg: dict | None) -> str:
|
||
"""右边要比的是**同一张明细表**的另一列("本次冲销 > 还未冲"那种行内比)。"""
|
||
text = str((cfg or {}).get("rightColumn") or "").strip()
|
||
# 界面上那一下点选存的是 `col:xxx`,手写配置存的是纯列名:两种都认,别为这点写法差报错
|
||
return text[4:] if text.startswith("col:") else text
|
||
|
||
|
||
def column_type(field: dict, column: str) -> str:
|
||
"""明细表某一列的类型。列不存在回空串,由 ``problems`` 去点名。"""
|
||
if not column:
|
||
return ""
|
||
for item in field.get("columns") or []:
|
||
if isinstance(item, dict) and str(item.get("key") or "").strip() == column:
|
||
return str(item.get("type") or "").strip()
|
||
return ""
|
||
|
||
|
||
def ops_for_field(field: dict, cfg: dict | None = None) -> tuple[str, ...]:
|
||
"""这一条阈值能用哪些比较符。
|
||
|
||
明细表看的是**要比的那一列**的类型:列是金额就能比大小,只有整张表那种
|
||
"比填没填"的比法才退回 ``empty`` / ``notEmpty``。
|
||
"""
|
||
if str(field.get("type") or "") != "table":
|
||
return ops_for(str(field.get("type") or ""))
|
||
column = column_of(cfg)
|
||
if not column:
|
||
return ops_for("table")
|
||
# 点了列却找不到那一列:列的类型说不清,比较符也就无从评判,交给 problems 点名列的事
|
||
return ops_for(column_type(field, column)) if column_type(field, column) else ()
|
||
|
||
|
||
def lefts(field: dict, cfg: dict, data: dict) -> list[tuple[str, Any, dict | None]]:
|
||
"""摆到比较号左边的东西,展开成 ``(第几行, 值, 整行)``。
|
||
|
||
- 普通字段:就一个值,与以前一模一样
|
||
- 明细表没点名列:整个数组,只问得出填没填
|
||
- 明细表点了列、逐行比:每行一个,命中任一行算命中
|
||
- 明细表点了列、比合计:那一列加总成一个数
|
||
"""
|
||
key = str(field.get("key") or "")
|
||
value = (data or {}).get(key)
|
||
column = column_of(cfg)
|
||
if str(field.get("type") or "") != "table" or not column:
|
||
return [("", value, None)]
|
||
rows = [row for row in (value or []) if isinstance(row, dict)]
|
||
if scope_of(cfg) == SCOPE_SUM:
|
||
cents = [to_cents(row.get(column)) for row in rows]
|
||
picked = [item for item in cents if item is not None]
|
||
# 一行数都没有就当没填:合计 0 参与比较会把"没填"判成"填了个 0"
|
||
return [("", round(sum(picked) / 100, 2) if picked else None, None)]
|
||
return [(f"第 {index} 行", row.get(column), row) for index, row in enumerate(rows, start=1)]
|
||
|
||
|
||
def threshold_fields(fields: Iterable[dict] | None) -> list[tuple[dict, dict]]:
|
||
"""挑出配了 ``threshold`` 的字段,返回 (字段定义, 阈值配置)。"""
|
||
out: list[tuple[dict, dict]] = []
|
||
for item in fields or []:
|
||
if not isinstance(item, dict):
|
||
continue
|
||
# 明细表也进来:它只能问"填过行没有"(``ops_for`` 只给 empty/notEmpty),
|
||
# 比大小那一档本来就轮不到它,不必整类踢出去
|
||
cfg = item.get(FIELD_PROP)
|
||
if isinstance(cfg, dict) and str(cfg.get("op") or "").strip():
|
||
out.append((item, cfg))
|
||
return out
|
||
|
||
|
||
def right_key(cfg: dict) -> str:
|
||
"""阈值右边那个字段名。
|
||
|
||
设计上 ``rightField`` 就写纯字段名(界面下拉选出来的就是它),但设计器之外的人
|
||
手写配置时习惯照 ``{form.x}`` 的写法来,这里一并认下,别为这点写法差报错。
|
||
"""
|
||
text = str(cfg.get("rightField") or "").strip()
|
||
if not text:
|
||
return ""
|
||
match = FORM_REF.match(text)
|
||
if match:
|
||
return str(match.group(1) or match.group(2) or "").strip()
|
||
return text
|
||
|
||
|
||
def resolve(db: Session, expr: object, data: dict, work=None) -> str:
|
||
"""阈值右边的值:``{form.x}`` 取字段、``{auto:...}`` 取系统值,其余按字面量。"""
|
||
return quota.resolve_text(db, expr, data or {}, work=work)
|
||
|
||
|
||
def gap_of(op: str, left: Any, right: Any) -> float:
|
||
"""命中程度:数值比较给差额(超了多少 / 还差多少),其余给 1。
|
||
|
||
写进标记格的是这个数而不是真假,条件分支就能用现成的「大于 0」判命中,
|
||
不必等条件引擎支持比两个字段——与额度把超支额落进 ``quotaOver`` 是同一招。
|
||
"""
|
||
if op not in NUMERIC_OPS:
|
||
return 1.0
|
||
mine, other = to_cents(left), to_cents(right)
|
||
if mine is None or other is None:
|
||
return 1.0
|
||
delta = mine - other if op in ("gt", "ge") else other - mine
|
||
# 命中才给差额;没命中给 0,免得标记格里留着上一个状态的数被条件分支读歪
|
||
return round(max(0, delta) / 100, 2)
|
||
|
||
|
||
class Hit(NamedTuple):
|
||
"""一条阈值的判定结果。
|
||
|
||
明细表逐行比时可能有几行都到线,留的是**超得最多**的那一行:``left`` / ``right`` /
|
||
``where`` 说的是这一行的数,文案与标记格都读它。普通字段只有 ``(where="")`` 一项。
|
||
"""
|
||
|
||
hit: bool = False
|
||
gap: float = 0.0
|
||
right: Any = None
|
||
left: Any = None
|
||
where: str = ""
|
||
|
||
|
||
def evaluate(db: Session, field: dict, cfg: dict, data: dict, work=None) -> Hit:
|
||
"""判一次,回 :class:`Hit`。
|
||
|
||
比较符不认识、或者要比的值是空值,都算**没命中**:没填的单子不该被阈值挡在门外,
|
||
必填该由必填去管,阈值只管"填了以后的数到没到线"。明细表逐行比时"有一行没填"
|
||
不该连累别的行,所以那一行直接跳过,而不是整条规则不判。
|
||
"""
|
||
op = str(cfg.get("op") or "").strip()
|
||
if op not in OPS:
|
||
return Hit()
|
||
empties = op in ("empty", "notEmpty")
|
||
right_ref = right_key(cfg)
|
||
right_column = right_column_of(cfg)
|
||
best = Hit()
|
||
for where, left, row in lefts(field, cfg, data):
|
||
if empties:
|
||
right: Any = None
|
||
elif right_column and row is not None:
|
||
right = row.get(right_column)
|
||
if right in (None, ""):
|
||
continue
|
||
elif right_ref:
|
||
right = (data or {}).get(right_ref)
|
||
if right in (None, ""):
|
||
continue
|
||
else:
|
||
right = resolve(db, cfg.get("right"), data, work=work)
|
||
if not empties and left in (None, "", [], {}):
|
||
continue
|
||
if not dicts.compare(left, op, right):
|
||
continue
|
||
gap = gap_of(op, left, right)
|
||
# 逐行比留超得最多的那行;命中但差额为 0(正好压线)也算命中,所以另留 hit 标记
|
||
if not best.hit or gap >= best.gap:
|
||
best = Hit(True, gap, right, left, where)
|
||
return best
|
||
|
||
|
||
def message_of(field: dict, cfg: dict, left: Any, right: Any, gap: float, *, where: str = "") -> str:
|
||
"""提示文案。默认那句够用,字段上 ``message`` 可以整句换掉。
|
||
|
||
``where`` 是明细表那头的"第几行",进了 ``{row}``,也拼进默认那句——
|
||
一张明细表十几行,只说「冲销明细已达到阈值」等于没说。
|
||
"""
|
||
label = str(field.get("label") or field.get("key") or "")
|
||
template = str(cfg.get("message") or "").strip()
|
||
at = f"({where})" if where else ""
|
||
values = {
|
||
"label": label, "left": _text(left), "right": _text(right),
|
||
"gap": _text(gap), "row": where, "column": column_of(cfg),
|
||
}
|
||
if template:
|
||
try:
|
||
return template.format(**values)
|
||
except (KeyError, IndexError, ValueError):
|
||
return template
|
||
op = str(cfg.get("op") or "").strip()
|
||
if op == "empty":
|
||
return f"「{label}」{at}还没填:这条阈值要求它填了才能过。"
|
||
if op == "notEmpty":
|
||
return f"「{label}」{at}已经填了:这条阈值不允许它填。"
|
||
return f"「{label}」{at}已达到阈值:{values['left']}(阈值 {values['right']})"
|
||
|
||
|
||
def _text(value: Any) -> str:
|
||
"""金额一律带千分位与两位小数:表单里的数一会儿是 int 一会儿是 float,
|
||
文案里两种写法混着出现最容易被财务问「这两个数怎么长得不一样」。"""
|
||
if isinstance(value, bool):
|
||
return str(value)
|
||
if isinstance(value, (int, float)):
|
||
return f"{value:,.2f}"
|
||
return "" if value is None else str(value)
|
||
|
||
|
||
def apply_check(db: Session, fields: Iterable[dict] | None, data: dict, *, work=None, actor=None) -> None:
|
||
"""提交链路里的阈值判定:算一遍 -> 写标记格 -> 该挡的挡。
|
||
|
||
位置排在额度之后、必填校验之前:额度与公式都已经算完,读到的就是这次提交的真数;
|
||
而阈值要挡的话,得赶在"请填写某某"之前把话说清楚。
|
||
"""
|
||
entries = threshold_fields(fields)
|
||
if not entries:
|
||
return
|
||
EngineError = _engine_error()
|
||
for field, cfg in entries:
|
||
key = str(field.get("key") or "")
|
||
result = evaluate(db, field, cfg, data, work=work)
|
||
flag = str(cfg.get("flag") or "").strip()
|
||
if flag and flag != key:
|
||
data[flag] = result.gap if result.hit else 0
|
||
mode = str(cfg.get("mode") or MODE_WARN).strip()
|
||
if not result.hit or mode == MODE_MARK:
|
||
continue
|
||
if mode == MODE_BLOCK:
|
||
raise EngineError(
|
||
message_of(field, cfg, result.left, result.right, result.gap, where=result.where)
|
||
)
|
||
|
||
|
||
def problems(fields: Iterable[dict] | None) -> list[str]:
|
||
"""字段上 ``threshold`` 配置的毛病。与 ``quota.problems`` 同一把尺子,前端有镜像。"""
|
||
out: list[str] = []
|
||
rows = [item for item in (fields or []) if isinstance(item, dict)]
|
||
keys = {str(item.get("key") or "").strip() for item in rows}
|
||
for index, item in enumerate(rows, start=1):
|
||
cfg = item.get(FIELD_PROP)
|
||
if cfg is None or cfg == {} or cfg == "":
|
||
continue
|
||
shown = str(item.get("label") or item.get("key") or "").strip() or "未命名"
|
||
at = f"第 {index} 个字段「{shown}」的阈值规则"
|
||
if not isinstance(cfg, dict):
|
||
out.append(f"{at}的格式不对")
|
||
continue
|
||
op = str(cfg.get("op") or "").strip()
|
||
if not op:
|
||
out.append(f"{at}没选比较符")
|
||
continue
|
||
column = column_of(cfg)
|
||
right_column = right_column_of(cfg)
|
||
is_table = str(item.get("type") or "") == "table"
|
||
if op not in OPS:
|
||
out.append(f"{at}的比较符不支持:{op}")
|
||
else:
|
||
allowed = ops_for_field(item, cfg)
|
||
if allowed and op not in allowed:
|
||
out.append(
|
||
f"{at}是明细表:要先点明比哪一列,比大小才有意义"
|
||
if is_table and not column and op in FULL_OPS
|
||
else f"{at}用的「{op}」这一格比不了:{'、'.join(allowed)} 才用得上"
|
||
)
|
||
if not is_table and (column or right_column):
|
||
out.append(f"{at}不是明细表,用不上「比哪一列」(column / rightColumn)")
|
||
if is_table and (column or right_column):
|
||
columns = {
|
||
str(one.get("key") or "").strip()
|
||
for one in (item.get("columns") or []) if isinstance(one, dict)
|
||
}
|
||
for name in (column, right_column):
|
||
if name and name not in columns:
|
||
out.append(f"{at}要比的明细表列「{name}」不存在")
|
||
if right_column and not column:
|
||
out.append(f"{at}要跟本表的某一列比,得先点明比哪一列")
|
||
elif right_column and scope_of(cfg) == SCOPE_SUM:
|
||
out.append(f"{at}按合计比的时候比不了行里的列:合计只有一个数,那一列是每行一个")
|
||
if op not in ("empty", "notEmpty"):
|
||
right_field = right_key(cfg)
|
||
if right_field and right_field not in keys:
|
||
out.append(f"{at}要比的字段「{right_field}」不存在")
|
||
elif right_field == str(item.get("key") or "").strip():
|
||
out.append(f"{at}拿自己跟自己比,永远不会命中")
|
||
elif not right_field and not right_column and not str(cfg.get("right") or "").strip():
|
||
# 右边可以是常量、别的字段,也可以是本表的某一列,三样都没给才叫没配
|
||
out.append(f"{at}没填阈值:给个常量,或者挑一个要比的字段 / 明细列")
|
||
mode = str(cfg.get("mode") or MODE_WARN).strip()
|
||
if mode not in MODES:
|
||
out.append(f"{at}的下场不支持:{mode}")
|
||
flag = str(cfg.get("flag") or "").strip()
|
||
if flag and flag not in keys:
|
||
out.append(f"{at}要写入的标记字段「{flag}」不存在")
|
||
return out
|
||
|
||
|
||
def _engine_error():
|
||
"""延迟导入:``app.engine.engine`` 会 import 本模块,顶层导会成环。"""
|
||
from ..engine import engine as engine_module
|
||
|
||
return engine_module.EngineError
|