178 lines
6.8 KiB
Python
178 lines
6.8 KiB
Python
"""流程匹配与定义校验。
|
||
|
||
一个业务模块常常要按项目类型、金额区间走不同流程(老系统是靠 ``ActProjectTypeEnum``
|
||
和硬编码的项目类型分支实现的)。这里改成"已发布流程 + 匹配条件 + 优先级",新增一条
|
||
分支不用改代码。
|
||
|
||
条件表达式刻意用受限语法(``字段 运算符 值``,多个用 and/or 串起来),不 eval:
|
||
流程管理员写的东西会进数据库并被执行,任何能写表达式的口子都是攻击面。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
import re
|
||
from typing import Any
|
||
|
||
from sqlalchemy import select
|
||
from sqlalchemy.orm import Session
|
||
|
||
from ...models import ApprovalFlow, ApprovalNode, FlowStatus, NodeType
|
||
|
||
_CONDITION_PATTERN = re.compile(
|
||
r"^\s*(?P<field>[A-Za-z_][A-Za-z0-9_.]*)\s*(?P<op>>=|<=|==|!=|>|<|in|contains)\s*(?P<value>.+?)\s*$"
|
||
)
|
||
|
||
def evaluate_simple_condition(expression: str, variables: dict[str, Any]) -> bool:
|
||
"""``contract_amount>=5000000 and type in [1,2]`` 这样的合取/析取式。"""
|
||
text = (expression or "").strip()
|
||
if not text:
|
||
return True
|
||
|
||
for connector, all_or_any in ((" or ", False), (" and ", True)):
|
||
parts = [part.strip() for part in text.split(connector) if part.strip()]
|
||
if len(parts) > 1:
|
||
results = [evaluate_simple_condition(part, variables) for part in parts]
|
||
return all(results) if all_or_any else any(results)
|
||
|
||
match = _CONDITION_PATTERN.match(text)
|
||
if not match:
|
||
return False
|
||
field_name = match.group("field")
|
||
operator = match.group("op")
|
||
raw_value = match.group("value")
|
||
left = _lookup(variables, field_name)
|
||
right = _parse_literal(raw_value)
|
||
|
||
if operator == "in":
|
||
return left in (right if isinstance(right, (list, tuple, set)) else [right])
|
||
if operator == "contains":
|
||
return str(right) in str(left or "")
|
||
if operator in (">", "<", ">=", "<="):
|
||
try:
|
||
left_number, right_number = float(left or 0), float(right if not isinstance(right, bool) else int(right))
|
||
except (TypeError, ValueError):
|
||
return False
|
||
return {">": left_number > right_number, "<": left_number < right_number,
|
||
">=": left_number >= right_number, "<=": left_number <= right_number}[operator]
|
||
if operator == "!=":
|
||
return str(left) != str(right)
|
||
return str(left) == str(right)
|
||
|
||
|
||
def _lookup(variables: dict[str, Any], dotted: str) -> Any:
|
||
current: Any = variables
|
||
for part in dotted.split("."):
|
||
if isinstance(current, dict):
|
||
current = current.get(part)
|
||
else:
|
||
return None
|
||
return current
|
||
|
||
|
||
def _parse_literal(raw: str) -> Any:
|
||
text = raw.strip()
|
||
if text.startswith("[") and text.endswith("]"):
|
||
try:
|
||
return json.loads(text)
|
||
except json.JSONDecodeError:
|
||
return [item.strip().strip("'\"") for item in text[1:-1].split(",") if item.strip()]
|
||
if text.lower() in ("true", "false"):
|
||
return text.lower() == "true"
|
||
if (text.startswith('"') and text.endswith('"')) or (text.startswith("'") and text.endswith("'")):
|
||
return text[1:-1]
|
||
try:
|
||
return float(text) if "." in text else int(text)
|
||
except ValueError:
|
||
return text
|
||
|
||
|
||
def match_flow(db: Session, module: str, variables: dict[str, Any]) -> ApprovalFlow | None:
|
||
"""挑一条最合适的已发布流程。
|
||
|
||
先按 ``priority`` 小的优先,其次按"匹配条件写得更多"的优先——没有显式条件的那条
|
||
是兜底默认流程,永远排最后。
|
||
"""
|
||
flows = db.execute(
|
||
select(ApprovalFlow).where(
|
||
ApprovalFlow.business_module == module,
|
||
ApprovalFlow.status == FlowStatus.PUBLISHED,
|
||
ApprovalFlow.is_deleted.is_(False),
|
||
).order_by(ApprovalFlow.priority, ApprovalFlow.id.desc())
|
||
).scalars().all()
|
||
|
||
candidates: list[tuple[int, int, ApprovalFlow]] = []
|
||
for flow in flows:
|
||
conditions = _conditions(flow.match_json)
|
||
if not conditions:
|
||
candidates.append((2, flow.priority, flow)) # 默认流程
|
||
continue
|
||
if all(evaluate_simple_condition(expression, variables) for expression in conditions):
|
||
candidates.append((0 if len(conditions) > 1 else 1, flow.priority, flow))
|
||
|
||
if not candidates:
|
||
return None
|
||
candidates.sort(key=lambda item: (item[0], item[1], -item[2].id))
|
||
return candidates[0][2]
|
||
|
||
|
||
def _conditions(raw: str) -> list[str]:
|
||
if not (raw or "").strip():
|
||
return []
|
||
try:
|
||
data = json.loads(raw)
|
||
except json.JSONDecodeError:
|
||
return [raw]
|
||
if isinstance(data, str):
|
||
return [data]
|
||
if isinstance(data, dict):
|
||
expressions = data.get("expressions") or []
|
||
return [str(item) for item in expressions if str(item).strip()]
|
||
return [str(item) for item in data if str(item).strip()]
|
||
|
||
|
||
def node_condition_passes(node: ApprovalNode, variables: dict[str, Any]) -> bool:
|
||
from ...models import NodeType as _NodeType
|
||
|
||
if node.node_type == _NodeType.CONDITION:
|
||
# 条件节点自身就是判定:通过 condition_json 决定流程是否继续走它后面的分支
|
||
return evaluate_simple_condition(node.condition_json, variables)
|
||
return evaluate_simple_condition(node.condition_json, variables)
|
||
|
||
|
||
def ordered_nodes(flow: ApprovalFlow) -> list[ApprovalNode]:
|
||
return sorted(
|
||
[node for node in flow.nodes if node.enabled and not node.is_deleted],
|
||
key=lambda node: (node.order_number, node.id),
|
||
)
|
||
|
||
|
||
def definition_errors(flow: ApprovalFlow) -> list[str]:
|
||
"""发布前自检:把"发出去才发现流程不通"挡在发布这一步。"""
|
||
nodes = ordered_nodes(flow)
|
||
errors: list[str] = []
|
||
if not nodes:
|
||
return ["流程没有任何节点"]
|
||
if not any(node.node_type == NodeType.APPROVE for node in nodes):
|
||
errors.append("流程至少要有一个审批节点")
|
||
|
||
keys = [node.node_key for node in nodes]
|
||
if len(keys) != len(set(keys)):
|
||
errors.append("存在重复的节点标识")
|
||
|
||
known = set(keys)
|
||
for node in nodes:
|
||
if node.next_node_key and node.next_node_key not in known:
|
||
errors.append(f"节点「{node.name}」的去向 {node.next_node_key} 不存在")
|
||
if node.reject_to not in ("end", "initiator") and node.reject_to not in known:
|
||
errors.append(f"节点「{node.name}」的驳回去向 {node.reject_to} 不存在")
|
||
for target in json.loads(node.rollback_keys_json or "[]"):
|
||
if target not in known:
|
||
errors.append(f"节点「{node.name}」允许退回的 {target} 不存在")
|
||
from .candidates import parse_config
|
||
|
||
for item in parse_config(node.candidates_json):
|
||
if not item.get("type"):
|
||
errors.append(f"节点「{node.name}」有缺少 type 的候选人配置")
|
||
return errors
|