1211 lines
57 KiB
Python
1211 lines
57 KiB
Python
"""In-memory view of a published process definition.
|
||
|
||
Equivalent to the ``Processing`` object that O2OA builds from the designer XML
|
||
before handing it to the ``x_processplatform_service_processing`` engine.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import hashlib
|
||
import json
|
||
from collections import OrderedDict
|
||
from collections.abc import Iterable
|
||
from dataclasses import dataclass, field
|
||
from datetime import datetime
|
||
|
||
from sqlalchemy import select
|
||
from sqlalchemy.orm import Session
|
||
|
||
from .. import dbconfig, designcache, models
|
||
|
||
ACTIVITY_BEGIN = "begin"
|
||
ACTIVITY_MANUAL = "manual"
|
||
ACTIVITY_CHOICE = "choice"
|
||
ACTIVITY_PARALLEL = "parallel"
|
||
ACTIVITY_MERGE = "merge"
|
||
ACTIVITY_SPLIT = "split"
|
||
ACTIVITY_SCRIPT = "script"
|
||
ACTIVITY_INVOKE = "invoke"
|
||
ACTIVITY_EMBED = "embed"
|
||
ACTIVITY_DELAY = "delay"
|
||
ACTIVITY_END = "end"
|
||
ACTIVITY_CANCEL = "cancel"
|
||
|
||
MANUAL_MODES = {"any", "all", "join", "serial"}
|
||
_FORM_PERMS = {"hidden", "readonly", "editable", "required"}
|
||
|
||
ACTIVITY_TYPES = {
|
||
ACTIVITY_BEGIN,
|
||
ACTIVITY_MANUAL,
|
||
ACTIVITY_CHOICE,
|
||
ACTIVITY_PARALLEL,
|
||
ACTIVITY_MERGE,
|
||
ACTIVITY_SPLIT,
|
||
ACTIVITY_SCRIPT,
|
||
ACTIVITY_INVOKE,
|
||
ACTIVITY_EMBED,
|
||
ACTIVITY_DELAY,
|
||
ACTIVITY_END,
|
||
ACTIVITY_CANCEL,
|
||
}
|
||
|
||
|
||
@dataclass
|
||
class ActivityNode:
|
||
id: str
|
||
type: str
|
||
name: str
|
||
alias: str = ""
|
||
description: str = ""
|
||
form: str = ""
|
||
config: dict = field(default_factory=dict)
|
||
x: float = 0.0
|
||
y: float = 0.0
|
||
order_number: int = 0
|
||
|
||
@property
|
||
def manual_mode(self) -> str:
|
||
return str(self.config.get("mode") or "any")
|
||
|
||
@property
|
||
def split_mode(self) -> str:
|
||
return str(self.config.get("mode") or "serial")
|
||
|
||
|
||
@dataclass
|
||
class RouteNode:
|
||
id: str
|
||
name: str
|
||
alias: str
|
||
from_activity: str
|
||
to_activity: str
|
||
decision: str = ""
|
||
expression: str = ""
|
||
order_number: int = 0
|
||
|
||
|
||
#: 出口路由里「往回走」的那两种语义:设计器上「退回 / goBack」「拒绝 / reject」
|
||
#: 两个词(见 ``RouteInspector`` 的 decision 下拉)。这两条线画的是把单子打回前面,
|
||
#: 不是「这一步办完了的下一站」。**凡是算「前面还有哪些环节 / 后面还会走到哪」
|
||
#: 的图遍历都必须绕开它们**:那种边把下游连回上游,照它走下去,一张图上只要有
|
||
#: 一条驳回线,整条下游就都成了上游的"上游",退回候选于是算出下一步来。
|
||
BACK_DECISIONS = frozenset({"goBack", "reject"})
|
||
|
||
|
||
def decision_of(definition: "ProcessDefinition", route: RouteNode) -> str:
|
||
"""这条出口的决定语义:环节上的 ``routeDecisions`` 覆盖优先,其次路由自己的
|
||
``decision``——与 ``engine.execute_task`` 当场判退回用的是同一份配置。"""
|
||
origin = definition.activity(route.from_activity)
|
||
overrides = dict((origin.config or {}).get("routeDecisions", {}) or {}) if origin is not None else {}
|
||
return str(overrides.get(route.name) or route.decision or "")
|
||
|
||
|
||
def is_back_route(definition: "ProcessDefinition", route: RouteNode) -> bool:
|
||
"""这条出口是不是回头线。
|
||
|
||
两种算法叠着用:
|
||
|
||
1. 设计者说清楚的——``decision``(或环节上的 ``routeDecisions`` 覆盖)是退回 / 拒绝;
|
||
2. 设计者没说清楚的——把标了语义的线摘掉之后,深度优先走一遍还绕回自己
|
||
(目标还在当前路径上)的那条边。费用报销那条 ``reject`` 属于第 1 种;
|
||
图纸上把"退回修改"画回前面的环节、路由动作留空的,属于第 2 种,
|
||
运行时同样不能当成往前走完的一段(发布校验也会点名它,见 ``_check_back_edges``)。
|
||
"""
|
||
return _marked_back_route(definition, route) or route.id in feedback_route_ids(definition)
|
||
|
||
|
||
#: 闭环边的进程内缓存:键同 ``engine.pair_gateways``(对象 id + 路由条数),值里再留住
|
||
#: 定义对象本身——留住引用,那个 id 才不会被回收后给另一份图纸复用而撞上旧答案。
|
||
_FEEDBACK_CACHE: dict[tuple[int, int], tuple["ProcessDefinition", frozenset[str]]] = {}
|
||
|
||
|
||
def _marked_back_route(definition: "ProcessDefinition", route: RouteNode) -> bool:
|
||
return decision_of(definition, route) in BACK_DECISIONS
|
||
|
||
|
||
def feedback_route_ids(definition: "ProcessDefinition") -> frozenset[str]:
|
||
"""图上那些"绕回自己"的边的 id(没标语义的回头线)。
|
||
|
||
从开始环节起深度优先,指回还在当前路径上的那个节点的那条边就是它;一个环里
|
||
只挑那一条真正回头的边,环上其余几条照常算往前走。读不出完整图(例如只给了
|
||
``activity`` / ``routes_from`` 的调用方)就当没有这种边,退回按第 1 种口径判。
|
||
"""
|
||
routes = getattr(definition, "routes", None)
|
||
if routes is None:
|
||
return frozenset()
|
||
key = (id(definition), len(routes))
|
||
hit = _FEEDBACK_CACHE.get(key)
|
||
if hit is not None and hit[0] is definition:
|
||
return hit[1]
|
||
forward: dict[str, list[RouteNode]] = {}
|
||
for node_id in definition.activities:
|
||
forward[node_id] = [r for r in definition.routes_from(node_id) if not _marked_back_route(definition, r)]
|
||
found: set[str] = set()
|
||
state: dict[str, int] = {}
|
||
begin = definition.begin.id if definition.begin is not None else ""
|
||
# 开始环节先走:环上"谁回头"要看主流程的方向,从发起人出发才会把那条逆着画的边挑出来
|
||
order = ([begin] if begin in forward else []) + sorted(
|
||
(node_id for node_id in forward if node_id != begin),
|
||
key=lambda node_id: (definition.activities[node_id].order_number, node_id),
|
||
)
|
||
for start in order:
|
||
if state.get(start):
|
||
continue
|
||
state[start] = 1
|
||
path: list[list] = [[start, 0]]
|
||
while path:
|
||
frame = path[-1]
|
||
rows = forward.get(frame[0], [])
|
||
if frame[1] >= len(rows):
|
||
state[frame[0]] = 2
|
||
path.pop()
|
||
continue
|
||
route = rows[frame[1]]
|
||
frame[1] += 1
|
||
target = route.to_activity
|
||
if state.get(target) == 1:
|
||
found.add(route.id)
|
||
elif not state.get(target) and target in forward:
|
||
state[target] = 1
|
||
path.append([target, 0])
|
||
if len(_FEEDBACK_CACHE) > 256:
|
||
_FEEDBACK_CACHE.clear()
|
||
_FEEDBACK_CACHE[key] = (definition, frozenset(found))
|
||
return _FEEDBACK_CACHE[key][1]
|
||
|
||
|
||
def forward_routes(definition: "ProcessDefinition", activity_id: str) -> list[RouteNode]:
|
||
"""某一环往外走的出口里,那些"往前走完"的(回头线不参与前瞻与预测,
|
||
包括没标出来但绕回自己的那条,见 :func:`is_back_route`)。
|
||
|
||
前瞻(:mod:`lookahead`)与试跑(:mod:`service.simulator`)都拿它当"后面还会走到哪"
|
||
的口径:把它们当成正常出口,几乎所有配了驳回的流程都再也免不掉重复签字、
|
||
预测里也多一条没人会走的路。
|
||
"""
|
||
return [route for route in definition.routes_from(activity_id) if not is_back_route(definition, route)]
|
||
|
||
|
||
def upstream_ids(definition: "ProcessDefinition", activity_id: str) -> set[str]:
|
||
"""正常路径上走在某一环前面的那些环节(反向走图,绕开回头线)。
|
||
|
||
退回的候选靠它筛。回头线不绕开的话,一张图上只要有一条驳回线,被它连回来的
|
||
那个环节后面的整条下游都会算成"上游",退回于是能退到下一步去。
|
||
"""
|
||
out: set[str] = set()
|
||
frontier = [activity_id]
|
||
while frontier:
|
||
for route in definition.routes_to(frontier.pop()):
|
||
if is_back_route(definition, route):
|
||
continue
|
||
src = route.from_activity
|
||
if src and src not in out:
|
||
out.add(src)
|
||
frontier.append(src)
|
||
out.discard(activity_id)
|
||
return out
|
||
|
||
|
||
def downstream_ids(definition: "ProcessDefinition", activity_id: str) -> set[str]:
|
||
"""从某一环往前走能到的那些环节(绕开回头线)。
|
||
|
||
撤回已办靠它判断"我这一步已经带出去多远",该收回来的是我带出去的那一段;
|
||
回头线尽头的那些环节不是(那是要退回去重走的地方),照它走下去会连发起人
|
||
手上那条补正待办一起收掉。
|
||
"""
|
||
out: set[str] = set()
|
||
frontier = [activity_id]
|
||
while frontier:
|
||
for route in forward_routes(definition, frontier.pop()):
|
||
nxt = route.to_activity
|
||
if nxt and nxt not in out:
|
||
out.add(nxt)
|
||
frontier.append(nxt)
|
||
out.discard(activity_id)
|
||
return out
|
||
|
||
|
||
@dataclass
|
||
class ProcessDefinition:
|
||
process_id: str
|
||
name: str
|
||
alias: str = ""
|
||
category: str = ""
|
||
category_name: str = ""
|
||
latest_form: str = ""
|
||
version: int = 1
|
||
activities: dict[str, ActivityNode] = field(default_factory=dict)
|
||
routes: list[RouteNode] = field(default_factory=list)
|
||
outbound: dict[str, list[RouteNode]] = field(default_factory=dict)
|
||
inbound: dict[str, list[RouteNode]] = field(default_factory=dict)
|
||
begin: ActivityNode | None = None
|
||
#: 流程级审批规则默认值(``skipStarter`` / ``dedup`` / ``dedupAhead``),
|
||
#: 见 models.Process.approval_config。
|
||
approval: dict = field(default_factory=dict)
|
||
#: 流程标题生成规则,见 models.Process.title_config 与 service/titles.py。
|
||
title: dict = field(default_factory=dict)
|
||
#: 编号生成时机,见 models.Process.serial_config 与 service/numbering.py 的 timing 一节。
|
||
#: 名字不带 ``_config`` 是沿用 ``title`` / ``approval`` 的写法;读它请走
|
||
#: ``numbering.timing_of(definition)``,别直接信里面的键。
|
||
serial: dict = field(default_factory=dict)
|
||
#: 流程级外部审批默认档,见 models.Process.open_approve 与
|
||
#: service/node_approve.effective_config。详情页命中设计缓存时手上没有流程行,
|
||
#: 这一份是它唯一的来源,所以必须跟 ``approval`` / ``title`` 一起进缓存。
|
||
open_approve: dict = field(default_factory=dict)
|
||
#: 这一份是不是**冻结定义**(单据发起那一刻的 :class:`models.ProcessSnapshot`)。
|
||
#: ``False`` = 现读的当前设计,行为与"在途单冻结设计"这套机制之前一字不差。
|
||
pinned: bool = False
|
||
#: 冻结定义才有:``form_id -> 那一刻的 oa_form 行``。表单和图是同一种东西——
|
||
#: 改一笔就会改变一张已经在走的单子该填什么,所以一起冻。见 :func:`form_node`。
|
||
forms: dict[str, dict] = field(default_factory=dict)
|
||
|
||
# -- lookup helpers ---------------------------------------------------
|
||
def activity(self, activity_id: str) -> ActivityNode | None:
|
||
return self.activities.get(activity_id)
|
||
|
||
def activity_by_name(self, name: str) -> ActivityNode | None:
|
||
for node in self.activities.values():
|
||
if node.name == name or node.alias == name or node.id == name:
|
||
return node
|
||
return None
|
||
|
||
def routes_from(self, activity_id: str) -> list[RouteNode]:
|
||
# 带上 id 收尾:order_number 撞车(老数据里好几条都是 0)时,
|
||
# 没有次级键的话顺序取决于数据库回行的先后,同名路由「谁先命中」就会漂。
|
||
return sorted(self.outbound.get(activity_id, []), key=lambda r: (r.order_number, r.name, r.id))
|
||
|
||
def routes_to(self, activity_id: str) -> list[RouteNode]:
|
||
return self.inbound.get(activity_id, [])
|
||
|
||
def route(self, route_id: str) -> RouteNode | None:
|
||
for node in self.routes:
|
||
if node.id == route_id or node.name == route_id or node.alias == route_id:
|
||
return node
|
||
return None
|
||
|
||
def find_routes(self, activity_id: str, route_name: str) -> list[RouteNode]:
|
||
"""本环节上叫得出这个名字的全部出口,顺序同 ``routes_from``。
|
||
|
||
同名路由是允许的:它们在待办界面上就是同一个按钮,到底走哪一条由路由
|
||
自己写的条件决定(挑法见 ``engine._route_by_condition``)。所以按名字找
|
||
路由要回全部候选让调用方去挑,而不是悄悄取第一条。
|
||
"""
|
||
if not route_name:
|
||
return []
|
||
return [
|
||
item
|
||
for item in self.routes_from(activity_id)
|
||
if route_name in (item.id, item.name, item.alias, item.decision)
|
||
]
|
||
|
||
def find_route(self, activity_id: str, route_name: str) -> RouteNode | None:
|
||
rows = self.find_routes(activity_id, route_name)
|
||
return rows[0] if rows else None
|
||
|
||
@property
|
||
def manual_activities(self) -> list[ActivityNode]:
|
||
return [a for a in self.activities.values() if a.type == ACTIVITY_MANUAL]
|
||
|
||
def form_ids(self) -> list[str]:
|
||
ids = [self.latest_form]
|
||
ids.extend(a.form for a in self.activities.values() if a.form)
|
||
return [i for i in ids if i]
|
||
|
||
def form_source(self, form_id: str) -> dict | None:
|
||
"""这一张表单**在本单眼里**的内容;``None`` = 该回库读当前表单。
|
||
|
||
只有冻结定义、且快照里确实存了这张表单时才给答案。快照里没有(发起之后
|
||
新绑的表单、嵌入引用的别家表单)就照旧现读,宁可读到新的,也不要读成一份空的。
|
||
"""
|
||
if not self.pinned or not form_id:
|
||
return None
|
||
row = self.forms.get(str(form_id))
|
||
return row if isinstance(row, dict) else None
|
||
|
||
def form_fields_source(self, form_id: str) -> list[dict] | None:
|
||
"""同 :func:`form_source`,但直接要字段清单(引擎与详情页最常用的形状)。"""
|
||
content = (self.form_source(form_id) or {}).get("content")
|
||
if not isinstance(content, dict):
|
||
return None
|
||
fields = content.get("fields")
|
||
return [item for item in fields if isinstance(item, dict)] if isinstance(fields, list) else []
|
||
|
||
|
||
#: 缓存里要带上哪些列:与 :func:`build` 读的列一字不差,缺一列就当作没命中回库重查
|
||
_PROCESS_FIELDS = ("id", "name", "alias", "category", "category_name", "latest_form",
|
||
"version", "approval_config", "title_config", "serial_config")
|
||
#: 后加的列:写的时候一起写,读的时候**缺了不算形状不对**。设计快照是不可变的、也没有
|
||
#: 重拍这一说(钉住的那个 id 就写在单据上),拿必需列去卡它,等于让这一列之前拍的所有
|
||
#: 快照整体作废、那些在途单从此跟着当前设计走——"改图不影响在途单"这条就默默没了。
|
||
#: 缺这一列按空默认档处理:环节上那份 ``openApprove`` 本来就在 ``config`` 里,冻得住。
|
||
_PROCESS_OPTIONAL_FIELDS = ("open_approve",)
|
||
_ACTIVITY_FIELDS = ("id", "type", "name", "alias", "description", "form", "config",
|
||
"x", "y", "order_number")
|
||
_ROUTE_FIELDS = ("id", "name", "alias", "from_activity", "to_activity", "decision",
|
||
"expression", "order_number")
|
||
|
||
|
||
class _CachedRow:
|
||
"""缓存里那一份列值 -> 一条"只看列"的行。
|
||
|
||
``build`` 只读列、不碰关系,所以设计可以从 Redis 里还原出来照原样拼装,
|
||
不必为缓存另写一套构造口径(那才会漂移)。缺列就当没命中,回库重查。
|
||
"""
|
||
|
||
__slots__ = ("__dict__",)
|
||
|
||
def __init__(self, values: dict) -> None:
|
||
self.__dict__.update(values)
|
||
|
||
|
||
def _rows(values: list, fields: tuple[str, ...],
|
||
optional: tuple[str, ...] = ()) -> list[_CachedRow]:
|
||
"""一批 dict -> 一批行;必需列对不上(旧版本存的、被人为改过的)回 ``[]``。
|
||
|
||
``optional`` 里那几列缺了不作废,按 ``None`` 补上——见 :data:`_PROCESS_OPTIONAL_FIELDS`。
|
||
"""
|
||
rows = []
|
||
for item in values or []:
|
||
if not isinstance(item, dict) or any(field not in item for field in fields):
|
||
return []
|
||
body = {field: item[field] for field in fields}
|
||
for field in optional:
|
||
body[field] = item.get(field)
|
||
rows.append(_CachedRow(body))
|
||
return rows
|
||
|
||
|
||
def _from_payload(process_id: str, payload: dict) -> ProcessDefinition | None:
|
||
"""命中:把缓存里那份原始行交回 :func:`build`。拼不出来回 ``None``(回库重查)。"""
|
||
process = _rows([payload.get("process")], _PROCESS_FIELDS, _PROCESS_OPTIONAL_FIELDS)
|
||
if not process or process[0].id != process_id:
|
||
return None
|
||
activities = _rows(payload.get("activities"), _ACTIVITY_FIELDS)
|
||
routes = _rows(payload.get("routes"), _ROUTE_FIELDS)
|
||
if not activities: # 一个环节都没有的设计不是合法设计,回库重查
|
||
return None
|
||
return build(process[0], activities, routes)
|
||
|
||
|
||
def _to_payload(process, activities, routes) -> dict:
|
||
"""原始行 -> 能进 JSON 的那几列(列名与 :func:`build` 读的口径一致)。"""
|
||
return {
|
||
"process": {field: getattr(process, field, None)
|
||
for field in _PROCESS_FIELDS + _PROCESS_OPTIONAL_FIELDS},
|
||
"activities": [{field: getattr(row, field, None) for field in _ACTIVITY_FIELDS}
|
||
for row in activities],
|
||
"routes": [{field: getattr(row, field, None) for field in _ROUTE_FIELDS}
|
||
for row in routes],
|
||
}
|
||
|
||
|
||
def cached_design(process_id: str) -> ProcessDefinition | None:
|
||
"""只问共享缓存:命中给出定义(一条 SQL 都不问),没命中回 ``None``。
|
||
|
||
给"自己分头并发查这三张表"的调用方用的(``GET /job/{job}`` 那类):命中就不必再摊三块
|
||
出去问,没命中照原样摊开并发,行为与改动前一字不差。
|
||
"""
|
||
return _from_payload(process_id, designcache.get(process_id) or {})
|
||
|
||
|
||
def design_cache_enabled() -> bool:
|
||
"""设计共享缓存这一层这次到底会不会命中(没配 Redis、或 ``OA_DESIGN_CACHE=off`` 就是不会)。
|
||
|
||
给"先问缓存、没命中再摊开问库"的调用方安排并发用:这一层不参与时那一读**必然回空**,
|
||
就不该让它占一个并发位、更不该把依赖它答复的那几块拖到第二轮去。
|
||
"""
|
||
return designcache.enabled()
|
||
|
||
|
||
def cache_design(process, activities, routes) -> None:
|
||
"""调用方自己把这三批行问回来了,顺手存一份:下一趟就不用再问那三趟。
|
||
|
||
刚写过设计的那一小段时间里存不进去(:func:`app.designcache.put` 里那道标记),
|
||
未提交的设计于是不会进缓存。
|
||
"""
|
||
if process is None:
|
||
return
|
||
designcache.put(getattr(process, "id", ""), _to_payload(process, activities, routes))
|
||
|
||
|
||
def load(db: Session, process_id: str) -> ProcessDefinition:
|
||
"""按流程主键把定义整条读出来:流程本身 -> 环节 -> 路由,串着问三趟。
|
||
|
||
这三条查询都只认 ``process_id``,彼此没有先后依赖,唯一的真依赖是表单——表单 id
|
||
写在环节行里,要它得先有环节。要并发跑的调用方(``GET /job/{job}``)自己分头查
|
||
这三张表,再交给 :func:`build` 拼;这里保持"一条链问完",单线程时它最省往返。
|
||
|
||
这三张表是发布后不再动的配置,于是整条链先问一趟 :mod:`app.designcache`:
|
||
审批、单据详情、审批人预览每次都重问一遍同样的三趟,纯排三次队(本部署一趟 17-21ms)。
|
||
**没配 Redis 或共享缓存被关掉时这一层形同不存在**——载荷永远是空 dict,照旧回库走
|
||
那三趟,与改动前一字不差。
|
||
|
||
这里刻意不再加"同一次请求里共用一份载荷"的 Session 级缓存:2026-10 数过一遍,
|
||
发起、审批、``GET /job/{job}``、``GET /task/{task}``、待办列表,每条路径上一次请求
|
||
最多 ``load`` 一遍同一个流程(``/task/{task}`` 是 1 次 load + 1 次旁路命中),列表里
|
||
真会摊开多流程的那处 :func:`app.api.runtime` 早有自己的 ``definitions`` 去重。省不到
|
||
东西的缓存只剩隐患,所以不留。
|
||
"""
|
||
definition = _from_payload(process_id, designcache.get(process_id) or {})
|
||
if definition is not None:
|
||
return definition
|
||
process = db.get(models.Process, process_id)
|
||
if process is None:
|
||
raise ValueError(f"流程不存在: {process_id}")
|
||
activities = db.execute(
|
||
select(models.Activity).where(models.Activity.process == process.id)
|
||
).scalars().all()
|
||
routes = db.execute(
|
||
select(models.Route)
|
||
.where(models.Route.process == process.id)
|
||
.order_by(models.Route.order_number, models.Route.name)
|
||
).scalars().all()
|
||
definition = build(process, activities, routes)
|
||
designcache.put(process_id, _to_payload(process, activities, routes))
|
||
return definition
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 在途单据脚下那块地:发起那一刻把设计冻起来,这张单之后只认这一份
|
||
#
|
||
# 为什么非要冻:设计器是**自动保存**的(``composables/useDesignAutosave.ts``,停手 1.5s
|
||
# 就落库),落的就是 ``oa_activity`` / ``oa_route`` 这三张线上表,而引擎每一步都现读它们。
|
||
# 于是"有人在改流程"和"有人在办一张走到一半的单"这两件事一旦同时发生,改的人当场就
|
||
# 换了办的人脚下的图:环节改名、出口少了一条、审批规则换档、表单多了一个必填……
|
||
# ``oa_process_version`` 那张表救不了这个——它是发布历史,给人看给人回滚,运行时不参与。
|
||
#
|
||
# 冻结只发生在**发起**这一刻,所以:新单照旧跟最新设计走(改完立刻生效这条产品口径
|
||
# 不动),已经在走的单停在出发时那一版。老单(这套机制之前发起的)身上没有快照引用,
|
||
# 照旧现读,升级不迁一行数据。
|
||
# ---------------------------------------------------------------------------
|
||
|
||
#: 快照 JSON 里表单那一段的键。
|
||
FORMS_KEY = "forms"
|
||
|
||
#: 快照要存下来的表单列:与 :func:`app.serializers.form` 读的那几列一字不差,
|
||
#: 详情页拿到就能直接交给 serializers 出参,不必为冻结另编一套形状。
|
||
_FORM_FIELDS = ("id", "name", "alias", "description", "process", "version",
|
||
"content", "editable", "order_number", "update_time")
|
||
|
||
#: 进程内那份定义缓存:快照行写完就不再改,所以它**不需要失效**,只需要限容量。
|
||
#: 这一层让"每张单读自己那一版"不至于变成每次审批多排一趟队。
|
||
_SNAPSHOT_CACHE: "OrderedDict[str, ProcessDefinition]" = OrderedDict()
|
||
_SNAPSHOT_CACHE_MAX = 512
|
||
|
||
|
||
def _form_rows(db: Session, form_ids: Iterable[str]) -> dict[str, dict]:
|
||
"""按 id 取那几张表单的**冻结用**列值(JSON 友好:时间落成字符串)。"""
|
||
out: dict[str, dict] = {}
|
||
for form_id in dict.fromkeys(str(item or "").strip() for item in form_ids):
|
||
if not form_id:
|
||
continue
|
||
row = db.get(models.FormElement, form_id)
|
||
if row is None:
|
||
continue
|
||
values = {field: getattr(row, field, None) for field in _FORM_FIELDS}
|
||
update_time = values.get("update_time")
|
||
values["update_time"] = update_time.isoformat(sep=" ") if isinstance(update_time, datetime) else update_time
|
||
out[form_id] = values
|
||
return out
|
||
|
||
|
||
def design_payload(db: Session, process_id: str) -> dict:
|
||
"""当前设计(流程 / 环节 / 路由)+ 这几张表单的内容,一次拍成能进 JSON 的一份。
|
||
|
||
图那三份走 :func:`_to_payload`,与 :mod:`app.designcache` 存进 Redis 的形状一字不差;
|
||
多出来的一段是 ``forms``(见 :func:`_form_rows`)。路由的排序与 :func:`load` 用同一套
|
||
``ORDER BY``——同名路由谁先命中看的就是这个先后,两边不一致就会漂。
|
||
"""
|
||
process = db.get(models.Process, process_id)
|
||
if process is None:
|
||
raise ValueError(f"流程不存在: {process_id}")
|
||
activities = db.execute(
|
||
select(models.Activity).where(models.Activity.process == process.id)
|
||
).scalars().all()
|
||
routes = db.execute(
|
||
select(models.Route)
|
||
.where(models.Route.process == process.id)
|
||
.order_by(models.Route.order_number, models.Route.name)
|
||
).scalars().all()
|
||
payload = _to_payload(process, activities, routes)
|
||
definition = build(process, activities, routes)
|
||
payload[FORMS_KEY] = _form_rows(db, definition.form_ids())
|
||
return payload
|
||
|
||
|
||
def _fingerprint_body(payload: dict) -> dict:
|
||
"""算指纹前把"不算设计内容"的那几列剔掉。
|
||
|
||
表单的 ``update_time`` 是人在设计器里停一下手就会变一次的列:把它算进去,一次
|
||
什么都没改的表单保存就会让后面的新单各存一行快照,内容寻址当场失效。
|
||
"""
|
||
body = {key: value for key, value in (payload or {}).items() if key != FORMS_KEY}
|
||
forms = (payload or {}).get(FORMS_KEY)
|
||
if isinstance(forms, dict):
|
||
body[FORMS_KEY] = {
|
||
str(key): {name: value for name, value in (item or {}).items() if name != "update_time"}
|
||
for key, item in forms.items()
|
||
if isinstance(item, dict)
|
||
}
|
||
return body
|
||
|
||
|
||
def fingerprint(payload: dict) -> str:
|
||
"""设计内容的指纹:同指纹必同内容,用来让同一份设计全库只存一行。"""
|
||
body = json.dumps(_fingerprint_body(payload), ensure_ascii=False, sort_keys=True, default=str)
|
||
return hashlib.sha256(body.encode("utf-8")).hexdigest()
|
||
|
||
|
||
def pin_enabled() -> bool:
|
||
"""发起时冻不冻快照:系统设置「流程设计」那一栏的总闸,默认开。"""
|
||
return bool(dbconfig.value("design_pin_enabled", True))
|
||
|
||
|
||
def pin(db: Session, process_id: str) -> str:
|
||
"""给**当前**设计拍一张不可变的照,返回 ``oa_process_snapshot`` 的主键。
|
||
|
||
先按指纹认领现成的那一行,没有才插,所以一百张同时发起的单共用一份设计而不是
|
||
一百份。两个进程同时拍同一张图可能各插一行,那也无妨:内容一模一样,谁被认领都对。
|
||
|
||
总闸(:func:`pin_enabled`)关掉时回空串——空串就是"这张单没冻快照"的既有口径,
|
||
:func:`for_work` 认它,照旧现读当前设计,调用方不必再判一遍开关。
|
||
"""
|
||
if not pin_enabled():
|
||
return ""
|
||
payload = design_payload(db, process_id)
|
||
mark = fingerprint(payload)
|
||
existing = db.execute(
|
||
select(models.ProcessSnapshot.id)
|
||
.where(models.ProcessSnapshot.process == process_id, models.ProcessSnapshot.fingerprint == mark)
|
||
.limit(1)
|
||
).scalar_one_or_none()
|
||
if existing:
|
||
return str(existing)
|
||
row = models.ProcessSnapshot(
|
||
process=process_id,
|
||
version=int((payload.get("process") or {}).get("version") or 1),
|
||
fingerprint=mark,
|
||
definition=payload,
|
||
)
|
||
db.add(row)
|
||
db.flush()
|
||
return row.id
|
||
|
||
|
||
def _parse_time(value: object) -> datetime | None:
|
||
"""快照里那个 ``update_time`` 是字符串,还原成 serializers 要的样子。"""
|
||
if isinstance(value, datetime):
|
||
return value
|
||
try:
|
||
return datetime.fromisoformat(str(value)) if value else None
|
||
except ValueError:
|
||
return None
|
||
|
||
|
||
def form_node(definition: ProcessDefinition, form_id: str):
|
||
"""冻结定义里那一张表单 -> 一条"只看列"的行,交给 :func:`app.serializers.form` 出参。
|
||
|
||
没冻过 / 快照里没这张表单回 ``None``,调用方回库读当前那张。
|
||
"""
|
||
values = definition.form_source(form_id)
|
||
if values is None:
|
||
return None
|
||
row = _CachedRow({field: values.get(field) for field in _FORM_FIELDS})
|
||
row.id = str(values.get("id") or form_id)
|
||
row.name = str(values.get("name") or "")
|
||
row.alias = str(values.get("alias") or "")
|
||
row.description = str(values.get("description") or "")
|
||
row.process = str(values.get("process") or "")
|
||
row.version = int(values.get("version") or 0)
|
||
row.content = dict(values.get("content") or {})
|
||
row.editable = str(values.get("editable") or "edit")
|
||
row.order_number = int(values.get("order_number") or 0)
|
||
row.update_time = _parse_time(values.get("update_time"))
|
||
return row
|
||
|
||
|
||
def from_snapshot(db: Session, process_id: str, snapshot_id: str) -> ProcessDefinition | None:
|
||
"""按快照主键重建定义;读不到、形状不对、不属于这条流程,一律回 ``None``。
|
||
|
||
回 ``None`` 时调用方是**回退去现读当前设计**,不是报错:快照机制之前发起的老单、
|
||
被运维清掉的快照行,都得让单子照样办得动。
|
||
"""
|
||
if not snapshot_id:
|
||
return None
|
||
hit = _SNAPSHOT_CACHE.get(snapshot_id)
|
||
if hit is not None:
|
||
_SNAPSHOT_CACHE.move_to_end(snapshot_id)
|
||
return hit if hit.process_id == process_id else None
|
||
row = db.get(models.ProcessSnapshot, snapshot_id)
|
||
if row is None or row.process != process_id:
|
||
return None
|
||
payload = row.definition if isinstance(row.definition, dict) else {}
|
||
# 拼装口径全站只有 _from_payload 这一处:冻结定义与现读定义不可能长出两种行为。
|
||
definition = _from_payload(process_id, payload)
|
||
if definition is None:
|
||
return None
|
||
definition.pinned = True
|
||
definition.version = int(row.version or definition.version)
|
||
forms = payload.get(FORMS_KEY)
|
||
definition.forms = {
|
||
str(key): dict(value or {})
|
||
for key, value in forms.items()
|
||
if isinstance(value, dict)
|
||
} if isinstance(forms, dict) else {}
|
||
_SNAPSHOT_CACHE[snapshot_id] = definition
|
||
_SNAPSHOT_CACHE.move_to_end(snapshot_id)
|
||
while len(_SNAPSHOT_CACHE) > _SNAPSHOT_CACHE_MAX:
|
||
_SNAPSHOT_CACHE.popitem(last=False)
|
||
return definition
|
||
|
||
|
||
def for_work(db: Session, row: object) -> ProcessDefinition:
|
||
"""**这张单据 / 这条待办**眼里的流程定义。
|
||
|
||
入参是任何带 ``process`` + ``design_snapshot`` 两个属性的行(``oa_work`` / ``oa_task``)。
|
||
冻过结就读自己那一版;没冻过(老单)或快照行没了就现读当前设计——这个回退是故意的,
|
||
宁可让一张孤零零的老单跟着新图走,也不能让它因为查不到快照而连环节都打不开。
|
||
"""
|
||
process_id = str(getattr(row, "process", "") or "")
|
||
snapshot_id = str(getattr(row, "design_snapshot", "") or "")
|
||
if snapshot_id:
|
||
definition = from_snapshot(db, process_id, snapshot_id)
|
||
if definition is not None:
|
||
return definition
|
||
return load(db, process_id)
|
||
|
||
|
||
def forget_snapshots() -> None:
|
||
"""进程内那份冻结定义清空(自检脚本与"改完快照想立刻看见"的运维口用)。"""
|
||
_SNAPSHOT_CACHE.clear()
|
||
|
||
|
||
def build(
|
||
process: models.Process,
|
||
activities: Iterable[models.Activity],
|
||
routes: Iterable[models.Route],
|
||
) -> ProcessDefinition:
|
||
"""把已经查出来的流程 / 环节 / 路由拼成 :class:`ProcessDefinition`。
|
||
|
||
只读列、不碰关系,所以行来自哪个 Session、有没有 ``expunge`` 过都不碍事。
|
||
顺序按调用方给的收(路由的先后决定 ``routes`` 和出入站索引的顺序),自己查的话
|
||
要与 :func:`load` 用同一套 ``ORDER BY``,否则同一张单的环节顺序会跟着变。
|
||
"""
|
||
definition = ProcessDefinition(
|
||
process_id=process.id,
|
||
name=process.name,
|
||
alias=process.alias or process.name,
|
||
category=process.category,
|
||
category_name=process.category_name,
|
||
latest_form=process.latest_form,
|
||
version=process.version,
|
||
approval=dict(getattr(process, "approval_config", None) or {}),
|
||
title=dict(getattr(process, "title_config", None) or {}),
|
||
serial=dict(getattr(process, "serial_config", None) or {}),
|
||
open_approve=dict(getattr(process, "open_approve", None) or {}),
|
||
)
|
||
for row in activities:
|
||
definition.activities[row.id] = ActivityNode(
|
||
id=row.id,
|
||
type=(row.type or "manual").lower(),
|
||
name=row.name,
|
||
alias=row.alias or row.name,
|
||
description=row.description or "",
|
||
form=row.form or "",
|
||
config=dict(row.config or {}),
|
||
x=row.x,
|
||
y=row.y,
|
||
order_number=row.order_number,
|
||
)
|
||
for row in routes:
|
||
node = RouteNode(
|
||
id=row.id,
|
||
name=row.name,
|
||
alias=row.alias or row.name,
|
||
from_activity=row.from_activity,
|
||
to_activity=row.to_activity,
|
||
decision=row.decision or "",
|
||
expression=row.expression or "",
|
||
order_number=row.order_number,
|
||
)
|
||
definition.routes.append(node)
|
||
definition.outbound.setdefault(node.from_activity, []).append(node)
|
||
definition.inbound.setdefault(node.to_activity, []).append(node)
|
||
for node in definition.activities.values():
|
||
if node.type == ACTIVITY_BEGIN:
|
||
definition.begin = node
|
||
break
|
||
if definition.begin is None and definition.activities:
|
||
definition.begin = next(iter(definition.activities.values()))
|
||
return definition
|
||
|
||
|
||
def validate(definition: ProcessDefinition) -> list[str]:
|
||
"""Designer side validation, returns a list of human readable problems."""
|
||
problems: list[str] = []
|
||
begins = [a for a in definition.activities.values() if a.type == ACTIVITY_BEGIN]
|
||
ends = [a for a in definition.activities.values() if a.type == ACTIVITY_END]
|
||
if not begins:
|
||
problems.append("缺少开始环节")
|
||
if len(begins) > 1:
|
||
problems.append("只能有一个开始环节")
|
||
if not ends:
|
||
problems.append("缺少结束环节")
|
||
for node in definition.activities.values():
|
||
if node.type not in ACTIVITY_TYPES:
|
||
problems.append(f"环节 {node.name} 类型未知: {node.type}")
|
||
if node.type == ACTIVITY_MANUAL and not definition.routes_from(node.id):
|
||
problems.append(f"人工环节 {node.name} 没有出口路由")
|
||
if node.type in {ACTIVITY_END, ACTIVITY_CANCEL} and definition.routes_from(node.id):
|
||
problems.append(f"{node.name} 是结束类环节,不能有出口路由")
|
||
same_name: dict[tuple[str, str], list[RouteNode]] = {}
|
||
for route in definition.routes:
|
||
if route.from_activity not in definition.activities:
|
||
problems.append(f"路由 {route.name} 的起点不存在")
|
||
continue
|
||
if route.to_activity not in definition.activities:
|
||
problems.append(f"路由 {route.name} 的终点不存在")
|
||
continue
|
||
same_name.setdefault((route.from_activity, route.name), []).append(route)
|
||
problems.extend(_check_route_names(definition, same_name))
|
||
for node in definition.activities.values():
|
||
if node.type == ACTIVITY_CHOICE:
|
||
routes = definition.routes_from(node.id)
|
||
if len(routes) < 2:
|
||
problems.append(f"分支环节 {node.name} 至少需要两条路由")
|
||
if not any(not (r.expression or "").strip() for r in routes):
|
||
problems.append(f"分支环节 {node.name} 需要一条无条件路由作为默认分支")
|
||
if node.type == ACTIVITY_PARALLEL and len(definition.routes_from(node.id)) < 2:
|
||
problems.append(f"平行环节 {node.name} 至少需要两条路由")
|
||
if node.type == ACTIVITY_MERGE and len(definition.routes_to(node.id)) < 2:
|
||
problems.append(f"汇总环节 {node.name} 至少需要两条入口路由")
|
||
problems.extend(_check_approver_policy(definition))
|
||
problems.extend(_check_approval_defaults(definition))
|
||
problems.extend(_check_approver_targets(definition))
|
||
problems.extend(_check_skip_rules(definition))
|
||
problems.extend(_check_must_rules(definition))
|
||
problems.extend(_check_cc_rules(definition))
|
||
problems.extend(_check_serial_timing(definition))
|
||
problems.extend(_check_reachable(definition))
|
||
problems.extend(_check_back_edges(definition))
|
||
return problems
|
||
|
||
|
||
def _check_route_names(
|
||
definition: ProcessDefinition, same_name: dict[tuple[str, str], list[RouteNode]]
|
||
) -> list[str]:
|
||
"""同名出口是允许的(界面上就是同一个按钮),但有两件事不能含糊。
|
||
|
||
过去一律禁止同名,逼得设计者把每条分支上的按钮都改成不同名字,审批人看到的
|
||
按钮就成了「同意-大额」「同意-常规」这种一看就不像同一个动作的东西。放开之后
|
||
靠两条守住底线:
|
||
|
||
1. 语义要一致——一个按钮不能既是「同意」又是「退回」,否则这张票算哪一票说不清;
|
||
2. 走哪条要分得开——同名里最多留一条不写条件的当默认,其余必须写条件,
|
||
否则运行时面对两条完全一样的候选只能瞎挑。
|
||
|
||
并联和拆分环节是每条出口都走,引擎不在它们之间挑,所以这两条都管不着。
|
||
"""
|
||
problems: list[str] = []
|
||
for (source_id, name), siblings in same_name.items():
|
||
if len(siblings) < 2:
|
||
continue
|
||
source = definition.activities[source_id]
|
||
if source.type in {ACTIVITY_PARALLEL, ACTIVITY_SPLIT}:
|
||
continue
|
||
decisions = {(route.decision or "").strip() for route in siblings}
|
||
if len(decisions) > 1:
|
||
shown = "、".join(sorted(decision or "未设置" for decision in decisions))
|
||
problems.append(
|
||
f"环节 {source.name} 的同名路由「{name}」语义不一致({shown}):"
|
||
"同一个按钮只能是一个意思,请改名字或者改成同一个决定"
|
||
)
|
||
defaults = [route for route in siblings if not (route.expression or "").strip()]
|
||
if len(defaults) > 1:
|
||
problems.append(
|
||
f"环节 {source.name} 有 {len(defaults)} 条同名的路由「{name}」都没写条件,"
|
||
"流转时分不出该走哪条:只留一条不写条件当默认,其余的写上条件"
|
||
)
|
||
return problems
|
||
|
||
|
||
def _check_approver_targets(definition: ProcessDefinition) -> list[str]:
|
||
"""审批人来源:组织层级那几种必须带参数,否则运行时一定解析不出人。"""
|
||
problems: list[str] = []
|
||
for node in definition.activities.values():
|
||
rows = (node.config or {}).get("taskValues")
|
||
if rows in (None, ""):
|
||
continue
|
||
if not isinstance(rows, list):
|
||
problems.append(f"环节 {node.name} 的审批人设置格式不对")
|
||
continue
|
||
problems.extend(approver_row_problems(node.name, rows))
|
||
return problems
|
||
|
||
|
||
def approver_row_problems(node_name: str, rows: object, subject: str = "审批人") -> list[str]:
|
||
"""校验一批「找人」配置行(环节审批人、跳过对象、抄送对象都是这个形状)。
|
||
|
||
``subject`` 只影响报错里那句主语:抄送对象出问题时说成「审批人设置」会把人带偏。
|
||
"""
|
||
from ..service import org # 延迟导入,避免 service 与 engine 相互引用成环
|
||
|
||
problems: list[str] = []
|
||
for item in rows if isinstance(rows, list) else []:
|
||
if not isinstance(item, dict):
|
||
problems.append(f"环节 {node_name} 有{subject}设置格式不对")
|
||
continue
|
||
kind = org.normalize_kind(item.get("type"))
|
||
data = [str(v) for v in (item.get("data") or []) if str(v or "").strip()]
|
||
if kind == "unitManager" and not data:
|
||
problems.append(f"环节 {node_name} 选了「指定部门负责人」但还没选部门")
|
||
elif kind == "creatorLeaderChain":
|
||
depth = next((v for v in data if v.isdigit()), "")
|
||
if depth and not 1 <= int(depth) <= org.MAX_LEADER_CHAIN:
|
||
problems.append(
|
||
f"环节 {node_name} 的连续上级层数要在 1-{org.MAX_LEADER_CHAIN} 级之间"
|
||
)
|
||
elif kind == "form" and not data:
|
||
# 设计器现在从字段清单里挑(见 utils/approverTargets.ts 的 formFieldPathOptions),
|
||
# 空着等于这个环节谁也找不到,别让它悄悄跑到运行时才发现。
|
||
problems.append(f"环节 {node_name} 选了「表单字段」找人但还没挑字段")
|
||
return problems
|
||
|
||
|
||
def _check_skip_rules(definition: ProcessDefinition) -> list[str]:
|
||
"""条件跳过审批人:条件得能编译,「只免其中几个人」还得真挑得出要免谁。
|
||
|
||
没设条件的规则在运行时按不命中处理(引擎那边宁可多批不敢乱免),但那是
|
||
一条永远不生效的配置,设计期就该报出来,而不是等上线后才发现免审没生效。
|
||
"""
|
||
from . import expressions # 与 expressions 同包,放函数里只为和其它检查保持一致
|
||
|
||
problems: list[str] = []
|
||
for node in definition.activities.values():
|
||
if node.type != ACTIVITY_MANUAL:
|
||
continue
|
||
rules = (node.config or {}).get("skipRules")
|
||
if rules in (None, ""):
|
||
continue
|
||
if not isinstance(rules, list):
|
||
problems.append(f"环节 {node.name} 的跳过设置格式不对")
|
||
continue
|
||
for index, rule in enumerate(rules, start=1):
|
||
if not isinstance(rule, dict):
|
||
problems.append(f"环节 {node.name} 有跳过设置格式不对")
|
||
continue
|
||
# 一个环节可以配好几条规则,报错得说清是哪一条,否则只有「规则名」能当门牌
|
||
label = rule_label(node.name, "跳过", index, rule)
|
||
scope = str(rule.get("scope") or "matched")
|
||
if scope not in {"matched", "all"}:
|
||
problems.append(f"{label}的跳过范围不支持:{scope}")
|
||
expression = str(rule.get("expression") or "").strip()
|
||
if not expression:
|
||
problems.append(f"{label}还没设条件")
|
||
continue
|
||
error = expressions.validate_script(expression)
|
||
if error:
|
||
problems.append(f"{label}的条件写错了:{error}")
|
||
if scope == "matched" and not (rule.get("taskValues") or []):
|
||
problems.append(f"{label}选了「只免其中几个人」但还没选免谁")
|
||
problems.extend(approver_row_problems(node.name, rule.get("taskValues")))
|
||
return problems
|
||
|
||
|
||
def rule_label(node_name: str, kind: str, index: int, rule: dict) -> str:
|
||
"""规则报错的门牌:有名字用名字,没名字用第几条(两处规则共用一套说法)。"""
|
||
name = str(rule.get("name") or "").strip()
|
||
head = f"环节 {node_name} 的{kind}规则「{name}」" if name else f"环节 {node_name} 的第 {index} 条{kind}规则"
|
||
return head
|
||
|
||
|
||
def _check_must_rules(definition: ProcessDefinition) -> list[str]:
|
||
"""条件必批:和免审规则一样,条件要能编译,而且必须点得出"谁来批"。"""
|
||
from . import expressions
|
||
|
||
problems: list[str] = []
|
||
for node in definition.activities.values():
|
||
if node.type != ACTIVITY_MANUAL:
|
||
continue
|
||
rules = (node.config or {}).get("mustRules")
|
||
if rules in (None, ""):
|
||
continue
|
||
if not isinstance(rules, list):
|
||
problems.append(f"环节 {node.name} 的必批设置格式不对")
|
||
continue
|
||
for index, rule in enumerate(rules, start=1):
|
||
if not isinstance(rule, dict):
|
||
problems.append(f"环节 {node.name} 有必批设置格式不对")
|
||
continue
|
||
label = rule_label(node.name, "必批", index, rule)
|
||
expression = str(rule.get("expression") or "").strip()
|
||
if not expression:
|
||
problems.append(f"{label}还没设条件")
|
||
continue
|
||
error = expressions.validate_script(expression)
|
||
if error:
|
||
problems.append(f"{label}的条件写错了:{error}")
|
||
if not (rule.get("taskValues") or []):
|
||
problems.append(f"{label}还没选必须审批的人")
|
||
problems.extend(approver_row_problems(node.name, rule.get("taskValues")))
|
||
return problems
|
||
|
||
|
||
def _check_cc_rules(definition: ProcessDefinition) -> list[str]:
|
||
"""抄送规则:时机合法、必须选到对象;设了抄送条件的话条件得能编译,否则等于没配。
|
||
|
||
抄送条件是可选项(留空=无条件照抄),所以只在"写了"的时候校验写法,不要求必填。
|
||
"""
|
||
from . import expressions
|
||
|
||
problems: list[str] = []
|
||
for node in definition.activities.values():
|
||
rules = (node.config or {}).get("ccRules")
|
||
if rules in (None, ""):
|
||
continue
|
||
if not isinstance(rules, list):
|
||
problems.append(f"环节 {node.name} 的抄送设置格式不对")
|
||
continue
|
||
for index, rule in enumerate(rules, start=1):
|
||
if not isinstance(rule, dict):
|
||
problems.append(f"环节 {node.name} 有抄送设置格式不对")
|
||
continue
|
||
# 一个环节可以配好几条抄送,报错得说清是哪一条,否则只有一样的文案能当门牌
|
||
label = rule_label(node.name, "抄送", index, rule)
|
||
when = str(rule.get("when") or "arrive")
|
||
if when not in {"arrive", "complete"}:
|
||
problems.append(f"{label}的抄送时机只能是到达时或办结后")
|
||
targets = rule.get("taskValues") or []
|
||
if not targets and not str(rule.get("taskScript") or "").strip():
|
||
problems.append(f"{label}还没选抄送对象")
|
||
expression = str(rule.get("expression") or "").strip()
|
||
if expression:
|
||
error = expressions.validate_script(expression)
|
||
if error:
|
||
problems.append(f"{label}的抄送条件写错了:{error}")
|
||
problems.extend(approver_row_problems(node.name, rule.get("taskValues"), "抄送对象"))
|
||
return problems
|
||
|
||
|
||
def _check_reachable(definition: ProcessDefinition) -> list[str]:
|
||
if definition.begin is None:
|
||
return []
|
||
seen: set[str] = {definition.begin.id}
|
||
stack = [definition.begin.id]
|
||
while stack:
|
||
current = stack.pop()
|
||
for route in definition.routes_from(current):
|
||
if route.to_activity not in seen:
|
||
seen.add(route.to_activity)
|
||
stack.append(route.to_activity)
|
||
return [
|
||
f"环节 {node.name} 从开始环节不可达"
|
||
for node in definition.activities.values()
|
||
if node.id not in seen
|
||
]
|
||
|
||
|
||
#: 没标语义的那条回头线,在运行时是**一次审批通过**:算一票同意、触发「本环节
|
||
#: 审批通过后」的写回与排号、也不收后面已经派出去的在途待办(见
|
||
#: ``engine.execute_task`` 里 decision 的判定)。
|
||
UNMARKED_BACK_EDGE = (
|
||
"路由「{route}」从「{src}」回到了前面的「{dst}」,但没标路由动作:"
|
||
"点它在引擎里算一次审批通过(算一票同意、触发本环节通过后的写回与排号、"
|
||
"也不收回后面已派的待办)。请把它标成「退回 / goBack」或「拒绝 / reject」"
|
||
)
|
||
|
||
#: 标了退回、线却指着往前走才能到的地方:引擎按退回处理,落点取候选环节或
|
||
#: ``goBackTarget``,画布上这条线的终点运行时根本不会被走到。
|
||
GOBACK_ROUTE_NOT_BACKWARD = (
|
||
"路由「{route}」标了「退回」,但指向的「{dst}」不是「{src}」的上游环节:"
|
||
"点退回时引擎退的是上游环节(或环节上指定的落点),画布这条线到不了那里"
|
||
)
|
||
|
||
|
||
def _check_back_edges(definition: ProcessDefinition) -> list[str]:
|
||
"""回头线要画清楚、也要标语义:这类线是"点退回却走到下一步"那一族问题的源头。
|
||
|
||
两条口径:
|
||
|
||
1. **闭了环却没标语义**:把已经标成退回/拒绝的边摘掉之后,剩下的图里做深度
|
||
优先,指回还在路径上的那个节点的那条边,就是画布上看着像退回、运行时却
|
||
被当成往前走的线。(一个环里只点那一条真正回头的边——先访问到谁就由谁闭环,
|
||
环上其它边是正常往前走的一段。)
|
||
2. **标了退回却指向前面**:退回的执行不看线的终点(落点是候选环节或
|
||
``goBackTarget``),终点不在上游就在骗人。
|
||
"""
|
||
problems: list[str] = []
|
||
forward = {
|
||
# 按**标了没有**筛,不按 is_back_route:后者的兜底正好把这条没标的边摘掉了,
|
||
# 那样就永远抓不到"没标语义"这件事本身。
|
||
node_id: [route for route in definition.routes_from(node_id) if not _marked_back_route(definition, route)]
|
||
for node_id in definition.activities
|
||
}
|
||
# 0/没来过、1=还在当前路径上、2=走完了
|
||
state: dict[str, int] = {}
|
||
for start in definition.activities:
|
||
if state.get(start):
|
||
continue
|
||
state[start] = 1
|
||
path: list[tuple[str, int]] = [[start, 0]] # type: ignore[list-item]
|
||
while path:
|
||
frame = path[-1]
|
||
routes = forward.get(frame[0], [])
|
||
if frame[1] >= len(routes):
|
||
state[frame[0]] = 2
|
||
path.pop()
|
||
continue
|
||
route = routes[frame[1]]
|
||
frame[1] += 1
|
||
target = route.to_activity
|
||
if state.get(target) == 1:
|
||
if not decision_of(definition, route):
|
||
problems.append(UNMARKED_BACK_EDGE.format(
|
||
route=route.name,
|
||
src=(definition.activity(frame[0]).name if definition.activity(frame[0]) else frame[0]),
|
||
dst=(definition.activity(target).name if definition.activity(target) else target),
|
||
))
|
||
elif not state.get(target) and target in definition.activities:
|
||
state[target] = 1
|
||
path.append([target, 0]) # type: ignore[list-item]
|
||
|
||
for route in definition.routes:
|
||
if decision_of(definition, route) != "goBack":
|
||
continue
|
||
target = definition.activity(route.to_activity)
|
||
if target is None or target.id in upstream_ids(definition, route.from_activity):
|
||
continue
|
||
origin = definition.activity(route.from_activity)
|
||
problems.append(GOBACK_ROUTE_NOT_BACKWARD.format(
|
||
route=route.name,
|
||
src=origin.name if origin is not None else route.from_activity,
|
||
dst=target.name,
|
||
))
|
||
return problems
|
||
|
||
|
||
#: 审批人去重的取值:``dedup`` 往回看(前面批过),``dedupAhead`` 往前看(后面还要批)。
|
||
DEDUP_MODES = {"none", "all"}
|
||
AHEAD_MODES = {"none", "all", "any"}
|
||
|
||
|
||
def _check_serial_timing(definition: ProcessDefinition) -> list[str]:
|
||
"""编号生成时机:取值要认识,指定的环节要真在这张流程图上。
|
||
|
||
环节被删掉、改名之后配置会指向一个不存在的地方,这时不挡发布只当没到那一步的话,
|
||
整条流程就永远不会有人给它排号——那种单子办完还空着单号,比发布时报错难查得多。
|
||
"""
|
||
from ..service import numbering
|
||
|
||
raw = definition.serial or {}
|
||
problems = numbering.timing_problems(raw)
|
||
if problems:
|
||
return problems
|
||
timing = numbering.clean_timing(raw)
|
||
if timing["at"] != numbering.TIMING_ACTIVITY or not timing["activity"]:
|
||
return []
|
||
node = definition.activity(timing["activity"]) or definition.activity_by_name(timing["activity"])
|
||
if node is None:
|
||
return [f"编号要在环节「{timing['activity']}」生成,但流程图上没有这个环节"]
|
||
if timing["when"] == numbering.WHEN_LEAVE and node.type in (ACTIVITY_END, ACTIVITY_CANCEL):
|
||
return [f"编号要在环节「{node.name}」批完再生成,但结束类环节没有「批完」这一步,改成到达时生成或换个环节"]
|
||
return []
|
||
|
||
|
||
def _check_approval_defaults(definition: ProcessDefinition) -> list[str]:
|
||
"""流程级审批规则与环节上的前瞻口径:只在取值不认识时报错,配置本身是可选的。"""
|
||
problems: list[str] = []
|
||
if str(definition.approval.get("dedup") or "none") not in DEDUP_MODES:
|
||
problems.append(f"审批人去重口径不支持:{definition.approval.get('dedup')}")
|
||
if str(definition.approval.get("dedupAhead") or "none") not in AHEAD_MODES:
|
||
problems.append(f"「后面还要他批才跳过」的口径不支持:{definition.approval.get('dedupAhead')}")
|
||
for node in definition.activities.values():
|
||
scope = (node.config or {}).get("skipAheadScope")
|
||
if scope not in (None, "") and str(scope) not in {"all", "any"}:
|
||
problems.append(f"环节 {node.name} 的前瞻去重口径不支持:{scope}")
|
||
return problems
|
||
|
||
|
||
def _check_approver_policy(definition: ProcessDefinition) -> list[str]:
|
||
"""审批方式的补充开关:依次审批要能解析出人,空审批人兜底要么选对策略要么配好人。"""
|
||
problems: list[str] = []
|
||
for node in definition.activities.values():
|
||
if node.type != ACTIVITY_MANUAL:
|
||
continue
|
||
config = node.config or {}
|
||
mode = str(config.get("mode") or "any")
|
||
if mode not in {"any", "all", "join", "serial", "ratio"}:
|
||
problems.append(f"环节 {node.name} 的审批方式不支持")
|
||
if mode == "ratio":
|
||
problems.extend(_quota_problems(node, config, "按比例会签"))
|
||
policy = str(config.get("emptyApprover") or "").strip()
|
||
if policy and policy not in {"toCreator", "autoPass", "toAdmin", "fixed"}:
|
||
problems.append(f"环节 {node.name} 的空审批人兜底策略不支持:{policy}")
|
||
if policy == "fixed" and not (config.get("emptyApproverValues") or []):
|
||
problems.append(f"环节 {node.name} 的空审批人兜底选了「指定人员」但还没选人")
|
||
action = str(config.get("timeoutAction") or "notify")
|
||
if action not in {"notify", "autoPass", "autoReject"}:
|
||
problems.append(f"环节 {node.name} 的超时处理方式不支持:{action}")
|
||
elif action != "notify" and not (config.get("expireValue") or 0):
|
||
problems.append(f"环节 {node.name} 配了超时自动处理但没设处理时限,定时器不会动它")
|
||
elif action == "autoReject" and not any(r.decision == "goBack" for r in definition.routes_from(node.id)):
|
||
problems.append(f"环节 {node.name} 要超时自动退回,但没有任何退回路由")
|
||
problems.extend(_check_form_perms(definition))
|
||
for node in definition.activities.values():
|
||
if node.type != ACTIVITY_MERGE:
|
||
continue
|
||
config = node.config or {}
|
||
if config.get("passCount") or config.get("passRatio"):
|
||
problems.extend(
|
||
_quota_problems(node, config, "汇聚放行", len(definition.routes_to(node.id)))
|
||
)
|
||
return problems
|
||
|
||
|
||
def _check_form_perms(definition: ProcessDefinition) -> list[str]:
|
||
"""表单字段权限的格式校验:**每种环节都查**,不再只盯着人工环节。
|
||
|
||
运行时一直肯 ``config.formPerms``,开始环节也一样 —— ``engine.create_job`` 把
|
||
``definition.begin`` 一起交给 ``_apply_form_runtime`` 与 ``_validate_form``,
|
||
藏起来的格子不上发起页、也不参与必填。以前这段校验躲在 ``type != manual: continue``
|
||
底下,于是发起环节写成 ``{"金额": "read_only"}`` 这种拼错的值能一路发布,
|
||
运行期那一格按「没配过」走,人对着界面点了「只读」却发现照样能改,
|
||
还以为是权限没生效。设计器现在也把这一格长在了开始环节上,两头得同一口径。
|
||
"""
|
||
problems: list[str] = []
|
||
for node in definition.activities.values():
|
||
perms = (node.config or {}).get("formPerms")
|
||
if perms in (None, ""):
|
||
continue
|
||
if not isinstance(perms, dict):
|
||
problems.append(f"环节 {node.name} 的表单字段权限格式不对")
|
||
continue
|
||
bad = [key for key, value in perms.items() if str(value) not in _FORM_PERMS]
|
||
if bad:
|
||
problems.append(
|
||
f"环节 {node.name} 有字段的权限取值不合法:{'、'.join(sorted(map(str, bad)))}"
|
||
)
|
||
return problems
|
||
|
||
|
||
def _quota_problems(node, config: dict, label: str, incoming: int = 0) -> list[str]:
|
||
""""几张票 / 多少比例"这类放行配额的校验:要么没配,要么配得对。
|
||
|
||
配错的比例在运行时会被夹回合法区间(不会卡死流程),但设计期还是得说清楚,
|
||
否则「200% 通过」这种配置上线后行为与设计者预期完全对不上。
|
||
"""
|
||
problems: list[str] = []
|
||
try:
|
||
count = int(config.get("passCount") or 0)
|
||
ratio = float(config.get("passRatio") or 0)
|
||
except (TypeError, ValueError):
|
||
return [f"环节 {node.name} 的{label}票数/比例要填数字"]
|
||
if count < 0 or ratio < 0:
|
||
problems.append(f"环节 {node.name} 的{label}票数/比例不能是负数")
|
||
if not count and not ratio:
|
||
problems.append(f"环节 {node.name} 选了{label},但还没设放行票数或比例")
|
||
if ratio and not 0 < ratio <= 100:
|
||
problems.append(f"环节 {node.name} 的{label}比例要在 0 到 100 之间")
|
||
if incoming and count > incoming:
|
||
problems.append(f"环节 {node.name} 只有 {incoming} 条入口支线,要求 {count} 票永远达不成")
|
||
return problems
|