unis-oa/backend/app/service/simulator.py

1622 lines
76 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

"""流程试跑:选好发起人、填好表单,先把这一单预先走一遍。
设计器的「校验」只看得见解得开画布的问题——缺出口、分支没有默认分支、环节不可达。
一张单真跑起来会落在谁手上、哪一环会因为找不到人自动通过、条件分支实际走哪一支、
并联汇聚等不等得齐、明细会拆出几条支线,光看图是看不出来的,只能等真发一单。
本模块按运行时的口径空跑一遍:找人、算条件、免审、去重、兜底全部直接调 ``engine``
里正在用的那几个函数,不另写一套规则,免得「试跑说没问题,真跑起来不是这么走的」。
试跑刻意不做三件事:
- **不落库、不派待办、不发通知**:全程只读。唯一的"写"是内存里那份表单数据——
系统带出与公式得先算出来,条件分支读的就是它。
- **不执行有副作用的环节**:脚本、外部调用、子流程一律原样经过并写明「试跑不执行」;
外部数据源带出的值与额度记账同样不做,配了这些东西的环节会挂一条说明。
- **不替人做决定,但替表单把能定的都定死**:同意还是退回是人的事,数据说了算的那部分
一律按这份表单收敛成一条——条件分支只走引擎会挑的那一支,人工环节的同名出口(待办上
本来就是一个按钮)也在按钮里按条件挑一条,适用条件当前不成立的出口点了会被引擎拦,
干脆不铺开。铺得开的才叫「由审批人选择」,退回路由(``goBack``)不参与预测。
唯一的例外是整环自动跳过:那时没有手能点,引擎照画布上第一条出口走,试跑照它。
算不准的地方一律往保守说:脚本找人、按上一环节处理人找人,换个人发起就可能换个人,
这类环节标 ``dynamic``。结论分三档——``ok`` 一路走到结束、``risk`` 走得通但有几处要人
看一眼、``blocked`` 会被挡住(必填没填、拆分没明细、汇聚等不齐、环路……)。
"""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any
from sqlalchemy import select
from sqlalchemy.orm import Session
from .. import models
from ..engine import definition as definition_module
from ..engine import lookahead
from ..engine.definition import ActivityNode, ProcessDefinition, RouteNode
from . import autofill as autofill_module
from . import dicts, fetch as fetch_module, flowmap, formruntime, org
from . import quota as quota_module, starters, threshold as threshold_module
# ---------------------------------------------------------------------------
# 上限:设计图再离谱,一次点击也不该变成一次卡顿
# ---------------------------------------------------------------------------
#: 整条试跑累计走访的环节数
MAX_STEPS = 400
#: 单条支线一口气走多少步就认定有环路
MAX_ROUNDS = 120
#: 一个分叉最多展开几条支线(并联画 50 条不常见,但得挡住)
MAX_BRANCHES = 24
#: 拆分环节最多试算几行明细:支线形状一样,看两行足够
MAX_SPLIT_ITEMS = 3
#: 同一个环节最多被走到几次(并联支线各自走到同一环是合法的)
MAX_NODE_VISITS = 8
#: 只有这几种审批方式能把「这一环他一定签过」当成事实,口径同 ``lookahead.STRICT_MODES``。
STRICT_MODES = frozenset({"all", "join", "serial"})
#: 结论档位
VERDICT_OK = "ok"
VERDICT_RISK = "risk"
VERDICT_BLOCKED = "blocked"
#: 发现的严重程度
LEVEL_ERROR = "error"
LEVEL_WARN = "warn"
LEVEL_INFO = "info"
#: 一次走访的结果。比 ``flowmap`` 那套运行时状态多两档:``waiting`` 是并联汇聚在等
#: 别的支线,``stopped`` 是这一路走到了作废环节。
VISIT_PASSED = "passed"
VISIT_SKIPPED = "skipped"
VISIT_WAITING = "waiting"
VISIT_BLOCKED = "blocked"
VISIT_STOPPED = "stopped"
#: 走访结果 -> 轨迹图上的节点状态(与 ``service/flowmap.py`` 同一套词,前端共用一个组件)
VISIT_TO_STATE = {
VISIT_PASSED: flowmap.STATE_DONE,
VISIT_SKIPPED: flowmap.STATE_SKIPPED,
VISIT_WAITING: flowmap.STATE_ACTIVE,
VISIT_BLOCKED: flowmap.STATE_STOPPED,
VISIT_STOPPED: flowmap.STATE_STOPPED,
}
@dataclass
class _Finding:
"""一条试跑发现:``level`` 定 severity,``activity`` 让界面点了能跳到那一环。"""
level: str
message: str
activity: str = ""
kind: str = ""
def as_dict(self) -> dict[str, Any]:
return {"level": self.level, "message": self.message, "activity": self.activity, "kind": self.kind}
@dataclass
class _Visit:
"""一次「这一单走到这一环」。并联支线和「出口由审批人选」都会让同一环被走到好几次。"""
index: int
activity: str
name: str
type: str
state: str
via: str = ""
branch: str = ""
mode: str = ""
note: str = ""
handlers: list[dict] = field(default_factory=list)
dropped: list[dict] = field(default_factory=list)
watchers: list[dict] = field(default_factory=list)
outcomes: list[dict] = field(default_factory=list)
dynamic: bool = False
def as_dict(self) -> dict[str, Any]:
return {
"index": self.index,
"activity": self.activity,
"name": self.name,
"type": self.type,
"state": self.state,
"via": self.via,
"branch": self.branch,
"mode": self.mode,
"note": self.note,
"handlers": list(self.handlers),
"dropped": list(self.dropped),
"watchers": list(self.watchers),
"outcomes": list(self.outcomes),
"dynamic": self.dynamic,
}
@dataclass
class _Token:
"""试跑令牌:只带四样东西——走到哪、怎么走过来的、在等哪张票箱、上一环节是谁。"""
activity: str
path: str
stack: tuple[str, ...] = ()
join: str = ""
branch: str = ""
via: str = ""
prev: tuple[str, ...] = ()
@dataclass
class _SimWork:
"""引擎那批函数只认几个属性,不需要真的 ``models.Work`` 行。
试跑全程不落库,所以这里是个形状正确的替身:``_context``、
``resolve_task_identities``、``_fallback_identities`` 读到的字段与真单据同名同形。
"""
id: str = "simulate"
job: str = "simulate"
serial: str = ""
title: str = ""
process: str = ""
process_name: str = ""
creator: str = ""
creator_person: str = ""
creator_identity: str = ""
creator_unit: str = ""
creator_unit_name: str = ""
data: dict = field(default_factory=dict)
variables: dict = field(default_factory=dict)
joins: dict = field(default_factory=dict)
status: str = "running"
activity: str = ""
class _Simulator:
"""按画布上这份定义空跑一遍。
与引擎的分工:判定口径(找人、条件、免审、去重、兜底、票数)一律现调 ``engine``
里的函数,本类只负责「往下走」——引擎停在人工环节等人点同意,试跑替它点下去,
于是能一路看到底。
"""
def __init__(self, db: Session, definition: ProcessDefinition, work: _SimWork) -> None:
from ..engine import engine as flow # 延迟导入:engine 反过来 import 了 service 这一堆
self.flow = flow
self.db = db
self.definition = definition
self.work = work
self.steps: list[_Visit] = []
self.node_visits: dict[str, list[_Visit]] = {}
self.findings: list[_Finding] = []
self.edges: dict[str, dict] = {
route.id: {"id": route.id, "used": False, "count": 0, "time": None, "back": False}
for route in definition.routes
}
#: 并联/拆分票箱,形状与 ``engine.tickets`` 用的那份完全一致
self.joins: dict[str, dict] = {}
#: 这一趟试跑里已经真签过字的人:「前面批过就跳过」拿它当凭据(口径见 :meth:`_dedup`)
self.approved: set[str] = set()
self.tokens: list[_Token] = []
self.endings: list[dict] = []
self.paths: set[str] = set()
self.blocked = False
# -- 记账 ---------------------------------------------------------------
def _add(self, level: str, message: str, *, activity: str = "", kind: str = "") -> None:
if message not in [item.message for item in self.findings]:
self.findings.append(_Finding(level=level, message=message, activity=activity, kind=kind))
def _error(self, message: str, *, activity: str = "", kind: str = "") -> None:
self._add(LEVEL_ERROR, message, activity=activity, kind=kind)
def _warn(self, message: str, *, activity: str = "", kind: str = "") -> None:
self._add(LEVEL_WARN, message, activity=activity, kind=kind)
def _info(self, message: str, *, activity: str = "", kind: str = "") -> None:
self._add(LEVEL_INFO, message, activity=activity, kind=kind)
def _record(
self,
node: ActivityNode,
state: str,
*,
via: RouteNode | None = None,
token: _Token | None = None,
note: str = "",
handlers: list[dict] | None = None,
dropped: list[dict] | None = None,
watchers: list[dict] | None = None,
outcomes: list[dict] | None = None,
mode: str = "",
dynamic: bool = False,
) -> _Visit:
visit = _Visit(
index=len(self.steps) + 1,
activity=node.id,
name=node.name,
type=node.type,
state=state,
via=via.name if via else "",
branch=token.branch if token else "",
mode=mode,
note=note,
handlers=list(handlers or []),
dropped=list(dropped or []),
watchers=list(watchers or []),
outcomes=list(outcomes or []),
dynamic=dynamic,
)
self.steps.append(visit)
self.node_visits.setdefault(node.id, []).append(visit)
return visit
# -- 口径工具 -----------------------------------------------------------
def _context(self, node: ActivityNode | None = None, token: _Token | None = None) -> dict:
"""求值上下文直接借引擎那份,口径不会和真跑的时候分裂。"""
prev = list(token.prev) if token else []
extra: dict[str, Any] = {
"prev_task_identity_list": prev,
"prev_identity": prev[0] if prev else "",
}
if node is not None:
extra["activity"] = {"id": node.id, "name": node.name}
return self.flow._context(self.db, self.work, None, extra)
def _label(self, identity: str) -> dict:
ref = org.ref_for(self.db, identity)
return {
"identity": identity,
"person": ref.person,
"name": ref.person_name or ref.name or identity,
"unit": ref.unit_name,
}
def _names(self, identities: list[str]) -> list[str]:
return [self._label(item)["name"] for item in identities]
def _decision(self, node: ActivityNode, route: RouteNode) -> str:
return self.flow._route_decision(self.definition, node, route.name)
def _forward(self, node: ActivityNode) -> list[RouteNode]:
"""往前走的路由:回头线(退回 / 拒绝)不参与预测,那是人按下退回之后的事。
判据是 ``definition.is_back_route``,与 ``engine.lookahead._routes``、
``definition.upstream_ids`` 同一份(含没标语义但绕回自己的那条边):预测里把
驳回线当正常出口走,会绕回前面重新摊一遍已经批过的环节,画出来的"会走到哪"
比真跑多一整圈。
"""
return definition_module.forward_routes(self.definition, node.id)
def _single(self, node: ActivityNode) -> RouteNode | None:
routes = self._forward(node)
return routes[0] if routes else None
def _why_unknown(self, expression: str, context: dict) -> str:
"""把「条件算不出来」的原因捞出来:是脚本写坏了,还是这一单少填了一格。"""
from ..engine import expressions
try:
expressions.evaluate(expression, context)
except Exception as exc: # noqa: BLE001 - 只为措辞重算一遍,判定已经由 guard_state 给过
return str(exc)
return "条件没写错,是这份表单数据让它算不出结果(多半是它读的字段还没填)"
def _guard(self, route: RouteNode, context: dict) -> str:
"""这一条出口的适用条件当场算成什么,判定口径直接取 :func:`engine.guard_state`。
``unknown``(当场算不出来)额外记一条说明:引擎和界面都把它跟「不成立」一样拦下来,
但对设计者是完全不同的两件事——一句是「这格还没填,填全了可能就换一条路」,
一句是「这条业务规则这一单没碰上」。混在一起说等于什么都没说。
"""
state = self.flow.guard_state(self.db, self.work, route, context)
if state == self.flow.GUARD_UNKNOWN:
self._warn(
f"路由 {route.name} 的适用条件当场算不出来:"
f"{self._why_unknown(str(route.expression or ''), context)}。这一单真跑的时候这一条会被拦住",
activity=route.to_activity,
kind="route_guard",
)
return state
def _condition_hit(self, expression: str, context: dict, *, where: str) -> bool:
from ..engine import expressions
# 这里要用 evaluate 而不是 evaluate_condition:后者把异常咽成 False,那条
# 「条件算不出来」的提示就永远发不出去,而分支悄悄走了默认那一条恰恰最难查。
try:
return bool(expressions.evaluate(expression, context))
except Exception as exc: # noqa: BLE001 - 条件写坏时按不命中处理,和运行时一致
self._warn(
f"{where}的条件当场算不出来,这一单按不成立处理:{exc}。把这一格填上再试,"
"走的可能就是另一条分支",
kind="expression",
)
return False
def _guards(self, routes: list[RouteNode], context: dict) -> dict[str, str]:
"""一批出口各自的适用条件结果,同一条只算一遍(算不出来的说明也只记一遍)。"""
return {route.id: self._guard(route, context) for route in routes}
def _buttons(
self, node: ActivityNode, context: dict, guards: dict[str, str] | None = None
) -> tuple[list[dict], list[RouteNode]]:
"""把往前走的路由并成「待办上的按钮」,再按这份表单算出每个按钮真正落在哪一环。
三条口径都照抄运行时,少一条预测就会多画一条根本走不到的路:
- 同名出口在待办上就是一个按钮(分组同 ``TaskDetailView.routeButtons``,按 ``name``);
- 一个按钮里的几条同名出口由引擎按条件挑一条(``engine._resolve_route`` →
``_route_by_condition``),不是每条都要走一遍;
- 整组都被适用条件挡住的按钮点了也会被引擎拦(``engine.route_guard_ok``),
这一单根本走不到,就别画进预测里。
返回 ``(点得动的按钮, 被这份表单挡住的出口)``,按钮形如
``{"name": 按钮名, "route": 按表单挑中的那条, "siblings": 同名出口条数}``。
"""
states = guards or self._guards(self._forward(node), context)
groups: dict[str, list[RouteNode]] = {}
for route in self._forward(node):
groups.setdefault(route.name, []).append(route) # 顺序就是画布上路由的顺序
buttons: list[dict] = []
blocked: list[RouteNode] = []
for name, rows in groups.items():
live = [route for route in rows if states.get(route.id) == self.flow.GUARD_TRUE]
if not live:
blocked.append(rows[0])
continue
picked = self.flow._route_by_condition(live, context) or live[0]
buttons.append({"name": name, "route": picked, "siblings": len(rows)})
return buttons, blocked
def _exit_note(self, buttons: list[dict]) -> str:
"""把「这一环还能点哪些按钮、每个按钮按这份表单去哪」串成一句;单按钮单出口不啰嗦。"""
parts: list[str] = []
for item in buttons:
target = self.definition.activity(item["route"].to_activity)
name = item["name"]
if item["siblings"] > 1 and target is not None:
parts.append(f"「{name}」有 {item['siblings']} 条同名出口,按这份表单走「{target.name}」")
else:
parts.append(f"「{name}」")
if len(buttons) > 1:
return "出口由审批人选择:" + "、".join(parts)
if any("同名出口" in part for part in parts):
return "这一环只有一个出口按钮," + parts[0]
return ""
def _cc(self, node: ActivityNode, context: dict) -> list[dict]:
"""这一环会抄送给谁(到达时 + 办结后两批一起算,界面上合成一行「抄送:…」)。"""
rules = self.flow.cc_rules(node, "arrive") + self.flow.cc_rules(node, "complete")
if not rules:
return []
seen: list[dict] = []
for rule in rules:
if not self.flow.cc_rule_matches(context, rule):
continue
for identity in self.flow.cc_identities(self.db, self.work, None, rule, node, context):
brief = self._label(identity)
if brief["identity"] not in [item["identity"] for item in seen]:
seen.append(brief)
return seen
# -- 走图 ---------------------------------------------------------------
def run(self) -> dict:
begin = self.definition.begin
if begin is None or not self.definition.activities:
self._error("画布上还没有开始环节,试跑无从走起", kind="no_begin")
self.blocked = True
return self.result()
self.tokens = [_Token(activity=begin.id, path=begin.id)]
while self.tokens:
self._walk(self.tokens.pop(0))
self._closing()
return self.result()
def _walk(self, token: _Token) -> None:
current = token.activity
via_id = token.via
rounds = 0
while current:
rounds += 1
if rounds > MAX_ROUNDS:
self._error(
f"一条支线连走 {MAX_ROUNDS} 步还没到头,画布上多半有环路", activity=current, kind="loop"
)
self.blocked = True
return
node = self.definition.activity(current)
if node is None:
self._error(f"有一条路由指向的环节({current})已经不存在了", kind="route")
self.blocked = True
return
route = self._arrive(node, token, self.definition.route(via_id) if via_id else None)
if route is None:
return
token.stack = token.stack + (node.id,)
current = route.to_activity
via_id = route.id
def _arrive(self, node: ActivityNode, token: _Token, via: RouteNode | None) -> RouteNode | None:
"""走到 ``node``:记下这一环的结论,返回下一步要走的那条路由(``None`` = 这条支线到此为止)。"""
if via is not None:
edge = self.edges.get(via.id)
if edge is not None:
edge["used"] = True
edge["count"] += 1
if len(self.steps) >= MAX_STEPS:
self._error(f"试跑走了 {MAX_STEPS} 步还没走完,先检查画布上有没有环路", kind="budget")
self.blocked = True
return None
if node.id in token.stack:
chain = " → ".join(
[(self.definition.activity(item).name if self.definition.activity(item) else item) for item in token.stack][-5:]
)
self._error(
f"环节 {node.name} 会被绕回来:{chain} → {node.name}。引擎遇到环路会直接报错,这一单发不出去",
activity=node.id,
kind="loop",
)
self._record(node, VISIT_BLOCKED, via=via, token=token, note="不靠退回就绕回本环,引擎会报错停下")
self.blocked = True
return None
if len(self.node_visits.get(node.id, ())) >= MAX_NODE_VISITS:
self._warn(f"环节 {node.name} 已经被走到 {MAX_NODE_VISITS} 次,试跑不再往下展开", activity=node.id, kind="budget")
return None
kind = node.type
if kind == definition_module.ACTIVITY_MANUAL:
return self._on_manual(node, token, via)
if kind == definition_module.ACTIVITY_CHOICE:
return self._on_choice(node, token, via)
if kind in {definition_module.ACTIVITY_PARALLEL, definition_module.ACTIVITY_SPLIT}:
return self._on_fork(node, token, via)
if kind == definition_module.ACTIVITY_MERGE:
return self._on_merge(node, token, via)
if kind == definition_module.ACTIVITY_END:
return self._on_end(node, token, via)
if kind == definition_module.ACTIVITY_CANCEL:
return self._on_cancel(node, token, via)
if kind in {
definition_module.ACTIVITY_BEGIN,
definition_module.ACTIVITY_SCRIPT,
definition_module.ACTIVITY_INVOKE,
definition_module.ACTIVITY_EMBED,
definition_module.ACTIVITY_DELAY,
}:
return self._on_pass_through(node, token, via)
self._error(f"环节 {node.name} 的类型({kind})不认识,试跑走不下去", activity=node.id, kind="type")
self._record(node, VISIT_BLOCKED, via=via, token=token, note=f"未知的环节类型:{kind}")
self.blocked = True
return None
def _no_exit(self, node: ActivityNode, token: _Token, via: RouteNode | None, *, who: str) -> None:
self._error(f"{who} {node.name} 没有往前走的路由,这一单会停在这里发不出去", activity=node.id, kind="no_route")
self.blocked = True
def _on_pass_through(self, node: ActivityNode, token: _Token, via: RouteNode | None) -> RouteNode | None:
route = self._single(node)
if route is None:
self._no_exit(node, token, via, who="环节")
self._record(node, VISIT_BLOCKED, via=via, token=token, note="没有出口路由")
return None
note = ""
if node.type == definition_module.ACTIVITY_BEGIN:
note = f"由 {self.work.creator_person or '所选用户'} 发起"
elif node.type == definition_module.ACTIVITY_SCRIPT:
note = "脚本环节:试跑不执行脚本,按走完往下走"
self._info(f"环节 {node.name} 是脚本环节。试跑不执行脚本,它改的数据、算的人都不会反映在本次预测里", activity=node.id, kind="not_executed")
elif node.type == definition_module.ACTIVITY_INVOKE:
note = "外部调用环节:试跑不发请求,按走完往下走"
self._info(f"环节 {node.name} 会调外部接口。试跑不发请求,真跑时它失败会让这一环卡住", activity=node.id, kind="not_executed")
elif node.type == definition_module.ACTIVITY_EMBED:
note = "子流程环节:试跑不新建子单,按子流程批完往下走"
self._info(f"环节 {node.name} 会起一条子流程。试跑只看父单,子流程里卡不卡要单独试跑那条流程", activity=node.id, kind="not_executed")
elif node.type == definition_module.ACTIVITY_DELAY:
minutes = int(node.config.get("minutes") or 0) if isinstance(node.config, dict) else 0
note = f"会先停 {minutes} 分钟,等定时器唤醒再往下走" if minutes else "延时环节没设时长,等于直接就过去"
if minutes:
self._info(f"环节 {node.name} 会停 {minutes} 分钟等定时器,这一单在这段时间里没有待办", activity=node.id, kind="delay")
else:
self._warn(f"环节 {node.name} 是延时环节但没设时长,等于白放一个环节", activity=node.id, kind="delay")
self._record(node, VISIT_PASSED, via=via, token=token, note=note)
return route
def _on_end(self, node: ActivityNode, token: _Token, via: RouteNode | None) -> RouteNode | None:
self._record(node, VISIT_PASSED, via=via, token=token, note="照这份数据,这一路能办结")
self.endings.append({"activity": node.id, "name": node.name, "branch": token.branch})
return None
def _on_cancel(self, node: ActivityNode, token: _Token, via: RouteNode | None) -> RouteNode | None:
self._record(node, VISIT_STOPPED, via=via, token=token, note="这一路会走到「作废」环节,单据在这里被终止")
self._warn(
f"照这份数据,这一路会走进作废环节 {node.name},单子不会办结而是被作废",
activity=node.id,
kind="cancel",
)
self.endings.append({"activity": node.id, "name": node.name, "branch": token.branch, "canceled": True})
return None
# -- 人工环节 -----------------------------------------------------------
def _on_manual(self, node: ActivityNode, token: _Token, via: RouteNode | None) -> RouteNode | None:
"""走到人工环节:先照运行时的顺序把人算出来,再替审批人「点同意」往下走。
顺序与 ``engine._arrive_manual`` 保持一致:找人 → 条件必批保人 → 条件免审 →
去重 → 空审批人兜底。少一步,预测就会和真跑差出一个人。
"""
config = dict(node.config or {})
context = self._context(node, token)
rows = [item for item in (config.get("taskValues") or []) if isinstance(item, dict)]
script = str(config.get("taskScript") or "").strip()
base = [i for i in org.resolve_task_identities(self.db, self.work.process, config, context) if i]
resolved, guard, must_hits = self.flow._must_rule_hits(self.db, self.work, config, base, context)
by_rule, rule_hits = self.flow._skip_rule_hits(self.db, self.work, config, resolved, context, protected=guard)
kept, drops = self._dedup(node, config, by_rule, guard)
notes: list[str] = []
dropped = self._drop_notes(drops) + self._rule_drop_notes(rule_hits)
state = VISIT_PASSED
fallback_used = False
if not kept:
if resolved:
# 本来有人、被免审或去重清空:这是「按规则不用他批」,不是「找不到人」,
# 口径与引擎一致——这种整环跳过不能再套空审批人兜底。
state = VISIT_SKIPPED
notes.append(
self.flow._skip_rule_note(rule_hits, whole=True)
or self.flow._dedup_note(self.db, drops, whole=True)
or "这一环的人都不必再批,整环自动通过"
)
else:
fallback = [i for i in self.flow._fallback_identities(self.db, self.work, config, context) if i]
if fallback:
kept = fallback
fallback_used = True
notes.append(f"按当前配置解析不出审批人,走环节兜底:交给 {'、'.join(self._names(fallback))}")
self._warn(
f"环节 {node.name} 找不到审批人,会按兜底交给 {'、'.join(self._names(fallback))}。"
"换成别的发起人或别的表单数据,很可能一个人都找不到",
activity=node.id,
kind="empty_approver",
)
else:
state = VISIT_SKIPPED
notes.append("解析不出审批人,兜底又是「本环节自动通过」,这一环等于没有审批")
self._warn(
f"环节 {node.name} 既找不到审批人、兜底又让它自动通过:这一单在这一环不会有任何人签字",
activity=node.id,
kind="empty_approver",
)
elif rule_hits or not drops.empty:
partial = ";".join(
item
for item in (
self.flow._skip_rule_note(rule_hits, whole=False),
self.flow._dedup_note(self.db, drops, whole=False),
)
if item
)
if partial:
notes.append(partial)
must_added = [hit for hit in must_hits if hit.get("added")]
if must_added:
notes.append(self.flow._must_rule_note(must_hits))
if not rows and not script:
self._warn(
f"环节 {node.name} 还没配审批人来源"
+ (",现在这一单是靠兜底才有人的" if kept else ",这一环会自动通过"),
activity=node.id,
kind="no_approver_config",
)
mode = str(config.get("mode") or "any")
handlers = [self._label(identity) for identity in kept]
if fallback_used:
for item in handlers:
item["reason"] = "兜底接手"
if state == VISIT_PASSED and len(handlers) > 1:
names = "、".join(item["name"] for item in handlers)
if mode == "serial":
notes.append("依次审批:" + " → ".join(item["name"] for item in handlers))
elif mode == "any":
notes.append(f"或签:{names} 任一人批完就往下走")
elif mode == "ratio":
notes.append(self._ratio_note(config, handlers))
if state == VISIT_PASSED and handlers:
flags = self.flow.approval_flags(config, self.definition.approval)
if mode in STRICT_MODES or len(handlers) == 1:
self.approved.update(item["person"] for item in handlers if item["person"])
elif flags.skip_approved:
self._info(
f"环节 {node.name} 是{self._mode_label(mode)},实际只有个别人会真签字,"
"后面「前面批过就跳过」免掉谁要跟真跑的时候才对得上",
activity=node.id,
kind="dedup",
)
dynamic = bool(script) or any(
org.normalize_kind(item.get("type")) in {"creator", "prev", "prevunit", "form"} | org.RELATION_KINDS
for item in rows
)
if script:
notes.append("审批人由找人脚本算出,换一单可能换人")
self._info(f"环节 {node.name} 用脚本找人,这里的人只是拿当前这份表单当场试算的结果", activity=node.id, kind="dynamic")
watchers = self._cc(node, context)
if watchers:
notes.append("抄送:" + "、".join(item["name"] for item in watchers))
routes_all = self.definition.routes_from(node.id)
if state == VISIT_SKIPPED and routes_all and self._decision(node, routes_all[0]) in definition_module.BACK_DECISIONS:
# 整环跳过时引擎沿「第一条出口」往下走,第一条恰好是退回路由,
# 等于这张单会被自动打回——设计者多半没意识到,够格报一条错。
self._error(
f"环节 {node.name} 会被整环跳过,而它的第一条出口「{routes_all[0].name}」是退回 / 拒绝路由:"
"引擎会照着它把单子自动退回去。把免审关掉,或者把退回路由挪到第二条",
activity=node.id,
kind="skip_goback",
)
self._record(
node, state, via=via, token=token, note=";".join(notes), handlers=handlers,
dropped=dropped, watchers=watchers, mode=mode, dynamic=dynamic,
)
self.blocked = True
return None
routes = self._forward(node)
if not routes:
self._no_exit(node, token, via, who="人工环节")
self._record(node, VISIT_BLOCKED, via=via, token=token, note="没有往前走的路由", mode=mode)
return None
guards = self._guards(routes_all, context)
buttons, blocked = self._buttons(node, context, guards)
if state == VISIT_SKIPPED:
# 整环跳过时没有审批人可点,引擎走的是 ``_single_route``=画布上的第一条出口,
# 既不在同名出口里按条件挑,也不看它自己写的适用条件。预测照同一条走,否则会
# 出现「试跑走直通、真跑绕一圈」;差在哪儿得说给设计者——他配的「某部门直通
# 总经理」在这一单自动跳过时其实没生效。
first = routes[0]
siblings = [route for route in routes_all if route.name == first.name]
picked = next((item for item in buttons if item["name"] == first.name), None)
buttons = [{"name": first.name, "route": first, "siblings": len(siblings)}]
blocked = []
landing = self.definition.activity(first.to_activity)
first_ok = guards.get(first.id) == self.flow.GUARD_TRUE
if len(siblings) > 1 or not first_ok:
reasons = []
if len(siblings) > 1:
reasons.append(f"不在 {len(siblings)} 条同名出口里按条件挑")
if not first_ok:
reasons.append("也不看这条出口自己写的适用条件")
message = (
f"环节 {node.name} 整环跳过时没有审批人可点,引擎照第一条出口「{first.name}」走到"
f"「{landing.name if landing else first.to_activity}」," + "、".join(reasons)
)
if picked is not None and picked["route"].id != first.id:
target = self.definition.activity(picked["route"].to_activity)
landing2 = target.name if target else picked["route"].to_activity
message += f";有人签字时按这份表单会走「{landing2}」"
elif picked is None and not first_ok:
message += ";这一单在这条出口上连适用条件都不成立,真到这儿审批人谁都点不动"
self._warn(message, activity=node.id, kind="skip_route")
elif not buttons:
names = "、".join(dict.fromkeys(route.alias or route.name for route in routes))
hint = (
";给其中一条不写适用条件当默认出口,或者把条件改成这一单碰得上的"
if all(str(route.expression or "").strip() for route in routes)
else ""
)
self._error(
f"环节 {node.name} 的出口({names})按当前这份表单全都不满足适用条件:"
f"审批人点哪一条都会被引擎拦下,这一单卡在这一环出不去{hint}",
activity=node.id,
kind="route_guard",
)
self._record(
node, VISIT_BLOCKED, via=via, token=token, mode=mode, handlers=handlers,
dropped=dropped, watchers=watchers, note="每条出口都不满足适用条件,点不出去",
)
self.blocked = True
return None
exit_note = self._exit_note(buttons) if state != VISIT_SKIPPED else ""
if exit_note:
notes.append(exit_note)
blocked_names = list(dict.fromkeys(route.alias or route.name for route in blocked))
if blocked_names and (len(buttons) + len(blocked)) > 1:
self._info(
f"环节 {node.name} 的出口「{'、'.join(blocked_names)}」按这份表单不满足适用条件,"
"审批人这一次点不了;换一份表单再试可能就点得动",
activity=node.id,
kind="route_guard",
)
# 界面按 outcomes 决定每条出口怎么说:``guard_ok`` 是「这一次点不点得动」,
# ``explored`` 是「这一单真会走的那几条」——同名出口只有挑中的那条算走过。
walked = {item["route"].id for item in buttons}
outcomes = [
{
"route": route.id,
"name": route.alias or route.name,
"decision": self._decision(node, route),
"guard_ok": guards.get(route.id, self.flow.GUARD_TRUE) == self.flow.GUARD_TRUE,
"explored": route.id in walked,
}
for route in routes_all
]
visit = self._record(
node, state, via=via, token=token, note=";".join(notes), handlers=handlers,
dropped=dropped, watchers=watchers, outcomes=outcomes, mode=mode, dynamic=dynamic,
)
visit.note = ";".join(notes)
for item in buttons[1:]:
route = item["route"]
self.tokens.append(
_Token(
activity=route.to_activity,
path=self._next_path(f"{token.path}/{route.to_activity}"),
stack=token.stack + (node.id,),
join=token.join,
branch=f"{node.name}:{item['name']}",
via=route.id,
prev=tuple(handler["identity"] for handler in handlers) or token.prev,
)
)
token.prev = tuple(item["identity"] for item in handlers) or token.prev
return buttons[0]["route"]
def _ratio_note(self, config: dict, handlers: list[dict]) -> str:
count = int(config.get("passCount") or 0)
ratio = float(config.get("passRatio") or 0)
names = "、".join(item["name"] for item in handlers)
if count:
return f"按比例会签:{names} 里同意满 {count} 票就放行"
if ratio:
return f"按比例会签:{names} 里同意到 {ratio:g}% 就放行"
return f"按比例会签但没设票数或比例,按全部同处理:{names}"
@staticmethod
def _mode_label(mode: str) -> str:
return {"any": "或签", "all": "会签", "join": "会签", "serial": "依次审批", "ratio": "按比例会签"}.get(mode, mode)
def _drop_notes(self, drops) -> list[dict]:
"""去重免掉的人以及各自的原因,界面上一眼能看出「这一环为什么少了一个人」。"""
out: list[dict] = []
for identity in drops.starter:
brief = self._label(identity)
out.append({"name": brief["name"], "reason": "就是发起人本人"})
for identity in drops.approved:
brief = self._label(identity)
out.append({"name": brief["name"], "reason": "这一单前面已经批过"})
for identity in drops.ahead:
brief = self._label(identity)
later = drops.origin.get(brief["person"]) or ""
out.append({"name": brief["name"], "reason": f"后面还要在「{later}」批" if later else "后面还要再批一次"})
return out
@staticmethod
def _rule_drop_notes(hits: list[dict]) -> list[dict]:
out: list[dict] = []
for hit in hits or []:
label = f"命中免审规则「{hit.get('name')}」" if hit.get("name") else "命中免审规则"
for name in hit.get("names") or []:
out.append({"name": name, "reason": label})
for hit in hits or []:
for name in hit.get("spared") or []:
out.append({"name": name, "reason": "属于必批对象,免审没生效"})
return out
def _dedup(self, node: ActivityNode, config: dict, identities: list[str], protected: set[str]):
"""审批人去重:口径抄 ``engine._skip_duplicate_identities``,只是「批过的人」换成试跑自己攒的那份。
真跑时的「前面批过」查的是已办表,试跑没有已办,只能拿这一趟真走过的环节当凭据;
或签与按比例会签那一环到底谁签说不准,所以不往「批过」里记(宁可多派待办)。
"""
drops = self.flow.DedupDrops()
if not identities:
return identities, drops
skip_starter, skip_approved, skip_ahead = self.flow.approval_flags(config, self.definition.approval)
if bool(config.get("first")):
# 起草环节不做前瞻:那张待办是发起人交单的落脚处,运行时也不许吞掉。
skip_ahead = False
if not (skip_starter or skip_approved or skip_ahead):
return list(identities), drops
guard = protected or set()
forecast = self._forecast(node) if skip_ahead else lookahead.Forecast()
out: list[str] = []
ahead_dropped: list[tuple[str, str]] = []
for identity in identities:
if identity in guard:
out.append(identity)
continue
person = org.ref_for(self.db, identity).person
if skip_starter and person and person == self.work.creator:
drops.starter.append(identity)
continue
if skip_approved and person and person in self.approved:
drops.approved.append(identity)
continue
if skip_ahead and person and person in forecast.persons:
ahead_dropped.append((identity, person))
continue
out.append(identity)
if ahead_dropped:
if bool((self.definition.approval or {}).get("dedupAheadKeepOne")) and not out:
kept, kept_person = ahead_dropped.pop(0)
out.append(kept)
drops.origin.pop(kept_person, None)
for identity, person in ahead_dropped:
drops.ahead.append(identity)
drops.origin[person] = forecast.origin.get(person, "")
return out, drops
def _forecast(self, node: ActivityNode) -> lookahead.Forecast:
"""往后看「后面还要他批」的人,口径与 ``engine._upcoming_forecast`` 一致。"""
base = self._context(node=None)
def resolve(item) -> set[str]:
config = dict(item.config or {})
context = dict(base)
context["activity"] = {"id": item.id, "name": item.name}
identities = org.resolve_task_identities(
self.db,
self.work.process,
{"taskValues": config.get("taskValues") or [], "taskScript": config.get("taskScript") or ""},
context,
)
return {org.ref_for(self.db, identity).person for identity in identities if identity}
return lookahead.upcoming(
self.definition,
node.id,
resolve,
scope=self.flow.ahead_scope(dict(node.config or {}), self.definition.approval),
routes=lambda item: self.flow.forecast_routes(self.db, self.work, self.definition, item, base),
droppable=lambda item: self.flow.rule_reach(
self.db, self.flow.skip_rules(dict(item.config or {})), scope_whole=True
),
)
# -- 分支 / 分叉 / 汇聚 --------------------------------------------------
def _on_choice(self, node: ActivityNode, token: _Token, via: RouteNode | None) -> RouteNode | None:
"""条件分支:拿这份表单数据判一遍,走引擎会走的那一条。"""
routes = self.definition.routes_from(node.id)
if not routes:
self._no_exit(node, token, via, who="分支环节")
self._record(node, VISIT_BLOCKED, via=via, token=token, note="分支环节没有出口路由")
return None
context = self._context(node, token)
picked: RouteNode | None = None
reason = ""
for route in routes:
expression = str(route.expression or "").strip()
if not expression:
continue
if self._condition_hit(expression, context, where=f"分支环节 {node.name} 的路由「{route.name}」"):
picked = route
reason = f"命中条件,走「{route.alias or route.name}」"
break
outcomes = [
{
"route": route.id,
"name": route.alias or route.name,
"decision": route.decision,
"guard_ok": True,
"explored": False,
}
for route in routes
]
if picked is None:
picked = next((route for route in routes if not str(route.expression or "").strip()), None)
if picked is not None:
reason = f"没有命中任何条件,走默认分支「{picked.alias or picked.name}」"
else:
picked = routes[0]
reason = f"没有默认分支,兜底走第一条「{picked.alias or picked.name}」"
self._warn(
f"分支环节 {node.name} 的每条出口都写了条件,而且这一单一条都没命中:"
"引擎只能兜底走第一条。给一条不写条件的路由当默认分支",
activity=node.id,
kind="choice",
)
for item in outcomes:
item["explored"] = item["route"] == picked.id
if len(routes) > 1:
others = "、".join(item["name"] for item in outcomes if not item["explored"])
if others:
reason += f";这一单不会走:{others}"
self._record(node, VISIT_PASSED, via=via, token=token, note=reason, outcomes=outcomes)
return picked
def _next_path(self, path: str) -> str:
"""给支线一个不撞车的路径名,票箱才分得开(口径同 ``tickets.unique_path``)。"""
if path not in self.paths:
self.paths.add(path)
return path
index = 2
while f"{path}@{index}" in self.paths:
index += 1
unique = f"{path}@{index}"
self.paths.add(unique)
return unique
def _on_fork(self, node: ActivityNode, token: _Token, via: RouteNode | None) -> RouteNode | None:
"""并联 / 拆分:把支线全展开,汇聚那一头等它们到齐。"""
from ..engine import tickets
paired = self.flow.pair_gateways(self.definition).get(node.id) or {}
merge_id = str(paired.get("merge") or "")
merge_node = self.definition.activity(merge_id) if merge_id else None
routes = self.definition.routes_from(node.id)
items: list | None = None
if node.type == definition_module.ACTIVITY_SPLIT:
items = self.flow._split_items(self.db, self.work, node, "")
path = str(node.config.get("dataPath") or node.config.get("splitPath") or "未设置")
if not items:
self._error(
f"拆分环节 {node.name} 按「{path}」找不到明细行,引擎在这一刻会直接报错,单子发不出去。"
"要么至少留一行明细,要么在它前面加一个分支环节先判断明细条数",
activity=node.id,
kind="split",
)
self._record(node, VISIT_BLOCKED, via=via, token=token, note="明细为空,引擎在这里报错停下")
self.blocked = True
return None
if not routes:
self._no_exit(node, token, via, who="拆分环节")
self._record(node, VISIT_BLOCKED, via=via, token=token, note="拆分环节没有出口路由")
return None
branch_routes = [routes[0]] * len(items)
else:
branch_routes = routes
if not branch_routes:
self._no_exit(node, token, via, who="分叉环节")
self._record(node, VISIT_BLOCKED, via=via, token=token, note="分叉环节没有出口路由")
return None
if len(branch_routes) > MAX_BRANCHES:
self._warn(
f"{node.name} 要展开 {len(branch_routes)} 条支线,试跑只展开前 {MAX_BRANCHES} 条",
activity=node.id,
kind="budget",
)
branch_routes = branch_routes[:MAX_BRANCHES]
if items is not None:
items = items[:MAX_BRANCHES]
expected = len(branch_routes)
quota_count, quota_ratio = self.flow._join_quota(merge_node, node)
key = ""
if merge_id:
key = tickets.join_key(token.path, merge_id)
tickets.register_join(
self.joins, key, expected, merge_id, token.path, pass_count=quota_count, pass_ratio=quota_ratio
)
else:
self._warn(
f"环节 {node.name} 分出去的支线找不到对应的汇聚环节,"
"这些支线会各自走到结束,永远合不拢",
activity=node.id,
kind="gateway",
)
labels: list[str] = []
for index, route in enumerate(branch_routes):
if items is not None:
label = f"{node.name} 第 {index + 1} 行"
else:
label = f"{node.name}:{route.alias or route.name}"
labels.append(label)
self.tokens.append(
_Token(
activity=route.to_activity,
path=self._next_path(f"{token.path}/{route.to_activity}" + (f"#{index}" if items is not None else "")),
stack=token.stack + (node.id,),
join=key,
branch=label,
via=route.id,
prev=token.prev,
)
)
if key:
state = self.joins.get(key) or {}
required = tickets.join_required(state)
head = (
f"拆成 {expected} 条支线"
if items is not None
else f"同时展开 {expected} 条支线"
)
tail = (
f",「{merge_node.name if merge_node else merge_id}」全到才放行"
if required >= expected
else f",到 {required} 条就在「{merge_node.name if merge_node else merge_id}」放行"
)
note = head + tail
else:
note = f"分出 {expected} 条支线,各自走各自的"
self._record(node, VISIT_PASSED, via=via, token=token, note=note)
return None
def _on_merge(self, node: ActivityNode, token: _Token, via: RouteNode | None) -> RouteNode | None:
"""汇聚:按票箱收票。没收齐的支线停在这儿等,这条预测支线也就到此为止。"""
from ..engine import tickets
route = self._single(node)
key = token.join
if not key or key not in self.joins:
# 与引擎同口径:没有真分过叉(分支环节选一条支线走进汇聚)就不等票,直接放行,
# 否则按入口路由条数去等永远等不齐,单子会静悄悄停在汇聚上。
note = "这条支线是分支选择后单独走进汇聚的,不等票,直接合流"
else:
ready, state = tickets.arrive_join(self.joins, key, via.name if via else "")
if not ready:
box = self.joins.get(key) or {}
self._record(
node,
VISIT_WAITING,
via=via,
token=token,
note=f"汇聚在等齐支线:已到 {box.get('arrived')}/{tickets.join_required(box)} 条",
)
return None
tickets.clear_join(self.joins, key)
expected = int((state or {}).get("expected") or 0)
required = tickets.join_required(state or {})
note = f"{expected} 条支线到齐" + ("" if required >= expected else f"(够 {required} 票即放行)")
token.join = str((state or {}).get("parent_join") or "")
if route is None:
self._no_exit(node, token, via, who="汇聚环节")
self._record(node, VISIT_BLOCKED, via=via, token=token, note="汇聚环节没有出口路由")
return None
self._record(node, VISIT_PASSED, via=via, token=token, note=note)
return route
# -- 收尾 ---------------------------------------------------------------
def _closing(self) -> None:
"""支线收拢之后补一遍账:票箱没等齐、一条路都没走到结束,都是要命的。"""
from ..engine import tickets
for key, state in list(self.joins.items()):
arrived = int(state.get("arrived") or 0)
expected = int(state.get("expected") or 0)
required = tickets.join_required(state)
if arrived >= required:
continue
merge_id = str(state.get("merge") or "")
node = self.definition.activity(merge_id)
name = node.name if node else merge_id
self._error(
f"汇聚环节「{name}」等不齐:分叉出 {expected} 条支线,只有 {arrived} 条走到它,要 {required} 条才放行。"
"这一单会安安静静停在汇聚环节,谁的待办里都不会有——通常是有条支线绕过了汇聚,或者走到结束/作废去了",
activity=merge_id,
kind="join",
)
if node is not None and not self.node_visits.get(node.id):
self._record(node, VISIT_BLOCKED, note="支线等不齐,卡在汇聚环节")
self.blocked = True
if not self.endings and not self.blocked:
self._error("这一单走不到「结束」环节:所有支线都停在半路上", kind="no_end")
self.blocked = True
# -- 出图 ---------------------------------------------------------------
def _landing_activity(self) -> str:
"""第一张待办落在哪一环:整张图上唯一画成「进行中」的地方。"""
for visit in self.steps:
if visit.type == definition_module.ACTIVITY_MANUAL and visit.state == VISIT_PASSED and visit.handlers:
return visit.activity
return ""
def _flow_map(self) -> dict:
landing = self._landing_activity()
nodes: dict[str, dict] = {}
for node in self.definition.activities.values():
visits = self.node_visits.get(node.id, [])
states = [visit.state for visit in visits]
state = flowmap.STATE_PENDING
handlers: list[dict] = []
waiting: list[dict] = []
notes: list[str] = []
for visit in visits:
if visit.note and visit.note not in notes:
notes.append(visit.note)
if not visits:
state = flowmap.STATE_PENDING
elif VISIT_BLOCKED in states or VISIT_STOPPED in states:
state = flowmap.STATE_STOPPED
elif VISIT_PASSED in states:
state = flowmap.STATE_ACTIVE if node.id == landing else flowmap.STATE_DONE
elif VISIT_WAITING in states:
state = flowmap.STATE_ACTIVE
else:
state = flowmap.STATE_SKIPPED
for visit in visits:
for handler in visit.handlers:
handlers.append(
{
"name": handler["name"],
"unit": handler.get("unit") or "",
"time": None,
"route": visit.via,
"opinion": handler.get("reason") or "",
"auto": False,
"retracted": False,
}
)
if node.id == landing:
waiting.append(
{
"name": handler["name"],
"unit": handler.get("unit") or "",
"since": None,
"expire_time": None,
"expired": False,
"press_count": 0,
"delegated": False,
}
)
if VISIT_BLOCKED in states and not notes:
notes.append("试跑在这一环走不下去了")
nodes[node.id] = {
"id": node.id,
"name": node.name,
"type": node.type,
"state": state,
"arrived_time": None,
"completed_time": None,
"rounds": len(visits),
"handlers": handlers,
"waiting": waiting,
"rejected": False,
"go_back_to": "",
"skipped": VISIT_SKIPPED in states,
"partial_skipped": any(visit.dropped for visit in visits),
"partial_added": False,
"note": ";".join(notes),
"expired": False,
"urged": False,
}
reached = sum(1 for item in nodes.values() if item["state"] != flowmap.STATE_PENDING)
current = [visit.activity for visit in self.steps if visit.state == VISIT_BLOCKED]
if not current and landing:
current = [landing]
return {
"activities": [
{
"id": item.id,
"name": item.name,
"type": item.type,
"x": float(item.x),
"y": float(item.y),
}
for item in self.definition.activities.values()
],
"nodes": nodes,
"edges": self.edges,
"current": current,
"reached": reached,
"total": len(nodes),
# 和 service/flowmap.py 同一条规矩:没拖过画布的流程坐标全在 0 点,交给前端自动布局
"auto_layout": not any(item.x or item.y for item in self.definition.activities.values()),
}
def result(self) -> dict:
flow_map = self._flow_map()
findings = [item.as_dict() for item in self.findings]
states = [item["state"] for item in flow_map["nodes"].values()]
summary = {
"steps": len(self.steps),
"nodes": len(flow_map["nodes"]),
"reached": flow_map["reached"],
"passed": sum(1 for item in self.steps if item.state == VISIT_PASSED),
"skipped": sum(1 for item in self.steps if item.state == VISIT_SKIPPED),
"blocked": sum(1 for item in self.steps if item.state == VISIT_BLOCKED),
"manual": len([node for node in self.definition.activities.values() if node.type == "manual"]),
"paths": len(self.endings),
"branches": len({visit.branch for visit in self.steps if visit.branch}),
"errors": sum(1 for item in findings if item["level"] == LEVEL_ERROR),
"warns": sum(1 for item in findings if item["level"] == LEVEL_WARN),
"unreached": states.count(flowmap.STATE_PENDING),
}
return {
"flow": flow_map,
"steps": [visit.as_dict() for visit in self.steps],
"findings": findings,
"summary": summary,
"data": dict(self.work.data or {}),
"endings": self.endings,
}
# ---------------------------------------------------------------------------
# 入口
# ---------------------------------------------------------------------------
def _rows(payload: object) -> list[dict]:
if not isinstance(payload, list):
return []
return [dict(item) for item in payload if isinstance(item, dict)]
def _draft(
db: Session,
process_id: str,
activities: list[dict] | None,
routes: list[dict] | None,
approval: dict | None,
) -> tuple[list[dict], list[dict] | None, dict]:
"""取「现在画布上这一份」设计:界面传了就用传的,没传就回退到库里的设计稿。
与 ``service/dedupaudit.py`` 同一套取值口径——试跑要能对着还没保存的图画,
否则设计者每次都得先保存才能看结果。
"""
process = db.get(models.Process, process_id)
if activities is None:
activity_rows = _rows(
[
{
"id": row.id,
"type": row.type,
"name": row.name,
"alias": row.alias,
"description": row.description,
"form": row.form,
"config": dict(row.config or {}),
"x": row.x,
"y": row.y,
"order_number": row.order_number,
}
for row in db.execute(
select(models.Activity).where(models.Activity.process == process_id)
)
.scalars()
.all()
]
)
else:
activity_rows = _rows(activities)
if routes is None:
route_rows: list[dict] | None = _rows(
[
{
"id": row.id,
"name": row.name,
"alias": row.alias,
"from_activity": row.from_activity,
"to_activity": row.to_activity,
"decision": row.decision,
"expression": row.expression,
"order_number": row.order_number,
}
for row in db.execute(
select(models.Route)
.where(models.Route.process == process_id)
.order_by(models.Route.order_number, models.Route.name)
)
.scalars()
.all()
]
)
else:
route_rows = _rows(routes)
if approval is None:
approval = dict(getattr(process, "approval_config", None) or {}) if process else {}
return activity_rows, route_rows, dict(approval or {})
def _definition(
db: Session,
process_id: str,
activities: list[dict] | None,
routes: list[dict] | None,
approval: dict | None,
) -> ProcessDefinition:
"""拼出一份 ``ProcessDefinition``。画布上那份和库里那份走同一条路。"""
process = db.get(models.Process, process_id)
activity_rows, route_rows, process_approval = _draft(db, process_id, activities, routes, approval)
if route_rows is None:
definition = definition_module.load(db, process_id)
definition.approval = process_approval
return definition
definition = ProcessDefinition(
process_id=process_id,
name=getattr(process, "name", "") or "",
alias=getattr(process, "alias", "") or getattr(process, "name", "") or "",
category=getattr(process, "category", "") or "",
category_name=getattr(process, "category_name", "") or "",
latest_form=getattr(process, "latest_form", "") or "",
version=int(getattr(process, "version", 1) or 1),
approval=process_approval,
title=dict(getattr(process, "title_config", None) or {}) if process else {},
)
for row in activity_rows:
activity_id = str(row.get("id") or "")
if not activity_id:
continue
definition.activities[activity_id] = ActivityNode(
id=activity_id,
type=str(row.get("type") or "manual").lower(),
name=str(row.get("name") or "未命名环节"),
alias=str(row.get("alias") or row.get("name") or ""),
description=str(row.get("description") or ""),
form=str(row.get("form") or ""),
config=dict(row.get("config") or {}),
x=float(row.get("x") or 0),
y=float(row.get("y") or 0),
order_number=int(row.get("order_number") or 0),
)
for row in route_rows:
route = RouteNode(
id=str(row.get("id") or ""),
name=str(row.get("name") or ""),
alias=str(row.get("alias") or row.get("name") or ""),
from_activity=str(row.get("from") or row.get("from_activity") or ""),
to_activity=str(row.get("to") or row.get("to_activity") or ""),
decision=str(row.get("decision") or ""),
expression=str(row.get("expression") or ""),
order_number=int(row.get("order_number") or 0),
)
definition.routes.append(route)
definition.outbound.setdefault(route.from_activity, []).append(route)
definition.inbound.setdefault(route.to_activity, []).append(route)
for node in definition.activities.values():
if node.type == definition_module.ACTIVITY_BEGIN:
definition.begin = node
break
if definition.begin is None and definition.activities:
definition.begin = next(iter(definition.activities.values()))
return definition
def _form_problems(db: Session, definition: ProcessDefinition, data: dict) -> list[str]:
"""照这份数据能不能把单发出去:必填、明细行数、级联与选项合法性。"""
form_id = definition.latest_form
if not form_id:
return ["流程还没有绑定默认表单,发不出单"]
fields = formruntime.fields_of(_form_content(db, form_id))
if not fields:
return []
cache = dicts.DictCache(db)
return formruntime.validate_submit(fields, {}, data, cache)
def _form_content(db: Session, form_id: str) -> dict:
"""模拟要整份表单内容:与引擎走同一份只读缓存(一次模拟要问好几遍同一张表单)。"""
return autofill_module.form_content(db, str(form_id or ""))
def draft_definition(
db: Session,
process_id: str,
activities: list[dict] | None = None,
routes: list[dict] | None = None,
approval: dict | None = None,
) -> ProcessDefinition:
"""「现在画布上这一份」拼成一份流程定义:界面传了就用传的,没传回退到库里的设计稿。
试跑用它,流程设计器那一格「退回到哪些环节才发」也用它——绕开回头线算上游可达那套
判据只有一份,在前端再写一遍迟早和引擎算出两个答案。
"""
return _definition(db, process_id, activities, routes, approval)
def simulate(
db: Session,
*,
process_id: str,
data: dict | None = None,
starter_identity: str = "",
activities: list[dict] | None = None,
routes: list[dict] | None = None,
approval: dict | None = None,
as_identity: str = "",
) -> dict:
"""试跑一遍:``data`` 是发起人填的表单,``starter_identity`` 是替他发起的那个身份。
``activities`` / ``routes`` / ``approval`` 缺省时读库里的设计稿,传了就用传的,
设计器上还没保存的改动照样能试。返回三档结论(``ok`` / ``risk`` / ``blocked``)、
一张和单据详情页同形状的轨迹图、逐环节的走单记录,以及一份按严重程度排好的问题清单。
"""
from ..engine import engine as flow
process = db.get(models.Process, process_id)
if process is None:
raise ValueError(f"流程不存在: {process_id}")
definition = _definition(db, process_id, activities, routes, approval)
identity = str(starter_identity or as_identity or "").strip()
person = org.person_by_identity(db, identity) if identity else None
if person is None:
return {
"verdict": VERDICT_BLOCKED,
"ok": False,
"starter": {"identity": identity, "person": "", "name": "", "account": "", "unit_name": ""},
"flow": _empty_flow(definition),
"steps": [],
"findings": [
{
"level": LEVEL_ERROR,
"message": "还没有选定发起人:试跑要知道「谁发起这一单」,上级、部门负责人、找人脚本都跟着这个人变",
"activity": "",
"kind": "starter",
}
],
"summary": {
"steps": 0, "nodes": len(definition.activities), "reached": 0, "passed": 0, "skipped": 0,
"blocked": 0, "manual": 0, "paths": 0, "branches": 0, "errors": 1, "warns": 0, "unreached": 0,
},
"data": dict(data or {}),
"endings": [],
"structure": [],
"form": [],
}
ref = org.ref_for(db, identity)
unit = org.unit_by_identity(db, identity)
# 用引擎自己的 Actor 口径,字段(person_id 是 str、person_name 取 display_name)与真发一单时一致,
# 「跳过发起人本人」这类判定才不会因为 id 类型对不上而失灵。
actor = flow.Actor.from_ref(db, person, identity)
work = _SimWork(
process=process_id,
process_name=process.name,
serial="",
title="",
creator=actor.person_id,
creator_person=actor.person_name,
creator_identity=actor.ref,
creator_unit=unit.path if unit else ref.unit,
creator_unit_name=unit.name if unit else ref.unit_name,
data=dict(data or {}),
)
form_id = definition.latest_form
fields = formruntime.fields_of(_form_content(db, form_id))
# 系统带出与公式先在内存里算一遍:条件分支、免审条件、必填校验读的都是算完的这份数据,
# 口径与引擎发起那一单时排的顺序一致(先带出、再联动、再公式、再阈值)。
runtime_notes: list[tuple[str, str]] = []
if fields:
try:
autofill_module.apply_form(db, work, actor=actor, fields=fields)
except Exception as exc: # noqa: BLE001 - 试跑不该因为一个带出配置写坏就整个跑不动
runtime_notes.append((LEVEL_WARN, f"系统带出算不出来:{exc}"))
try:
cache = dicts.DictCache(db)
dicts.apply_auto_fill(fields, work.data, cache)
except Exception as exc: # noqa: BLE001
runtime_notes.append((LEVEL_WARN, f"字典带出算不出来:{exc}"))
try:
formruntime.compute_formulas(fields, work.data, flow._context(db, work, None))
except Exception as exc: # noqa: BLE001
runtime_notes.append((LEVEL_WARN, f"公式算不出来:{exc}"))
try:
# 环节权限也按开始那一环算一份:这一环被藏起来的格子,阈值不挡提交(与引擎同口径,
# 否则试跑报一句"会挡住"而真跑照样过,那句提示就成了新的猜测来源)。
# definition.begin 就是那个环节对象本身,不是它的 id,直接取 config 就对了。
begin = definition.begin
threshold_module.apply_check(
db, fields, work.data, work=work, actor=actor,
perms=formruntime.perm_map(begin.config if begin is not None else {}, fields),
)
except flow.EngineError as exc: # 阈值挡住提交,本身就是要报出来的一条
runtime_notes.append((LEVEL_ERROR, f"阈值规则会挡住这张单:{exc}"))
except Exception as exc: # noqa: BLE001 - 规则算崩了别谎报成"会挡住",那会让人去改一张没毛病的画布
runtime_notes.append((LEVEL_WARN, f"阈值规则算不出来,这一单到底挡不挡没法预判:{exc}"))
for fetch_field, _cfg in fetch_module.fetch_fields(fields):
runtime_notes.append(
(
LEVEL_INFO,
f"字段「{fetch_field.get('label') or fetch_field.get('key')}」的值要从外部数据源带,试跑不发请求;"
"条件若依赖它,真跑时结果可能不一样",
)
)
break
for _quota_field, _cfg in quota_module.quota_fields(fields):
runtime_notes.append(
(LEVEL_INFO, "这张单上有额度字段,试跑不查台账也不记账,超没超支要真发一单才知道")
)
break
work.title = str(work.data.get("title") or process.name)
structure = definition_module.validate(definition)
from ..engine import expressions
for route in definition.routes:
error = expressions.validate_script(route.expression or "")
if error:
structure.append(f"路由 {route.name} 条件脚本错误:{error}")
for node in definition.activities.values():
for key, value in (node.config or {}).items():
if isinstance(value, str) and key.lower().endswith("script"):
error = expressions.validate_script(value)
if error:
structure.append(f"环节 {node.name} 脚本错误:{error}")
if not starters.is_open(process):
# 发起范围按账号比,试跑这边也只看账号:多身份那套"把身上所有身份都摆进来"
# 已经没有对象可摆(见 service/personref.py)
if not starters.allowed(db, process, identities=[actor.ref], is_admin=False):
structure.append(f"「{person.name}」不在这条流程的发起范围里,真发单会被挡在发起页")
form_problems = _form_problems(db, definition, work.data)
simulator = _Simulator(db, definition, work)
for level, message in runtime_notes:
simulator._add(level, message, kind="form_runtime")
result = simulator.run()
findings = list(result["findings"])
for item in structure:
findings.append({"level": LEVEL_ERROR, "message": item, "activity": "", "kind": "structure"})
for item in form_problems:
findings.append({"level": LEVEL_ERROR, "message": f"发起会被表单校验挡住:{item}", "activity": "", "kind": "form"})
# 严重的排前面,同级别按出现的先后;同一条话只说一遍
order = {LEVEL_ERROR: 0, LEVEL_WARN: 1, LEVEL_INFO: 2}
seen: set[tuple[str, str]] = set()
ordered: list[dict] = []
for item in sorted(findings, key=lambda row: order.get(str(row.get("level")), 9)):
key = (str(item.get("level")), str(item.get("message")))
if key in seen:
continue
seen.add(key)
ordered.append(item)
findings = ordered
errors = [item for item in findings if item["level"] == LEVEL_ERROR]
warns = [item for item in findings if item["level"] == LEVEL_WARN]
verdict = VERDICT_BLOCKED if errors else (VERDICT_RISK if warns else VERDICT_OK)
result["summary"].update(
{
"errors": len(errors),
"warns": len(warns),
"infos": len([item for item in findings if item["level"] == LEVEL_INFO]),
# 分清楚「表单还没填完」和「流程本身有问题」:前者补数据就行,后者得回画布改
"form_errors": len([item for item in errors if item.get("kind") == "form"]),
"design_errors": len([item for item in errors if item.get("kind") not in ("form",)]),
"nodes": max(result["summary"]["nodes"], len(definition.activities)),
}
)
result.update(
{
"verdict": verdict,
"ok": not errors,
"findings": findings,
"structure": structure,
"form": form_problems,
"starter": {
"identity": actor.ref,
"person": actor.person_id,
"name": actor.person_name or ref.person_name,
"account": getattr(person, "account", "") or "",
"unit_name": work.creator_unit_name,
},
}
)
return result
def _empty_flow(definition: ProcessDefinition) -> dict:
return {
"activities": [
{"id": item.id, "name": item.name, "type": item.type, "x": float(item.x), "y": float(item.y)}
for item in definition.activities.values()
],
"nodes": {},
"edges": {},
"current": [],
"reached": 0,
"total": len(definition.activities),
"auto_layout": not any(item.x or item.y for item in definition.activities.values()),
}