From 5ff8c1eada3cebdb984ebbb00350be23683b91d2 Mon Sep 17 00:00:00 2001 From: kangwenjing <1138819403@qq.com> Date: Mon, 19 Oct 2026 09:21:34 +0800 Subject: [PATCH] =?UTF-8?q?init=20=E5=88=9D=E5=A7=8B=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/app/engine/conditions.py | 591 +++++++ backend/app/engine/lookahead.py | 289 ++++ backend/app/service/dedupaudit.py | 1114 +++++++++++++ backend/app/service/drafts.py | 581 +++++++ backend/app/service/processdata.py | 500 ++++++ backend/app/service/simulator.py | 1465 +++++++++++++++++ backend/scripts/advance_offset.py | 278 ++++ backend/scripts/advance_offset_demo.py | 362 ++++ backend/scripts/dedupe_reads.py | 89 + docs/approval-dedup-design.md | 260 +++ docs/draft-create-api.md | 204 +++ frontend/src/components/oa/FieldRefInput.vue | 105 ++ .../oa/design/ApproverRuleEditor.vue | 312 ++++ .../components/oa/design/DedupAuditPanel.vue | 295 ++++ .../components/oa/design/ProcessPicker.vue | 111 ++ .../oa/design/ProcessSimulateDialog.vue | 471 ++++++ .../oa/design/ProcessSourcePanel.vue | 343 ++++ frontend/src/composables/useDedupAudit.ts | 86 + frontend/src/utils/approvalDedup.ts | 131 ++ frontend/src/utils/dedupAudit.ts | 118 ++ frontend/src/utils/fieldCapabilities.ts | 137 ++ frontend/src/utils/processCatalog.ts | 45 + frontend/src/utils/processSource.ts | 116 ++ frontend/src/utils/quotaConfig.ts | 406 +++++ frontend/src/utils/quotaPick.ts | 18 + 25 files changed, 8427 insertions(+) create mode 100644 backend/app/engine/conditions.py create mode 100644 backend/app/engine/lookahead.py create mode 100644 backend/app/service/dedupaudit.py create mode 100644 backend/app/service/drafts.py create mode 100644 backend/app/service/processdata.py create mode 100644 backend/app/service/simulator.py create mode 100644 backend/scripts/advance_offset.py create mode 100644 backend/scripts/advance_offset_demo.py create mode 100644 backend/scripts/dedupe_reads.py create mode 100644 docs/approval-dedup-design.md create mode 100644 docs/draft-create-api.md create mode 100644 frontend/src/components/oa/FieldRefInput.vue create mode 100644 frontend/src/components/oa/design/ApproverRuleEditor.vue create mode 100644 frontend/src/components/oa/design/DedupAuditPanel.vue create mode 100644 frontend/src/components/oa/design/ProcessPicker.vue create mode 100644 frontend/src/components/oa/design/ProcessSimulateDialog.vue create mode 100644 frontend/src/components/oa/design/ProcessSourcePanel.vue create mode 100644 frontend/src/composables/useDedupAudit.ts create mode 100644 frontend/src/utils/approvalDedup.ts create mode 100644 frontend/src/utils/dedupAudit.ts create mode 100644 frontend/src/utils/fieldCapabilities.ts create mode 100644 frontend/src/utils/processCatalog.ts create mode 100644 frontend/src/utils/processSource.ts create mode 100644 frontend/src/utils/quotaConfig.ts create mode 100644 frontend/src/utils/quotaPick.ts diff --git a/backend/app/engine/conditions.py b/backend/app/engine/conditions.py new file mode 100644 index 0000000..faa6eaa --- /dev/null +++ b/backend/app/engine/conditions.py @@ -0,0 +1,591 @@ +"""路由条件的静态口径:两条分支能不能在同一张单上一起走到。 + +条件分支和适用条件写的是「用印类别是合作类协议」「金额超过 10 万」这种话,图本身 +看不出来:画布上两条线都通,真跑起来却只会走一条。以前凡是往后看的判定(前瞻去重、 +设计期体检)都把带条件的出口一律当成「可能走」,于是配得再准的分支也只换来一句 +「后面有一条分支不经过他」——设计者明明把条件写死了,体检却装作没看见。 + +本模块把条件式读成可以比对的形式,只回答三件事: + +- ``decide(guard, known)``:在已知 ``known``(走到这里必须满足的那些条件)之下, + 这一条条件是**一定成立**、**一定不成立**,还是**说不准**; +- ``possible(term)``:一组条件凑在一起**有没有可能同时成立**(自相矛盾就走到头了); +- ``pick(...)``:一个环节的出口里,哪几条在这一单上还真走得通(口径抄 ``_pick_choice``: + 条件分支取第一条成立的那条,没人成立就走没写条件的那条)。 + +看不懂的条件一律降级成一个「整句原子」:只跟一模一样的整句(含取反)对消,别的一概 +不让步。**判断只做减法**——只有证得死「这两条不可能同时成立」才剪枝,证不出来就当可能, +所以永远不会因为读不懂条件而少报一次重复。 +""" + +from __future__ import annotations + +import ast +from dataclasses import dataclass, field +from typing import Iterable, Sequence + +#: ``decide()`` 的三档结论。 +TRUE = "true" +FALSE = "false" +UNKNOWN = "unknown" + +#: 原子按域分开比对:跨域(同一个字段既当文本又当数值)不互相让步,宁可算不出。 +DOMAIN_VALUE = "value" #: 单值:``==`` / ``in`` / ``!=`` / ``not in`` +DOMAIN_NUMBER = "number" #: 数值区间:``>`` / ``>=`` / ``<`` / ``<=`` +DOMAIN_TEXT = "text" #: 子串:``'经营管理中心' in 字段`` +DOMAIN_MEMBERS = "members" #: 多选:``contains([...], 字段)`` / ``字段 in [...]`` +DOMAIN_OPAQUE = "opaque" #: 读不懂的整句,只按文本对消 + +#: ``X or ''`` 这类兜底里被丢掉的假值:``truthy`` 与它撞上才算矛盾。 +FALSY_TEXTS = frozenset({"", "none", "false", "null"}) + +#: 比较式的取反:``not (x > 5)`` 就是 ``x <= 5``,翻完还能接着比区间。 +_FLIP_COMPARE = { + ast.Lt: ast.GtE, + ast.LtE: ast.Gt, + ast.Gt: ast.LtE, + ast.GtE: ast.Lt, +} +_COMPARE_OP = { + ast.Lt: "lt", + ast.LtE: "le", + ast.Gt: "gt", + ast.GtE: "ge", +} + +#: 上下文里本来就有的名字,不能当成表单字段。 +_CONTEXT_NAMES = frozenset({"data", "form", "work", "user", "variables", "context", "true", "false", "null"}) + +#: 一个环节往下最多摊开多少条「已知条件」:分支画得太碎就到此为止,按说不准处理。 +MAX_TERMS = 24 + + +@dataclass(frozen=True) +class Atom: + """一条最小说明,比如「用印类别属于 {QTYYWJ}」「部门路径里含经营管理中心」。 + + ``field`` 是 ``data:sealCategory`` / ``work:creator_unit`` 这种带来源的键, + 读不懂的整句用 ``opaque:<归一化文本>``,于是 ``not X`` 与 ``X`` 天然对消。 + """ + + field: str + domain: str + op: str + values: tuple[str | float, ...] = () + + @property + def key(self) -> tuple[str, str]: + return (self.field, self.domain) + + def describe(self) -> str: + """读不懂的整句就照原样念;认得出的式子由 :meth:`Lit.describe` 说。""" + if self.domain == DOMAIN_OPAQUE: + return self.field[len("opaque:") :] + return self.field.split(":", 1)[-1] + + +@dataclass(frozen=True) +class Lit: + """一个原子,可能带着「不成立」这层否定。""" + + atom: Atom + negated: bool = False + + def flipped(self) -> "Lit": + return Lit(self.atom, not self.negated) + + def describe(self) -> str: + """给人看的一句话:``用印类别=QTYYWJ`` / ``部门不含经营管理中心``。""" + name = self.atom.field.split(":", 1)[-1] + if self.atom.domain == DOMAIN_OPAQUE: + return ("非" if self.negated else "") + self.atom.describe() + joined = "/".join(str(item) for item in self.atom.values) + table = { + ("eq", False): f"{name}={joined}", + ("eq", True): f"{name}≠{joined}", + ("in", False): f"{name}∈{joined}", + ("in", True): f"{name}∉{joined}", + ("contains", False): f"{name}含{joined}", + ("contains", True): f"{name}不含{joined}", + ("substr", False): f"{name}含{joined}", + ("substr", True): f"{name}不含{joined}", + ("truthy", False): f"{name}填了", + ("truthy", True): f"{name}没填", + ("gt", False): f"{name}>{joined}", + ("ge", False): f"{name}≥{joined}", + ("lt", False): f"{name}<{joined}", + ("le", False): f"{name}≤{joined}", + } + return table.get((self.atom.op, self.negated), f"{name}{'≠' if self.negated else '='}{joined}") + + +#: 一条合取式(这些条件同时成立),以及一个条件式的范式(若干条里有一条成立即可)。 +Term = tuple[Lit, ...] + + +def _text(value: object) -> str: + return " ".join(str(value or "").split()) + + +def opaque(source: str) -> Atom: + return Atom(f"opaque:{_text(source)}", DOMAIN_OPAQUE, "opaque") + + +@dataclass(frozen=True) +class Guard: + """一条路由上写的条件,读成了「几条可能走法,每条是一组合取条件」。 + + ``terms`` 为空 = 这条条件永远不成立;只有一条空合取式 = 没写条件/永远成立。 + """ + + source: str = "" + terms: tuple[Term, ...] = ((),) + + @property + def blank(self) -> bool: + """没写条件,或者写的就是一句恒真。""" + return not _text(self.source) + + @property + def always(self) -> bool: + return self.terms == ((),) + + @property + def never(self) -> bool: + return self.terms == () + + @property + def fields(self) -> tuple[str, ...]: + """这条条件在看哪几个字段/上下文(只用来措辞,不参与判定)。""" + names = {item.atom.field for term in self.terms for item in term if not item.atom.field.startswith("opaque:")} + return tuple(sorted(name.split(":", 1)[-1] for name in names)) + + @property + def readable(self) -> bool: + """整句里有没有真读出点东西(全是不透明原子的就算读不懂)。""" + return any(item.atom.domain != DOMAIN_OPAQUE for term in self.terms for item in term) + + def describe(self) -> str: + """给人看的一句话:几条可能走法用「或」连,读不懂就退回原式。""" + if self.blank: + return "没写条件" + if not self.readable: + return _text(self.source) + parts = [] + for term in self.terms: + if not term: + parts.append("恒成立") + continue + parts.append(" 且 ".join(item.describe() for item in term)) + return " 或 ".join(parts) if parts else "恒不成立" + + +def parse(source: object) -> Guard: + """把一条路由条件读成 :class:`Guard`。读不懂不报错,整句退化成不透明原子。""" + raw = str(source or "") + text = raw.strip() + if not text: + return Guard(source=raw) + try: + tree = ast.parse(text, mode="eval") + except SyntaxError: + return Guard(source=raw, terms=((Lit(opaque(text)),),)) + return Guard(source=raw, terms=_dnf(tree.body, False)) + + +# --------------------------------------------------------------------------- +# 判定 +# --------------------------------------------------------------------------- + + +def possible(term: Term) -> bool: + """一组条件有没有可能同时成立。""" + return _satisfiable(term) + + +def conjoin(known: tuple[Term, ...], guard: Guard) -> tuple[Term, ...]: + """把一条条件并到「已经知道的条件」上(叉乘,摊不开就退回原样当说不准)。""" + if guard.always: + return known + if guard.never: + return () + merged: list[Term] = [] + for base in known: + for term in guard.terms: + merged.append(base + term) + if len(merged) > MAX_TERMS: + # 摊得太开:留着已知那份继续判,只是别再把这条新条件当成已知事实。 + return known + out = tuple(item for item in merged if _satisfiable(item)) + return out if out else () + + +def decide(guard: Guard, known: tuple[Term, ...] = ((),)) -> str: + """在 ``known`` 之下这条条件一定成立 / 一定不成立 / 说不准。 + + ``known`` 是「能走到这儿」必须满足的条件(DNF)。判「一定成立」用的是 + 「已知条件 ∧ 这条条件不成立」有没有可能成立:证不出矛盾就当说不准。 + """ + if guard.never: + return FALSE + if guard.always: + return TRUE + bases = known or ((),) + sat = any(_satisfiable(base + term) for base in bases for term in guard.terms) + if not sat: + return FALSE + for base in bases: + for term in guard.terms: + if _satisfiable(base + tuple(item.flipped() for item in term)): + return UNKNOWN + return TRUE + + +def pick(states: Sequence[str], *, deterministic: bool) -> list[int]: + """一个环节的出口里哪些还真可能走:``states`` 是每条出口的 :func:`decide` 结果。 + + 口径与引擎一致(``engine._pick_choice`` / ``engine._resolve_route``): + + - 条件分支(``deterministic``)由引擎自己挑:取第一条**成立**的出口,都不成立就走 + 没写条件的那条。所以一旦某条被证成,排在它后面的出口就不可能走了;排在它前面 + 那些「说不准」的还得留着——万一将来那句条件成立,被选走的就是它。 + - 人工环节的出口是人点的,引擎只负责拦下「适用条件不成立」的那几条:剩下都算可能。 + """ + alive = [index for index, state in enumerate(states) if state != FALSE] + if not alive: + return list(range(len(states))) # 一条都走不了=图画错了,别在这里替它做主 + if not deterministic: + return alive + for index in alive: + if states[index] == TRUE: + return [item for item in alive if item <= index] + return alive + + +def hint(guard: Guard) -> str: + """给措辞用的一句「这条要看什么」:字段名,读不懂就回原式。""" + fields = guard.fields + if fields: + return "、".join(fields[:3]) + ("…" if len(fields) > 3 else "") + return _text(guard.source) or "没写条件" + + +# --------------------------------------------------------------------------- +# 读式子 +# --------------------------------------------------------------------------- + + +def _dnf(node: ast.expr, negate: bool) -> tuple[Term, ...]: + """把条件式摊成「或」套「且」。摊不开的部分变成一个整句原子。""" + if isinstance(node, ast.BoolOp): + parts = [_dnf(item, negate) for item in node.values] + if isinstance(node.op, ast.Or): + if negate: + return _cross(parts) + return tuple(item for part in parts for item in part) + if negate: + return tuple(item for part in parts for item in part) + return _cross(parts) + if isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Not): + return _dnf(node.operand, not negate) + if isinstance(node, ast.Constant): + truth = bool(node.value) if isinstance(node.value, bool) else str(node.value).strip().lower() not in FALSY_TEXTS + if truth != negate: + return ((),) + return () + lit = _literal(node, negate) + if lit is not None: + return ((lit,),) + return ((Lit(opaque(ast.unparse(node)), negate),),) + + +def _cross(parts: Iterable[tuple[Term, ...]]) -> tuple[Term, ...]: + out: tuple[Term, ...] = ((),) + for part in parts: + if not part: + return () + out = tuple(base + term for base in out for term in part) + if len(out) > MAX_TERMS: + return out[:MAX_TERMS] + return out + + +def _literal(node: ast.expr, negate: bool) -> Lit | None: + """认得出的一次判断,认不出返回 ``None``。""" + node = _unwrap(node) + if isinstance(node, ast.Compare): + return _from_compare(node, negate) + if isinstance(node, ast.Call): + return _from_call(node, negate) + name = _field(node) + if name: + return Lit(Atom(name, DOMAIN_VALUE, "truthy"), negate) + return None + + +def _unwrap(node: ast.expr) -> ast.expr: + """剥掉 ``str(X or '')`` / ``bool(X)`` / ``X or ''`` 这些为拼字符串穿的壳。""" + for _ in range(6): + if isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id in {"str", "bool"} and len(node.args) == 1: + node = node.args[0] + continue + if isinstance(node, ast.BoolOp) and isinstance(node.op, ast.Or) and len(node.values) == 2 and _is_empty(node.values[1]): + node = node.values[0] + continue + return node + return node + + +def _is_empty(node: ast.expr) -> bool: + """``X or ''`` / ``X or []`` / ``X or None``:兜底那一侧是空值才算壳,别把 ``X or 'A'`` 也剥了。""" + if isinstance(node, ast.Constant): + return node.value is None or node.value is False or str(node.value).strip() == "" + return isinstance(node, (ast.List, ast.Tuple, ast.Set, ast.Dict)) and not node.elts + + +def _from_compare(node: ast.Compare, negate: bool) -> Lit | None: + if len(node.ops) != 1: + return None + op = node.ops[0] + left, right = node.left, node.comparators[0] + if isinstance(op, (ast.Eq, ast.NotEq)): + pair = _field_with_literal(left, right) + if pair is None: + return None + name, values = pair + negated = isinstance(op, ast.NotEq) + return Lit(Atom(name, _value_domain(values), "eq", values), negated != negate) + if isinstance(op, (ast.In, ast.NotIn)): + if isinstance(right, (ast.Tuple, ast.List, ast.Set)): + values = _literal_values(right) + name = _field(left) + if name and values: + return Lit(Atom(name, _value_domain(values), "in", values), isinstance(op, ast.NotIn) != negate) + if isinstance(left, ast.Constant) and isinstance(left.value, str): + name = _field(right) + if name: + return Lit(Atom(name, DOMAIN_TEXT, "substr", (left.value,)), isinstance(op, ast.NotIn) != negate) + return None + if type(op) in _COMPARE_OP: + pair = _field_with_literal(left, right, numbers_only=True) + if pair is None: + return None + name, values = pair + kind = _COMPARE_OP[type(op)] + if negate: + kind = { # 取反之后还是区间,照样能比 + "lt": "ge", + "le": "gt", + "gt": "le", + "ge": "lt", + }[kind] + return Lit(Atom(name, DOMAIN_NUMBER, kind, values), False) + return None + + +def _from_call(node: ast.Call, negate: bool) -> Lit | None: + if isinstance(node.func, ast.Name) and node.func.id == "contains" and len(node.args) == 2: + values = _literal_values(node.args[0]) or _as_literal_tuple(node.args[0]) + name = _field(node.args[1]) + if name and values: + return Lit(Atom(name, DOMAIN_MEMBERS, "contains", values), negate) + return None + return None + + +def _field_with_literal(node: ast.expr, other: ast.expr, *, numbers_only: bool = False) -> tuple[str, tuple] | None: + """``字段 == 值``(写法反着也认),返回字段与那一侧的字面值。""" + for left, right in ((node, other), (other, node)): + name = _field(left) + values = _as_literal_tuple(right) + if not name or not values: + continue + if numbers_only and not all(isinstance(item, (int, float)) and not isinstance(item, bool) for item in values): + continue + return name, values + return None + + +def _as_literal_tuple(node: ast.expr) -> tuple: + if isinstance(node, ast.Constant) and isinstance(node.value, (str, int, float)) and not isinstance(node.value, bool): + return (node.value,) + if isinstance(node, (ast.Tuple, ast.List, ast.Set)): + return _literal_values(node) + return () + + +def _literal_values(node: ast.expr) -> tuple: + if not isinstance(node, (ast.Tuple, ast.List, ast.Set)): + return () + out = [] + for item in node.elts: + if isinstance(item, ast.Constant) and isinstance(item.value, (str, int, float)) and not isinstance(item.value, bool): + out.append(item.value) + else: + return () + return tuple(out) + + +def _field(node: ast.expr) -> str: + """这个式子说的是哪个来源:``data:xxx`` / ``work:xxx``,说不清就回空。""" + node = _unwrap(node) + if isinstance(node, ast.Name): + if node.id in _CONTEXT_NAMES: + return "" + return f"data:{node.id}" + if isinstance(node, ast.Subscript) and isinstance(node.value, ast.Name) and node.value.id in {"data", "form", "work", "variables", "user"}: + key = node.slice + if isinstance(key, ast.Constant) and isinstance(key.value, str): + return f"{node.value.id}:{key.value}" + return "" + if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) and node.func.attr == "get": + owner = node.func.value + if isinstance(owner, ast.Name) and owner.id in {"data", "form", "work", "variables", "user", "context"} and node.args: + key = node.args[0] + if isinstance(key, ast.Constant) and isinstance(key.value, str): + return f"{owner.id}:{key.value}" + return "" + return "" + + +def _value_domain(values: Sequence[object]) -> str: + """跟数字比就是数值域,跟文本比就是单值域;两种混着写就当说不准。""" + numbers = [item for item in values if isinstance(item, (int, float)) and not isinstance(item, bool)] + if numbers and len(numbers) == len(values): + return DOMAIN_NUMBER + return DOMAIN_VALUE + + +# --------------------------------------------------------------------------- +# 矛盾检查 +# --------------------------------------------------------------------------- + + +@dataclass +class _Bucket: + """同一个(字段,域)上攒下来的正/负条件,逐个往里收,收出矛盾就报。""" + + domain: str + values: set | None = None #: 值域:还可能是哪几个值;``None`` = 没限定 + low: float = float("-inf") + high: float = float("inf") + low_open: bool = True + high_open: bool = True + positive: set = field(default_factory=set) #: 文本/成员/不透明域:必须出现的 + negative: set = field(default_factory=set) #: 必须不出现的 + truthy: bool = False + falsy_only: bool = False + broken: bool = False + + def add(self, lit: Lit) -> None: + atom = lit.atom + if self.domain == DOMAIN_VALUE: + self._value(lit) + elif self.domain == DOMAIN_NUMBER: + self._number(lit) + elif self.domain == DOMAIN_MEMBERS: + wanted = set(atom.values) + if lit.negated: + self.negative |= wanted + else: + self.positive |= wanted + else: # text / opaque:整句或子串,只跟同一句对消 + wanted = set(atom.values) or {atom.field} + if lit.negated: + self.negative |= wanted + else: + self.positive |= wanted + + def _value(self, lit: Lit) -> None: + atom = lit.atom + if atom.op == "truthy": + if lit.negated: + self.falsy_only = True + else: + self.truthy = True + return + wanted = {str(item) for item in atom.values} + if lit.negated: + self.negative |= wanted + return + if self.values is None: + self.values = set(wanted) + else: + self.values &= wanted + if not self.values: + self.broken = True + + def _number(self, lit: Lit) -> None: + atom = lit.atom + if not atom.values: + return + bound = float(atom.values[0]) # type: ignore[arg-type] + kind = atom.op + if lit.negated: + # 取反的区间还是区间:not (x > 5) 就是 x <= 5,判「这条条件一定成立」全靠这一步 + kind = {"gt": "le", "ge": "lt", "lt": "ge", "le": "gt"}[kind] + if kind == "gt": + self._raise(bound, True) + elif kind == "ge": + self._raise(bound, False) + elif kind == "lt": + self._lower(bound, True) + elif kind == "le": + self._lower(bound, False) + elif kind == "eq": + self._raise(bound, False) + self._lower(bound, False) + + def _raise(self, bound: float, open_: bool) -> None: + # 同一条边界上「开区间」比闭区间更紧,谁紧听谁的 + if bound > self.low or (bound == self.low and open_ and not self.low_open): + self.low, self.low_open = bound, open_ + self._narrow() + + def _lower(self, bound: float, open_: bool) -> None: + if bound < self.high or (bound == self.high and open_ and not self.high_open): + self.high, self.high_open = bound, open_ + self._narrow() + + def _narrow(self) -> None: + if self.low > self.high or (self.low == self.high and (self.low_open or self.high_open)): + self.broken = True + + def conflicts(self) -> bool: + if self.broken: + return True + if self.domain == DOMAIN_VALUE: + if self.values is not None and self.values <= self.negative: + return True + if self.values is not None and self.truthy and all(item in FALSY_TEXTS for item in self.values): + return True + if self.falsy_only and self.values is not None and all(item not in FALSY_TEXTS for item in self.values): + return True + return False + if self.domain == DOMAIN_NUMBER: + return self.low > self.high or (self.low == self.high and (self.low_open or self.high_open)) + if self.positive & self.negative: + return True + # 多选:「含这几个里的某一个」被「这几个一个都不许含」整个盖住 + return self.domain == DOMAIN_MEMBERS and bool(self.positive) and self.positive <= self.negative + + +def _satisfiable(term: Term) -> bool: + """一组条件能不能同时成立:按字段分桶收一遍,收出矛盾就是走不到。""" + buckets: dict[tuple[str, str], _Bucket] = {} + for lit in term: + bucket = buckets.get(lit.atom.key) + if bucket is None: + bucket = buckets[lit.atom.key] = _Bucket(lit.atom.domain) + bucket.add(lit) + for bucket in buckets.values(): + if bucket.conflicts(): + return False + # 数值取反(``not (x > 5)`` 这种在范式里已是反向区间)不需要再看一眼 + return True + + +def describe(guards: Iterable[Guard]) -> str: + """几条条件合起来的一句话说明(只在提示语里用)。""" + parts = [guard.describe() for guard in guards if not guard.always] + return ";".join(part for part in parts if part) diff --git a/backend/app/engine/lookahead.py b/backend/app/engine/lookahead.py new file mode 100644 index 0000000..9394714 --- /dev/null +++ b/backend/app/engine/lookahead.py @@ -0,0 +1,289 @@ +"""前瞻分析:从某一环往后看,同一个人还会不会被要求审批。 + +``skipApproved``(前面批过就跳过)看的是过去,这里看的是未来——后面还要他签, +前面这一环就不必再拦一次。未来不是既成事实,所以判定一律往保守的方向做: + +- ``all``(默认口径):只有**每一条**后续路径都一定经过他,才算「后面还要他批」。 + 条件分支、或签、配了免审条件的环节都会把「一定」变成「不一定」,这时前面照常派待办。 +- ``any``:只要有一条后续路径可能经过他就跳过前面。省待办更狠,但分支一拐弯 + 他可能一次都没批过,只在路径简单的流程上用。 + +环路(退回重走)、解析不出人、超出走访预算,统统按「不敢断定」处理: +宁可多派一条待办,也不能让一张单子谁都没批就走到头。 + +本模块只认 ``activity(id)`` / ``routes_from(id)`` / ``resolve(node)`` 这三件事, +不碰数据库,方便单独测;「这一环当下哪几条出口真走得通」「这一环的免审条件碰得到谁」 +这两个要读库、算表单的问题,由调用方以回调传进来(见 ``upcoming`` 的 ``routes`` / +``droppable``),传与不传只影响能省掉多少待办,不会让判定变激进。 +""" + +from __future__ import annotations + +import logging +from dataclasses import dataclass, field +from typing import Callable, Iterable + +logger = logging.getLogger(__name__) + +#: 前瞻口径,与流程级 ``approval_config.dedupAhead`` 取值一致。 +SCOPE_NONE = "none" +SCOPE_ALL = "all" +SCOPE_ANY = "any" + +#: 到结束/作废就算走完,后面没有人再批。 +TERMINAL_TYPES = frozenset({"end", "cancel"}) +#: 名单上的每个人都必须表态的审批方式:只有这几种能把「他会批」算成确定发生。 +#: 或签(any)与按比例会签(ratio)都不算——同意的凑够数就把其他人结掉了。 +STRICT_MODES = frozenset({"all", "join", "serial"}) + +#: 一次前瞻最多走访多少个环节。图再离谱也不该把「到达某一环」拖慢。 +MAX_VISITS = 120 + + +@dataclass +class Forecast: + """往后看的结果。 + + ``persons`` 是可以认为「后面还会批」的人;``origin`` 记着是在后面哪个环节遇到他的, + 流转日志要说清「凭什么免掉前面这一环」。 + """ + + persons: set[str] = field(default_factory=set) + origin: dict[str, str] = field(default_factory=dict) + visits: int = 0 + #: 图太大没看完:结果只可能少不可能多,调用方不用特殊处理。 + truncated: bool = False + + +Resolver = Callable[[object], Iterable[str]] + + +def upcoming( + definition: object, + activity_id: str, + resolve: Resolver, + *, + scope: str = SCOPE_ALL, + max_visits: int = MAX_VISITS, + routes: Callable[[object], Iterable[object]] | None = None, + droppable: Callable[[object], dict] | None = None, +) -> Forecast: + """从 ``activity_id`` 往后看,返回「后面还会批」的人。 + + ``resolve(node)`` 给出某个环节的处理人(person id);解析抛错=这一环后面指不定 + 是谁,整次前瞻作废(回空集,谁都不跳过)。 + + ``routes(node)`` 给出这一环**当下真走得通**的出口:条件分支按当前表单收敛成一条、 + 适用条件不成立的先剪掉。不给就按画布上所有出口算(保守)。 + ``droppable(node)`` 说清这一环的免审条件碰得到谁,用来回答「他会不会被免掉」; + 不给就一律当碰得到(保守)。 + """ + if scope == SCOPE_ANY: + return _reachable(definition, activity_id, resolve, max_visits, routes) + return _guaranteed(definition, activity_id, resolve, max_visits, routes, droppable) + + +class _Budget: + """走访预算:超了就停,并且把结果标成「没看完」。""" + + def __init__(self, max_visits: int) -> None: + self.left = max(1, int(max_visits)) + self.visits = 0 + self.truncated = False + + def spend(self) -> bool: + if self.left <= 0: + self.truncated = True + return False + self.left -= 1 + self.visits += 1 + return True + + +class _Abort(Exception): + """解析不出后面是谁(脚本抛错、数据坏了):这次前瞻整个不算。""" + + +def _persons_of(node: object, resolve: Resolver, cache: dict[str, set[str]]) -> set[str]: + node_id = str(getattr(node, "id", "") or "") + if node_id in cache: + return cache[node_id] + config = getattr(node, "config", None) or {} + if not (config.get("taskValues") or str(config.get("taskScript") or "").strip()): + # 没配找人方式的环节本来就没处理人(或者靠兜底补人),不算「一定有他」。 + cache[node_id] = set() + return cache[node_id] + try: + persons = {str(item) for item in resolve(node) if str(item or "").strip()} + except Exception as exc: # noqa: BLE001 - 前瞻失败只该让跳过不生效,不该影响流转 + raise _Abort(str(exc)) from exc + cache[node_id] = persons + return persons + + +def _counts( + node: object, persons: set[str], person: str, droppable: Callable[[object], dict] | None = None +) -> bool: + """这个环节把「他会批」算不算确定发生。 + + 或签、按比例会签都不算(凑够票就把其他人结掉了),除非整环就他一个人。 + 免审条件不再一票否决整环:只有这条规则**可能碰到他**(整环都免、或者名单说不准、 + 或者就叫到他名字)才算这一环不一定有他——规则点的是别人,他这一票照样跑不掉。 + """ + if not persons: + return False + config = getattr(node, "config", None) or {} + if config.get("skipRules") and _may_drop(node, person, droppable): + return False + mode = str(config.get("mode") or "any") + return mode in STRICT_MODES or len(persons) == 1 + + +def _may_drop(node: object, person: str, droppable: Callable[[object], dict] | None) -> bool: + """这一环配的免审条件有没有可能把 ``person`` 免掉;没给回调就一律当可能。""" + if droppable is None: + return True + try: + reach = droppable(node) or {} + except Exception: # noqa: BLE001 - 算不出来就按最保守的「碰得到他」处理 + return True + if reach.get("whole") or reach.get("unknown"): + return True + return person in (reach.get("persons") or set()) + + +def _reachable( + definition: object, + activity_id: str, + resolve: Resolver, + max_visits: int, + provider: Callable[[object], Iterable[object]] | None = None, +) -> Forecast: + """``any`` 口径:往后能走到的环节里出现过谁,就算谁「后面可能还要批」。""" + forecast = Forecast() + budget = _Budget(max_visits) + cache: dict[str, set[str]] = {} + begin = definition.activity(str(activity_id)) # type: ignore[attr-defined] + queue = [str(r.to_activity) for r in _routes(definition, begin, provider)] + seen = {str(activity_id), *queue} + try: + while queue: + node_id = queue.pop(0) + if not budget.spend(): + break + node = definition.activity(node_id) # type: ignore[attr-defined] + if node is None or str(getattr(node, "type", "")) in TERMINAL_TYPES: + continue + if str(getattr(node, "type", "")) == "manual": + for person in _persons_of(node, resolve, cache): + forecast.persons.add(person) + forecast.origin.setdefault(person, str(getattr(node, "name", "") or "")) + for route in _routes(definition, node, provider): + nxt = str(route.to_activity) + if nxt not in seen: + seen.add(nxt) + queue.append(nxt) + except _Abort as exc: + logger.warning("审批人前瞻分析失败,本环节不跳过任何人:%s", exc) + return Forecast() + forecast.truncated = budget.truncated + forecast.visits = budget.visits + return forecast + + +def _guaranteed( + definition: object, + activity_id: str, + resolve: Resolver, + max_visits: int, + provider: Callable[[object], Iterable[object]] | None = None, + droppable: Callable[[object], dict] | None = None, +) -> Forecast: + """``all`` 口径:只认「每条后续路径都躲不开」的人。 + + ``g(n) = 这一环的人 ∪ (每条出口路由的 g 交集)``,从本环节的出口一路往里收。 + 绕回本环、走回栈上的环节、没看完的分支都回空集,交集一旦空掉就不再跳过。 + """ + forecast = Forecast() + budget = _Budget(max_visits) + cache: dict[str, set[str]] = {} + memo: dict[str, set[str]] = {} + + def walk(node_id: str, stack: frozenset[str]) -> tuple[set[str], bool]: + if node_id in memo: + return memo[node_id], False + if node_id == str(activity_id) or node_id in stack: + # 绕回自己或成环:说不清还会不会经过,保守按「不确定」处理。 + return set(), True + node = definition.activity(node_id) # type: ignore[attr-defined] + if node is None: + return set(), True + if not budget.spend(): + return set(), True + kind = str(getattr(node, "type", "")) + routes = _routes(definition, node, provider) + if kind in TERMINAL_TYPES or not routes: + ahead, uncertain = set(), False + else: + # 每条出口都要走到才算「一定」:取交集,任何一条分支不确定就整体不确定 + parts: list[set[str]] = [] + uncertain = False + for route in routes: + sub, sub_uncertain = walk(str(route.to_activity), stack | {node_id}) + parts.append(sub) + uncertain = uncertain or sub_uncertain + ahead = set.intersection(*parts) if parts else set() + if kind == "manual": + own = _persons_of(node, resolve, cache) + keeping = {person for person in own if _counts(node, own, person, droppable)} + if keeping: + ahead = ahead | keeping + # 后序遍历,所以这一环比已经记过的下游都更近,日志里说「后面最近在哪 + # 个环节还要批」就该用覆盖后的那一个。 + for person in keeping: + forecast.origin[person] = str(getattr(node, "name", "") or "") + if not uncertain: + memo[node_id] = ahead + return ahead, uncertain + + try: + begin = definition.activity(str(activity_id)) # type: ignore[attr-defined] + for route in _routes(definition, begin, provider): + persons, _ = walk(str(route.to_activity), frozenset({str(activity_id)})) + forecast.persons |= persons + except _Abort as exc: + logger.warning("审批人前瞻分析失败,本环节不跳过任何人:%s", exc) + return Forecast() + forecast.truncated = budget.truncated + forecast.visits = budget.visits + # 交集口径下 origin 会记下没真正生效的环节,只用于日志措辞,这里按结果收一遍。 + forecast.origin = {p: name for p, name in forecast.origin.items() if p in forecast.persons} + return forecast + + +def _routes( + definition: object, + node: object, + provider: Callable[[object], Iterable[object]] | None = None, +) -> list[object]: + """这一环往外走的出口。 + + 退回(``goBack``)一律不算:它是「把单子打回去」而不是往前走完,退回之后重走哪几环 + 说不准。把它当成一条正常出口,几乎所有配了「驳回」的流程都再也免不掉重复签字—— + 与 ``service/simulator.py`` 的 ``_forward`` 同一口径。 + + ``provider`` 是调用方给的「当下真走得通的那几条」,拿不到就退回画布上的全部出口。 + """ + node_id = str(getattr(node, "id", "") or "") + try: + rows = list(provider(node)) if provider is not None else list(definition.routes_from(node_id) or []) # type: ignore[attr-defined] + except Exception: # noqa: BLE001 - 定义或条件有问题时按「后面什么都可能发生」处理 + return [] + overrides = dict((getattr(node, "config", None) or {}).get("routeDecisions") or {}) + out: list[object] = [] + for route in rows: + name = str(getattr(route, "name", "") or "") + decision = str(overrides.get(name) or getattr(route, "decision", "") or "") + if decision != "goBack": + out.append(route) + return out diff --git a/backend/app/service/dedupaudit.py b/backend/app/service/dedupaudit.py new file mode 100644 index 0000000..85758f2 --- /dev/null +++ b/backend/app/service/dedupaudit.py @@ -0,0 +1,1114 @@ +"""设计期「重复审批人」体检:同一张单会被同一个人签几次,配置真管住了吗。 + +运行时早就有这套免重复签字的规矩(``engine.approval_flags`` 那三个开关,加上 +``engine/lookahead.py`` 的往后看),可设计器里看不见结果:画了六个环节、三个人 +各出现两次,到底谁会被自动跳过、哪一环照旧要签两次,只能等真发一单才发现。 +本模块把同一套判定挪到设计期跑一遍——拿画布上当前的环节与路由(含还没保存的改动)、 +按组织现在的找人结果试算,逐个环节给出结论。 + +刻意不复算一遍规则:三档开关、前瞻口径都直接调 ``engine`` 里那几个纯函数, +只有"后面这一环躲不躲得开"是这里按图自己算的,口径与 ``lookahead._guaranteed`` 一致 +(成环、没看完、解析不出人,一律按"不敢断定"处理)。 + +画布上的重复分几种,结论的确定程度完全不同,所以各给一档: + +- 一前一后(后面那个能从前面走到):策略管不管得住,判得准。 +- 互斥分支上(互相走不到,也没有并行环节同时展开两支):这一单根本不会都走到,不算重复。 +- 条件上对不上(走到前面那一环的前提与通往后面那一环的分支条件互相矛盾):同样走不到一起, + 单独列成 ``impasses`` 说清凭什么排除,别让人对着两个环节自己想不通。 +- 并行/拆分分支上(两支会同时展开):运行时两边都派待办,去重两头都不认,只能标"待确认"。 + +路由上写的条件(条件分支的判据、出口上的适用条件)是这张图的一部分,不是一句注释: +它们由 ``engine/conditions.py`` 读成可比对的形式,「会不会两次都走到」「后面必经他吗」 +两问都按它们算过。判不出的条件一律当"可能走",所以这一层只会让结论更准,不会让漏报变多。 + +试算本身也有猜不准的地方:靠发起人、上一环节处理人、表单字段、脚本找人的环节, +换个人发起就可能换个人,这类环节标 ``dynamic``,界面上那句"这条是试算"就是这么来了。 +降级降到哪儿有讲究——往回看那档认的是"这张单他真批过一次",运行时换成谁都改得成立, +所以被它管住的一对照样算"已管住";往前看那档认的是"后面每条路都要他批",这一句本身就 +依赖后面那一环落到几个人身上,名单没定就只能报"待确认"。 + +环节上配的免审 / 必批条件也只按人判:规则点的是别人,就不该拖住整环说"他可能不签"。 +这份"规则碰得到谁"的口径住在 ``engine.rule_reach``,前瞻去重与设计期体检共用一份, +两边不会各算各的。 +""" + +from __future__ import annotations + +from dataclasses import dataclass, field + +from sqlalchemy import select +from sqlalchemy.orm import Session + +from .. import models +from ..engine import conditions +from ..engine.conditions import Guard, Term +from . import org + +#: 与 engine 里那四档策略同名,前端 utils/approvalDedup 用的是同一套词。 +POLICY_EACH = "each" +POLICY_FIRST = "first" +POLICY_LAST = "last" +POLICY_ONCE = "once" + +SCOPE_ALL = "all" +SCOPE_ANY = "any" + +#: 名单上每个人都必须表态的审批方式:只有这几种能把"他一定会批"算成确定发生。 +#: 口径抄自 ``lookahead.STRICT_MODES``(或签与按比例会签凑够票就把别人结掉了)。 +STRICT_MODES = frozenset({"all", "join", "serial"}) +#: 会把多支分支同时展开的环节类型:落在这种分支上的重复,两边都会真的派待办。 +CONCURRENT_TYPES = frozenset({"parallel", "split"}) + +#: 一次体检最多看多少个环节、走多少步。设计图再离谱也不该把这一枪拖成卡顿。 +MAX_NODES = 300 +MAX_WALK = 20000 + +#: 一对重复审批的结论。 +PAIR_DOUBLE = "double" #: 两处都要他签:这一对没被任何一档策略管住 +PAIR_LATER = "later" #: 后面那一环自动跳过(前面已经批过) +PAIR_EARLIER = "earlier" #: 前面这一环自动跳过(后面还要他批) +PAIR_UNKNOWN = "unknown" #: 并行分支同时展开,或找人要等运行时才定得下来 + +#: 这一对为什么落在这样一个结论上。界面上那一键修法照它挑(见 ``utils/dedupAudit.ts``): +#: 前三种是"开一档往回看就管得住",后两种是去重本身救不了的。 +CAUSE_COVERED = "covered" #: 生效中的那档管住了这一对,没有要修的东西 +CAUSE_POLICY_OFF = "policy_off" #: 两个方向都没开,这一对本来就没人管 +CAUSE_AHEAD_UNPROVEN = "ahead_unproven" #: 往前看开着,但后面有一条分支不经过他,不敢跳 +CAUSE_FIRST_NODE = "first_node" #: 前面那环是起草环节,往前看不许跳(待办是落脚点) +CAUSE_CONCURRENT = "concurrent" #: 两个环节会同时展开,去重两头都够不着 +CAUSE_MUST_RULE = "must_rule" #: 后面那环配了必批规则,可能把他保下来再签一次 + +#: 一组重复审批的总评。 +VERDICT_COVERED = "covered" #: 每一对都有人管 +VERDICT_OPEN = "open" #: 至少还有一对要签两次 +VERDICT_WATCH = "watch" #: 说不准,需要人看一眼 +VERDICT_BRANCH = "branch" #: 重复都落在互斥分支上,同一张单不会都走到 + +#: 这几种找人方式要等这一单真跑起来才定得下来,设计期算出来的人只能当参考。 +RUNTIME_KINDS = frozenset({"creator", "prev", "prevunit", "form"}) | org.RELATION_KINDS + + +@dataclass +class _Node: + """体检用的一个人工环节:试算出来的人 + 这一环真正生效的那档策略。""" + + id: str + name: str + type: str + config: dict + persons: dict[str, str] = field(default_factory=dict) # person id → 展示名 + policy: str = POLICY_EACH + inherited: bool = True + skip_starter: bool = False + skip_approved: bool = False + skip_ahead: bool = False + scope: str = SCOPE_ALL + dynamic: bool = False + has_skip_rules: bool = False + has_must_rules: bool = False + first: bool = False + mode: str = "any" + unknown: list[str] = field(default_factory=list) + notes: list[str] = field(default_factory=list) + #: 免审 / 必批规则「碰得到谁」:整环、说不准、还是就这么几个(口径见 ``engine.rule_reach``) + drop_reach: dict = field(default_factory=lambda: {"whole": False, "unknown": False, "persons": set()}) + must_reach: dict = field(default_factory=lambda: {"whole": False, "unknown": False, "persons": set()}) + + @property + def manual(self) -> bool: + return self.type == "manual" + + def may_drop(self, person: str) -> bool: + """这一环配的免审条件有没有可能把 ``person`` 免掉。 + + 只有说死「这条规则碰的是那几个人、而他不在这几个人里」才敢放行;规则带脚本、 + 按发起人/上级找人、或者名字解析不出来,一律当他可能被免掉——放错了就是让整环 + 一个人都没批,比多签一次严重得多。 + """ + reach = self.drop_reach + return bool(reach["whole"] or reach["unknown"] or person in reach["persons"]) + + def must_keep(self, person: str) -> bool: + """必批规则会不会把 ``person`` 保下来,让「前面批过」也免不掉他。""" + reach = self.must_reach + return bool(reach["unknown"] or person in reach["persons"]) + + def counts_as_certain(self, person: str) -> bool: + """这一环的"他一定会批"算不算确定发生(与 ``lookahead._counts`` 同一口径)。 + + 免审条件不再一票否决整环:配了免审规则只说明这一环可能少几个人,能不能少到 + 他头上是另一件事——规则碰的那几个人里没有他,这一环对他的"一定会批"照样成立。 + """ + if not self.persons or self.may_drop(person): + return False + return self.mode in STRICT_MODES or len(self.persons) == 1 + + +@dataclass +class _Pair: + """一对重复环节的判定。两个布尔各说一件事,别混在一起看: + + - ``certain``:这一对里两个环节的人现在是不是都定得下来(试算出来的名单标 ``False``); + - ``settled``:这一对归没被管住,**换成谁、名单怎么变都成立吗**。往回看那档认的是 + 「这张单他真批过一次」,运行时换成谁都改得成立;往前看那档认的是「后面每条路都要他批」, + 这句话本身依赖后面那一环落到几个人身上,所以只有后面那个环节要等运行时才定人时, + 这条结论才算判不准——前面那环自己动态不影响它。 + """ + + outcome: str + certain: bool + settled: bool + reason: str + cause: str + #: 「后面有一条分支不经过他」到底是哪一条:环节名 + 分支名 + 它看哪个字段 + blockers: list[dict] = field(default_factory=list) + #: 走到前面那一环得先满足什么(分支条件是判断的一部分,得说清前提) + entry: str = "" + + @property + def conditional(self) -> bool: + """这条结论有没有拿分支条件参与判断。""" + return bool(self.blockers) or bool(self.entry) + + +#: 退回路由的决定值:这一条不走完审批,而是把单子打回去。 +GO_BACK = "goBack" + +#: 「能走到这一环」的条件最多摊成几条:分支画得太碎就补一条「说不准」,别硬撑。 +MAX_ENTRY_TERMS = 12 +#: 一条结论最多举几条挡路分支,再多就只是刷屏。 +MAX_BLOCKERS = 3 + +#: 挡路分支:一条出口,以及它在说些什么。 +Blocker = dict + + +@dataclass +class _Edge: + """画布上的一条出口路由:除了从哪到哪,还带着它自己写的那个条件。 + + 以前只把路由当成一条边,条件分支和适用条件全被抹平成「可能走」,于是配得再死的 + 分支也只换来一句「后面有一条分支不经过他」。现在条件跟着边一起走。 + """ + + dst: str + name: str + decision: str = "" + guard: Guard = field(default_factory=Guard) + order: int = 0 + + @property + def forward(self) -> bool: + """这条出口是不是往前走:退回不参与「后面还要他批」的推算,与试跑同一口径。""" + return self.decision != GO_BACK + + +@dataclass +class _Walk: + """一趟推演的收获:结论 + 挡路的那几条出口 + 走到起点得先满足什么。 + + ``unknown`` 是「没看完、成环、算超预算」这一类判不出来的情况。它绝不能被当成 + 「走不到」——那会把一次真重复悄悄抹掉;判不出来的,一律留着让人再看一眼。 + """ + + ok: bool + blockers: list[Blocker] = field(default_factory=list) + entry: str = "" + unknown: bool = False + + +@dataclass +class _Graph: + """画布上那张图。可达、必经、并行同展、走到某一环得满足什么条件,都在这里问。 + + 两种走法故意不一样,别拧成一股: + + - **会不会重复**(:meth:`possible`):退回也算一条路。退回去重走一遍,两个环节 + 可能真都要他签,这里漏判就是少报,宁可保守。 + - **后面必经他吗**(:meth:`must_pass`):只看往前走的出口。退回意味着这张单没批完, + 不会有人因为「他后面还要批」而少签一次,口径与 ``service/simulator.py`` 一致。 + """ + + edges: dict[str, list[_Edge]] = field(default_factory=dict) + adjacency: dict[str, list[str]] = field(default_factory=dict) + #: 画布上有没有写过任何一条路由条件:一条都没有时「按条件走得到」与「结构上走得到」等价 + guarded: bool = False + types: dict[str, str] = field(default_factory=dict) + names: dict[str, str] = field(default_factory=dict) + _reach: dict[str, set[str]] = field(default_factory=dict) + _ancestors: dict[str, set[str]] = field(default_factory=dict) + _entry: dict[str, tuple[Term, ...]] = field(default_factory=dict) + _entry_ready: bool = False + + @classmethod + def build(cls, activities: list[dict], routes: list[dict]) -> "_Graph": + types: dict[str, str] = {} + names: dict[str, str] = {} + overrides: dict[str, dict[str, str]] = {} + for item in activities: + node_id = str(item.get("id") or "") + if not node_id: + continue + types[node_id] = str(item.get("type") or "manual") + names[node_id] = str(item.get("name") or "未命名环节") + config = item.get("config") + if isinstance(config, dict) and isinstance(config.get("routeDecisions"), dict): + # 环节上可以把某条出口改标成「退回」,判定要看这份覆盖,口径同 ``engine._route_decision`` + overrides[node_id] = { + str(key): str(value) for key, value in config["routeDecisions"].items() if value + } + edges: dict[str, list[_Edge]] = {} + adjacency: dict[str, list[str]] = {} + for item in routes: + src = str(_pick(item, "from_activity", "fromActivity")) + dst = str(_pick(item, "to_activity", "toActivity")) + if not src or not dst: + continue + name = str(item.get("name") or "") + decision = overrides.get(src, {}).get(name) or str(_pick(item, "decision") or "") + if not decision: + for key in ("id", "alias"): + decision = overrides.get(src, {}).get(str(item.get(key) or "")) or "" + if decision: + break + edge = _Edge( + dst=dst, + name=name or f"{names.get(src, src)}→{names.get(dst, dst)}", + decision=decision, + guard=conditions.parse(_pick(item, "expression")), + order=_as_int(_pick(item, "order_number", "orderNumber")), + ) + rows = edges.setdefault(src, []) + if not any(item.dst == dst and item.name == edge.name for item in rows): + rows.append(edge) + targets = adjacency.setdefault(src, []) + if dst not in targets: + targets.append(dst) + types.setdefault(src, "manual") + types.setdefault(dst, "manual") + for rows in edges.values(): + # 引擎取出口也是按 (order_number, name) 排,条件分支挑「第一条成立的」靠的就是这个顺序 + rows.sort(key=lambda item: (item.order, item.name)) + return cls( + edges=edges, + adjacency=adjacency, + types=types, + names=names, + guarded=any(item.guard.readable or not item.guard.blank for rows in edges.values() for item in rows), + ) + + # -- 出口 --------------------------------------------------------------- + + def out(self, node_id: str, *, forward_only: bool = False) -> list[_Edge]: + rows = self.edges.get(node_id, []) + return [item for item in rows if item.forward] if forward_only else rows + + def is_choice(self, node_id: str) -> bool: + """这一环的出口由引擎按条件挑一条,而不是由人挑。""" + return self.types.get(node_id) == "choice" + + def steps(self, node_id: str, known: Term, *, forward_only: bool) -> tuple[list[tuple[_Edge, Term]], list[_Edge]]: + """站在这一环上,脚下还真走得通的出口有哪些,走完之后「已知条件」变成什么。 + + ``known`` 是走到这一环已经攒下的那组合取条件(一条走法)。出口条件本身可能是 + 一句「或」,所以同一条出口也可能摊成好几条走法,摊不开的那条直接不往下走。 + 第二个返回值是被条件挡死的出口——判不出「会不会重复」时可以拿它说一句 + 「那条分支要的是另一个值」。 + """ + rows = self.out(node_id, forward_only=forward_only) + if not rows: + return [], [] + bases = (known,) + states = [conditions.decide(item.guard, bases) for item in rows] + dead = [item for index, item in enumerate(rows) if states[index] == conditions.FALSE] + keep = conditions.pick(states, deterministic=self.is_choice(node_id)) + out: list[tuple[_Edge, Term]] = [] + for index in keep: + for merged in conditions.conjoin(bases, rows[index].guard) or (known,): + out.append((rows[index], merged)) + return out, dead + + # -- 可达 --------------------------------------------------------------- + + def reachable(self, node_id: str) -> set[str]: + """从这个环节的出口往后能走到的环节(绕回来的也算,条件一律当可能走)。""" + if node_id not in self._reach: + seen: set[str] = set() + queue = list(self.adjacency.get(node_id, [])) + while queue: + nxt = queue.pop(0) + if nxt in seen: + continue + seen.add(nxt) + if len(seen) > MAX_WALK: + break + queue.extend(self.adjacency.get(nxt, [])) + self._reach[node_id] = seen + return self._reach[node_id] + + def ancestors(self, node_id: str) -> set[str]: + """能走到这个环节的环节(反向可达,不含自己)。""" + if node_id not in self._ancestors: + reverse: dict[str, list[str]] = {} + for src, targets in self.adjacency.items(): + for dst in targets: + reverse.setdefault(dst, []).append(src) + seen: set[str] = set() + queue = list(reverse.get(node_id, [])) + while queue: + nxt = queue.pop(0) + if nxt in seen: + continue + seen.add(nxt) + if len(seen) > MAX_WALK: + break + queue.extend(reverse.get(nxt, [])) + self._ancestors[node_id] = seen + return self._ancestors[node_id] + + def concurrent(self, left: str, right: str) -> bool: + """这两个环节会不会在同一张单上同时展开(并行分支、明细拆分)。 + + 判据是"有一个并行/拆分环节能同时走到两边"。条件分支、或签都带不来这种共同祖先, + 所以互斥分支上的重复在这里就是"根本不会同时走到"。 + """ + shared = self.ancestors(left) & self.ancestors(right) + return any(self.types.get(node_id) in CONCURRENT_TYPES for node_id in shared) + + def order(self, nodes: list["_Node"]) -> dict[str, int]: + """给环节排先后:从开始环节 BFS 的最小跳数,走不到的用画布顺序兜底。""" + depth: dict[str, int] = {} + begin = self.begin() + frontier = [begin] if begin else ([nodes[0].id] if nodes else []) + step = 0 + while frontier and step <= MAX_NODES: + nxt: list[str] = [] + for node_id in frontier: + if node_id in depth: + continue + depth[node_id] = step + nxt.extend(self.adjacency.get(node_id, [])) + step += 1 + frontier = nxt + return {node.id: depth.get(node.id, index + MAX_NODES) for index, node in enumerate(nodes)} + + def begin(self) -> str: + return next((node_id for node_id, kind in self.types.items() if kind == "begin"), "") + + # -- 走到某一环得先满足什么 -------------------------------------------- + + def entry(self, node_id: str) -> tuple[Term, ...]: + """能走到这一环的几条前提(DNF)。``((),)`` 表示没条件或者说不准。 + + 从开始环节往外摊:走到下一条出口就把那条的条件并进来。分支太碎摊不开时补一条 + 「没有前提」而不是硬挑一条——前提写少了会少剪枝(多报一次重复),写多了会少报, + 两个方向里只有前者是可以接受的。 + """ + self._build_entry() + return self._entry.get(node_id, ((),)) + + def _build_entry(self) -> None: + if self._entry_ready: + return + self._entry_ready = True + begin = self.begin() or next(iter(self.edges), "") + if not begin: + return + self._entry[begin] = ((),) + queue = [begin] + rounds = 0 + seen_edges = 0 + while queue and rounds < MAX_NODES * 4 and seen_edges < MAX_WALK: + rounds += 1 + nxt_queue: list[str] = [] + for src in queue: + known = self._entry.get(src, ((),)) + for edge in self.out(src): + seen_edges += 1 + merged = conditions.conjoin(known, edge.guard) + if merged == known and not edge.guard.always: + merged = known # 摊不开:这条前提别当成已知事实 + if merged == (): # 与已知前提对不上:这条路走不到 + continue + current = self._entry.get(edge.dst) + if current is None: + self._entry[edge.dst] = merged + nxt_queue.append(edge.dst) + continue + added = tuple(item for item in merged if item not in current) + if not added: + continue + combined = current + added + if len(combined) > MAX_ENTRY_TERMS: + # 摊不开了:补一条「没前提」,让下游一律按说不准处理 + combined = (((),),) if ((),) not in combined else combined + if combined != current: + self._entry[edge.dst] = combined + nxt_queue.append(edge.dst) + queue = nxt_queue + + # -- 两个结论 ----------------------------------------------------------- + + def possible(self, start: str, target: str) -> _Walk: + """这张单有没有可能先后走到 ``start`` 和 ``target``。 + + 退回也算路(退回去重走一遍真的会签两次)。只有「所有走法都在条件上自相矛盾」 + 才敢说走不到;读不懂的条件、没走完的分支一律当成还可能走。 + """ + if target not in self.reachable(start): + return _Walk(False) + if not self.guarded: + # 整张图一条条件都没写:条件这一层剪不掉任何路,结构可达就是可达,不必再走一趟 + return _Walk(True) + return self._search(start, target, forward_only=False) + + def must_pass(self, start: str, target: str) -> _Walk: + """从 ``start`` 往前走,是不是每条走得通的路都躲不开 ``target``。 + + 被条件挡死的出口不算路;退回路由不算路;成环、算超预算、走到头没遇到, + 一律算没证成——跟 ``lookahead`` 的保守口径一致,不敢断定就别跳。 + """ + return self._search(start, target, forward_only=True) + + def _search(self, start: str, target: str, *, forward_only: bool) -> _Walk: + """按条件走一趟图,``forward_only`` 决定问的是哪一种: + + - ``False``:有没有一条走得通的路能到 ``target``(有一条就算,全堵死才算堵死); + - ``True``:是不是每条走得通的路都经过 ``target``(有一条躲得开就不算必经)。 + + 两种走法共用一趟递归,只是「说不准」时往哪边靠:问「能不能」时不敢说不可能, + 问「必经吗」时不敢说一定——判不出来的那一支在两种问题里都站在保守的一侧。 + """ + blockers: list[Blocker] = [] + pruned: list[tuple[str, _Edge]] = [] # 被条件判死的出口,回头解释「为什么走不到」全靠它 + budget = [MAX_WALK] + memo: dict[tuple[str, tuple[Term, ...]], bool | None] = {} + + def walk(node_id: str, known: Term, stack: frozenset[str]) -> bool | None: + if node_id == target: + return True + if budget[0] <= 0 or node_id in stack: + return None # 没看完或者成环:这一支说不准 + key = (node_id, known) + if key in memo: + return memo[key] + budget[0] -= 1 + steps, dead = self.steps(node_id, known, forward_only=forward_only) + pruned.extend((node_id, item) for item in dead) + if not steps: + memo[key] = False + return False + verdicts = [walk(edge.dst, known_after, stack | {node_id}) for edge, known_after in steps] + if forward_only: + out: bool | None + if any(item is False for item in verdicts): + out = False + elif any(item is None for item in verdicts): + out = None + else: + out = True + elif any(item is True for item in verdicts): + out = True + elif any(item is None for item in verdicts): + out = None + else: + out = False + memo[key] = out + if forward_only and out is False: + # 必经没证成:点名「这条路根本不经过他」的那几条出口,一句「有条分支」太含糊 + for edge, _ in steps: + if self.leads_to(edge.dst, target): + continue # 这条路本来就要经过他,不算挡路 + if not self.branchy(node_id): + continue # 只有一条出口的环节,抱怨它没意义 + blockers.append(self._blocker(node_id, edge)) + return out + + known = self.entry(start) + verdicts = [walk(start, term, frozenset()) for term in known] + # 有一条支路没判明白,这一趟就只能算「判不准」:问必经时不敢说一定,问可达时不敢说不可能 + unknown = any(item is None for item in verdicts) + if forward_only: + ok = all(item is True for item in verdicts) + else: + ok = any(item is True for item in verdicts) + if not ok: + # 走不到:只有「本来通得到目标、却被条件判死」的那几条出口解释了这件事 + for node_id, edge in pruned: + if self.leads_to(edge.dst, target): + blockers.append(self._blocker(node_id, edge)) + return _Walk(ok, blockers[:MAX_BLOCKERS], _entry_note(known), unknown) + + def leads_to(self, node_id: str, target: str) -> bool: + """从这一环(含它自己)往前走,有没有可能走到 ``target``。""" + return node_id == target or target in self.reachable(node_id) + + def branchy(self, node_id: str) -> bool: + """这一环是不是个真正的分叉:只有一条出口的环节没什么好抱怨的。""" + return len(self.out(node_id, forward_only=True)) > 1 + + def _blocker(self, node_id: str, edge: _Edge) -> Blocker: + """一条挡路的出口:环节名、分支名、它要看哪个字段。""" + return { + "at": self.names.get(node_id, node_id), + "route": edge.name, + "to": self.names.get(edge.dst, edge.dst), + "hint": conditions.hint(edge.guard), + "detail": edge.guard.describe(), + "blank": edge.guard.blank, + "goback": not edge.forward, + } + + +def _entry_note(known: tuple[Term, ...]) -> str: + """把「走到起点得满足什么」说成一句人话。""" + if not known or known == ((),): + return "" + readable = [item for item in known if item] + if not readable: + return "" + if len(readable) < len(known): + return "" # 其中有一条没有前提:等于说不准,别装作判出来了 + parts = [" 且 ".join(lit.describe() for lit in term) for term in readable] + text = " 或者 ".join(parts) + return text if len(text) <= 120 else text[:117] + "…" + + +def audit( + db: Session, + *, + process_id: str, + activities: list[dict] | None = None, + routes: list[dict] | None = None, + approval: dict | None = None, + as_identity: str = "", +) -> dict: + """按画布上这份设计算一遍重复审批人;``activities``/``routes``/``approval`` 缺省时读库里的设计稿。 + + ``as_identity`` 是试算用的样例身份:发起人上级、部门负责人这类找人方式没有身份就 + 算不出来,设计器默认传当前登录人(多半就是这个流程的负责人自己)。 + """ + from ..engine import engine as flow # 延迟导入:engine 反过来 import 了 service 这一堆 + + rows_activities, rows_routes, process_approval = _draft(db, process_id, activities, routes, approval) + graph = _Graph.build(rows_activities, rows_routes) + nodes = _build_nodes(db, process_id, rows_activities, process_approval, as_identity, flow, graph) + + by_person: dict[str, list[_Node]] = {} + for node in nodes: + if node.manual: + for person in node.persons: + by_person.setdefault(person, []).append(node) + + order = graph.order(nodes) + impasses: list[dict] = [] + groups = [ + _group(node_list, graph, order, person, impasses) + for person, node_list in by_person.items() + if len(node_list) > 1 + ] + groups.sort(key=lambda item: (-item["doubles"], -item["unclear"], -len(item["nodes"]))) + # 同一个人、同一对环节,正反两个方向各判过一次,合成一条说就够了 + impasses = _tidy_impasses(impasses) + + manual = [node for node in nodes if node.manual] + return { + "process": process_id, + "policy": flow.repeat_policy({}, process_approval), + "ahead_scope": flow.ahead_scope({}, process_approval), + "keep_one": bool(process_approval.get("dedupAheadKeepOne")), + "as_identity": as_identity, + "as_identity_name": org.ref_for(db, as_identity).person_name if as_identity else "", + "nodes": [_node_row(node) for node in manual], + "groups": groups, + "impasses": impasses, + "stats": { + "manual": len(manual), + "resolved": sum(1 for node in manual if node.persons), + "people": len(by_person), + "groups": len(groups), + "open": sum(1 for item in groups if item["verdict"] == VERDICT_OPEN), + "watch": sum(1 for item in groups if item["verdict"] == VERDICT_WATCH), + "branch": sum(1 for item in groups if item["verdict"] == VERDICT_BRANCH), + "conditional": sum(1 for item in groups if item["conditional"]), + "impossible": len(impasses), + }, + } + + +def _tidy_impasses(rows: list[dict]) -> list[dict]: + """同一对环节正反两向各判过一次,只留先出现的那条:说一遍就够了。""" + seen: set[frozenset[str]] = set() + out: list[dict] = [] + for item in rows: + key = frozenset({item["from"], item["to"]}) + if key in seen: + continue + seen.add(key) + out.append(item) + return out + + +def _node_row(node: _Node) -> dict: + """环节那一侧的对外形状:设计器拿它画徽标、说清这一环生效的是哪一档。""" + return { + "id": node.id, + "name": node.name, + "mode": node.mode, + "policy": node.policy, + "inherited": node.inherited, + "skip_starter": node.skip_starter, + "skip_approved": node.skip_approved, + "skip_ahead": node.skip_ahead, + "ahead_scope": node.scope, + "first": node.first, + "dynamic": node.dynamic, + "has_skip_rules": node.has_skip_rules, + "has_must_rules": node.has_must_rules, + "unknown": node.unknown, + "notes": node.notes, + "persons": [{"person": pid, "name": name} for pid, name in node.persons.items()], + } + + +def _as_int(value: object) -> int: + """画布传来的序号可能是字符串,也可能压根没带。""" + try: + return int(value or 0) + except (TypeError, ValueError): + return 0 + + +def _pick(item: dict, *keys: str) -> object: + """下划线 / 驼峰两种写法都认:设计保存那套接口本来就是两种通吃。""" + for key in keys: + if key in item: + return item[key] + return "" + + +# --------------------------------------------------------------------------- +# 输入整形 +# --------------------------------------------------------------------------- + + +def _draft( + db: Session, + process_id: str, + activities: list[dict] | None, + routes: list[dict] | None, + approval: dict | None, +) -> tuple[list[dict], list[dict], dict]: + """画布传来的设计优先,没传的那部分回退到库里的设计稿。""" + if activities is None: + activities = [ + { + "id": row.id, + "type": row.type, + "name": row.name, + "config": dict(row.config or {}), + "order_number": row.order_number, + } + for row in db.execute( + select(models.Activity) + .where(models.Activity.process == process_id) + .order_by(models.Activity.order_number) + ).scalars().all() + ] + if routes is None: + routes = [ + { + "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) + ).scalars().all() + ] + if approval is None: + process = db.get(models.Process, process_id) + approval = dict((process.approval_config or {}) if process else {}) + return _as_list(activities), _as_list(routes), dict(approval or {}) + + +def _as_list(rows: object) -> list[dict]: + if not isinstance(rows, list): + return [] + return [dict(item) for item in rows if isinstance(item, dict)] + + +def _build_nodes( + db: Session, + process_id: str, + activities: list[dict], + approval: dict, + as_identity: str, + flow, + graph: _Graph, +) -> list[_Node]: + """把画布上的环节翻成体检用的节点,顺手把每一环的人试算出来。""" + nodes: list[_Node] = [] + for item in activities[:MAX_NODES]: + config = dict(item.get("config") or {}) + node = _Node( + id=str(item.get("id") or ""), + name=str(item.get("name") or "未命名环节"), + type=graph.types.get(str(item.get("id") or ""), str(item.get("type") or "manual")), + config=config, + mode=str(config.get("mode") or "any"), + has_skip_rules=bool(config.get("skipRules")), + has_must_rules=bool(config.get("mustRules")), + first=bool(config.get("first")), + ) + if node.manual: + _resolve_rules(db, node, flow) + node.policy = flow.repeat_policy(config, approval) + node.scope = flow.ahead_scope(config, approval) + node.skip_starter, node.skip_approved, node.skip_ahead = flow.approval_flags(config, approval) + # 两个方向都没在环节上钉过=整档跟着流程默认;钉过任何一个就自己说了算 + node.inherited = config.get("skipApproved") is None and config.get("skipAhead") is None + _resolve_persons(db, node, as_identity) + nodes.append(node) + return nodes + + +def _resolve_rules(db: Session, node: _Node, flow) -> None: + """环节上配的免审 / 必批条件:可能碰到哪几个人,先按人备好。 + + 只问「这条规则碰的是哪几个人」,不去算它的条件式——那一层要等这张单的表单填出来 + 才算得出来,设计期硬算就是把猜测当成事实。名单算不出来(带脚本、按发起人/上级找人、 + 名字解析不到)就当碰得到所有人:这里放错一次手,代价是一整环没人批, + 比让人多签一次重得多。 + """ + node.drop_reach = flow.rule_reach(db, flow.skip_rules(node.config), scope_whole=True) + node.must_reach = flow.rule_reach(db, flow.must_rules(node.config)) + if node.drop_reach["unknown"]: + node.notes.append("这一环配了免审条件,具体免掉谁要等这一单的表单填了才知道") + + +def _resolve_persons(db: Session, node: _Node, as_identity: str) -> None: + """这一环现在会落到谁身上。 + + ``preview_selectors`` 拿样例身份试算,够画出来给人看;但"这一单一定是他"是另一回事: + 发起人上级、上一环节处理人、表单字段、找人脚本都得等单子跑起来才定得下来, + 所以这里自己再判一次 ``dynamic``,只把按身份/人员/岗位/分组/部门配的当硬结论。 + """ + rows = [item for item in (node.config.get("taskValues") or []) if isinstance(item, dict)] + script = str(node.config.get("taskScript") or "").strip() + kinds = {org.normalize_kind(item.get("type")) for item in rows} + if not rows and not script: + node.notes.append("这一环还没配找人方式,运行时按兜底设置处理") + return + node.dynamic = bool(kinds & RUNTIME_KINDS) or bool(script) + preview = org.preview_selectors(db, rows, as_identity, script) + node.unknown = [str(item) for item in preview.get("unknown") or []] + node.notes.extend(str(item) for item in preview.get("notes") or []) + for brief in preview.get("identities") or []: + identity = str(brief.get("distinguished_name") or "") + if not identity: + continue + ref = org.ref_for(db, identity) + if not ref.person: + continue + node.persons.setdefault( + ref.person, ref.person_name or str(brief.get("person_name") or "") or ref.name or ref.person + ) + if script: + node.notes.append("找人脚本要等表单填完才算得出人,这里的名单只是当场试算") + elif node.dynamic and bool(kinds & org.RELATION_KINDS) and as_identity: + node.notes.append(f"按「{org.ref_for(db, as_identity).person_name}」试算的,换个人发起可能就不是这批人") + elif node.dynamic: + node.notes.append("这一环的人要等这一单跑起来才定得下来") + + +# --------------------------------------------------------------------------- +# 判定 +# --------------------------------------------------------------------------- + + +def _group( + nodes: list[_Node], graph: _Graph, order: dict[str, int], person: str, impasses: list[dict] +) -> dict: + """一个人身上这一串重复环节:逐对判一遍,再汇成一组结论。""" + chain = sorted(nodes, key=lambda node: (order.get(node.id, 0), node.id)) + pairs: list[dict] = [] + branch = 0 + for first in chain: + for later in chain: + if first is later: + continue + hit = _pair(person, first, later, graph, impasses) + if hit is None: + branch += 1 # 互斥分支或按条件走不到一起:这一单不会同时走到,不算一次重复 + continue + pairs.append( + { + "from": first.id, + "from_name": first.name, + "to": later.id, + "to_name": later.name, + "outcome": hit.outcome, + "certain": hit.certain, + "settled": hit.settled, + "cause": hit.cause, + "reason": hit.reason, + "conditional": hit.conditional, + "entry": hit.entry, + "blockers": hit.blockers, + } + ) + skipped, worries, roles = _roles(chain, pairs) + doubles = [item for item in pairs if item["outcome"] == PAIR_DOUBLE and item["certain"]] + unclear = [item for item in pairs if _disposition(item) == "watch"] + if doubles: + verdict = VERDICT_OPEN + elif unclear: + verdict = VERDICT_WATCH + elif pairs: + verdict = VERDICT_COVERED + else: + verdict = VERDICT_BRANCH + return { + "person": person, + "name": nodes[0].persons.get(person, person), + "dynamic": any(node.dynamic for node in chain), + "conditional": any(item["conditional"] for item in pairs), + "verdict": verdict, + "nodes": [ + { + "id": node.id, + "name": node.name, + "policy": node.policy, + "inherited": node.inherited, + "dynamic": node.dynamic, + "role": roles.get(node.id, "sign"), + "note": _role_note(roles.get(node.id, "sign"), skipped.get(node.id) or worries.get(node.id)), + } + for node in chain + ], + "pairs": pairs, + "doubles": len(doubles), + "unclear": len(unclear), + "branch": branch, + "node_ids": [node.id for node in chain], + } + + +def _pair(person: str, first: _Node, later: _Node, graph: _Graph, impasses: list[dict]) -> _Pair | None: + """同一个人先后出现在两个环节:这一对会不会只签一次,凭什么。 + + 先问往后看、再问往回看——顺序和引擎一致:前瞻跳掉的那一环不产生已办, + 所以往后看成立时轮不到往回看表态。返回 ``None`` 表示这一对构不成重复。 + + 问图的时候分两问:``possible`` 问「这一单会不会两次都走到」,``must_pass`` 问 + 「往后走是不是每一条都躲不开他」。前一问答"不会"就是压根没有重复,后一问答"躲得开" + 就是这一对还得靠策略管住——两问都得把路由上写的条件算进去,只盯着图的形状, + 配得再死的条件分支也只会换来一句「有一条分支不经过他」。 + + 判成"会签两次"时 ``cause`` 要说清是哪一档没管住:是压根没配(``policy_off``)、 + 往后看开着的但不敢断定(``ahead_unproven``)、还是前面那环躲不掉(``first_node``)—— + 界面上一键修法挑哪一种,全看这一句说得准不准。 + """ + if later.id not in graph.reachable(first.id): + if not graph.concurrent(first.id, later.id): + return None + # 并行/拆分把两支同时展开:两边都真的派待办,去重两头都够不着,只能提醒 + return _Pair( + PAIR_UNKNOWN, False, False, "两个环节会同时展开,运行时两边都会派待办", CAUSE_CONCURRENT + ) + reach = graph.possible(first.id, later.id) + if not reach.ok and not reach.unknown: + # 条件对不上:这一单不可能两次都走到,压根就不是重复。说清是哪几条出口挡的路, + # 免得设计者对着两个环节想不通「明明看着会签两次」。 + impasses.append( + { + "person": person, + "name": first.persons.get(person, person), + "from": first.id, + "from_name": first.name, + "to": later.id, + "to_name": later.name, + "entry": reach.entry, + "blockers": reach.blockers, + "reason": _impossible_reason(first, later, reach), + } + ) + return None + dynamic = first.dynamic or later.dynamic + missed = "" # 往前看没跳成的原因,落到"签两次"上时就是这一对的 cause + blockers: list[dict] = [] + if first.skip_ahead: + if first.first: + # 起草环节那张待办是经办人在这张单上的落脚点,往后看不许把它吞掉 + missed = CAUSE_FIRST_NODE + elif first.scope == SCOPE_ANY: + # 激进口径只说"有一条路可能用到他",名单一动结论就跟着动,不敢算管定 + return _Pair( + PAIR_EARLIER, + not dynamic, + not dynamic, + "后面还要他批,前面这一环自动跳过", + CAUSE_COVERED, + entry=reach.entry, + ) + else: + must = graph.must_pass(first.id, later.id) + blockers = must.blockers + if must.ok and later.counts_as_certain(person): + # 这条结论只依赖后面那一环(必经 + 整环名单算不算一定批),前面那环动态无所谓 + return _Pair( + PAIR_EARLIER, + not dynamic, + not later.dynamic, + _ahead_reason(), + CAUSE_COVERED, + entry=reach.entry, + ) + else: + # 往前看开着却不敢断定后面躲不开他:条件分支、或签、免审条件都会让"一定"不成立 + missed = CAUSE_AHEAD_UNPROVEN + uncertain_only = must.ok # 必经证成了,是后面那一环自己说不准 + if later.skip_approved: + if later.must_keep(person): + return _Pair( + PAIR_LATER, + False, + False, + "前面已经批过,后面这一环本来会自动跳过,可这一环配了必批规则,可能还是把他留下来", + CAUSE_MUST_RULE, + entry=reach.entry, + ) + # 往回看认的是"他在这张单上真批过一次",运行时名单换成谁都管得住 + return _Pair( + PAIR_LATER, not dynamic, True, "前面已经批过,后面这一环自动跳过", CAUSE_COVERED, entry=reach.entry + ) + if missed: + if missed == CAUSE_FIRST_NODE: + reason = "前面那环是起草环节,「后面还要他批」不许跳,他会签两次" + if first.skip_starter: + reason += ";这一环开了「跳过发起人」,这一单由他本人发起时那一次不用签" + else: + reason = _unproven_reason(later, blockers, uncertain_only=uncertain_only, unknown=must.unknown) + return _Pair(PAIR_DOUBLE, not dynamic, False, reason, missed, blockers, reach.entry) + return _Pair( + PAIR_DOUBLE, + not dynamic, + False, + "两档策略都没管到这一对,他会签两次", + CAUSE_POLICY_OFF, + entry=reach.entry, + ) + + +def _unproven_reason( + later: _Node, blockers: list[dict], *, uncertain_only: bool = False, unknown: bool = False +) -> str: + """「往后看不敢跳」要说出是哪儿挡的,光说「有一条分支」等于什么都没说。""" + if uncertain_only: + return ( + f"往后看没敢跳:后面每一条路都过「{later.name}」,可这一环是或签或配了免审条件," + f"说不准这一单是不是真轮到他批,他会签两次" + ) + if unknown: + return "往后看没敢跳:后面的路绕来绕去(或者环节太多没敢走完),判不出必经他,他会签两次" + if not blockers: + return f"往后看没敢跳:「{later.name}」是不是真轮到他批说不准,他会签两次" + parts = [ + f"「{item['at']}」还有一条「{item['route']}」→「{item['to']}」不经过他" + + ("" if item["blank"] else f"(这条要看 {item['hint']})") + for item in blockers + ] + return "往后看没敢跳:" + ";".join(parts) + ",他会签两次" + + +def _ahead_reason() -> str: + """跳得掉的那一句:分支条件把后面的路收窄成一条,才敢断定必经他。 + + 「按哪条前提收窄的」另放在 ``entry`` 字段里,界面上单独一行显示,别挤进这句结论。 + """ + return "后面每一条路都要他批,前面这一环自动跳过" + + +def _impossible_reason(first: _Node, later: _Node, reach: _Walk) -> str: + """走不到一起的这一对,凭哪几条出口说的。""" + if reach.entry: + head = f"走到「{first.name}」要满足 {reach.entry}" + else: + head = f"走到「{first.name}」这条路本身就没写条件" + if not reach.blockers: + return f"{head};从这个环节往前走,通往「{later.name}」的出口都在条件下堵死了" + parts = [ + f"「{item['at']}」通往「{item['to']}」的那条「{item['route']}」要 {item.get('detail') or item['hint']}" + for item in reach.blockers + ] + return f"{head},而 " + ";".join(parts) + "——两边对不上,这一单不会两次都走到" + + +def _settled(pair: dict) -> bool: + """这一对算不算"不用再看了":管没管住这件事,跟运行时换成谁无关。 + + 判定在 :class:`_Pair` 里就分开了两件事——名单是不是当场定得下来(``certain``), + 与结论管不管得住(``settled``)。总评只看后者:名单要试算这一条仍然带着 + "这条是试算"标露在人前,但不该把一档明明管得住的配置报成"要人确认"。 + """ + return bool(pair.get("settled")) + + +def _disposition(pair: dict) -> str: + """这一对折回环节上的落法:``skip`` 会被自动跳过 / ``double`` 照旧要签 / ``watch`` 判不准。""" + outcome = pair["outcome"] + if outcome == PAIR_UNKNOWN: + return "watch" + if outcome == PAIR_DOUBLE: + return "double" if pair["certain"] else "watch" + return "skip" if _settled(pair) else "watch" + + +def _roles(chain: list[_Node], pairs: list[dict]) -> tuple[dict[str, dict], dict[str, dict], dict[str, str]]: + """把逐对结论折回环节上:这一环对这个人到底是要批,还是会被自动跳过。""" + skipped: dict[str, dict] = {} + worries: dict[str, dict] = {} + doubles: set[str] = set() + for item in pairs: + landing = _disposition(item) + if landing == "double": + doubles.update({item["from"], item["to"]}) + elif landing == "skip": + skipped.setdefault(item["to"] if item["outcome"] == PAIR_LATER else item["from"], item) + else: + worries.setdefault(item["from"], item) + worries.setdefault(item["to"], item) + roles: dict[str, str] = {} + for node in chain: + if node.id in doubles: + roles[node.id] = "double" + elif node.id in skipped: + roles[node.id] = "skip" + elif node.id in worries: + roles[node.id] = "watch" + else: + roles[node.id] = "sign" + return skipped, worries, roles + + +def _role_note(role: str, pair: dict | None) -> str: + """这一环的结论要说人话:凭什么跳过、凭什么还让他签、凭什么判不准。""" + if role == "skip" and pair is not None: + other = pair["to_name"] if pair["outcome"] == PAIR_EARLIER else pair["from_name"] + return f"{pair['reason']}(另一处:{other})" + if role == "double": + return "这一环照旧要他批,而前面已经让他批过一次" + if role == "watch" and pair is not None: + if pair["cause"] == CAUSE_CONCURRENT: + return "这一环会不会和别的那一环同时走到,静态判不出来" + if pair["cause"] == CAUSE_MUST_RULE: + return "这一环配了必批规则,去重保不齐把他留下来再签一次" + return "这一环落到谁身上要等这张单跑起来才定得下来,跳不跳也就跟着判不准" + return "" diff --git a/backend/app/service/drafts.py b/backend/app/service/drafts.py new file mode 100644 index 0000000..5a18ec4 --- /dev/null +++ b/backend/app/service/drafts.py @@ -0,0 +1,581 @@ +"""从接口一句话建出一张流程草稿:认流程、列参数、校验数据、落库,全收在这一处。 + +为什么单独一个 service 而不是写在接口里:同一件"建草稿"现在有三个入口——发起页 +保存草稿、开放平台替外部系统建单、脚本铺演示数据。标题口径、发起范围、明细表整型 +这三件事只要有两处各写一遍,迟早会出现"页面存的草稿和接口存的草稿打开来不一样"。 + +三条刻意的取舍: + +* **流程可以按名字叫**。``oa_process.id`` 是那串 32 位十六进制,是给机器看的, + 而调用方手里只有"创建一个印章使用申请"这句人话,所以 id / 别名 / 名称 / + 「分类/流程名」/ 关键词五种写法都认。但**歧义时宁可报错列出候选**,绝不替调用方 + 猜一条流程:草稿建到别的流程上,比建失败难查十倍。 +* **草稿不卡必填**。草稿存在的意义就是"先存一半",缺字段是常态不是错误,缺哪几项 + 只作为提醒回给人看;但**取值本身不合法**(选项值早就不在字典里、级联没选到末级) + 照样说清楚——这种值存下去,到发起那一刻一定会挡人,现在说是省一趟返工。 +* **认不出来的字段不丢**。引擎发起时也是原样保留表单里没有的键(变量、系统写的标记 + 都在里面,见 ``engine._apply_form_runtime``),这里替调用方丢掉只会让脚本莫名其妙 + 少数据,所以只提示、不删除。 + +错误直接抛 :mod:`app.envelope` 的 ``ApiError``:这个 service 只服务 HTTP 入口, +"找不到流程""不在发起范围里"本来就是界面上要念出来的那句话,再包一层自定义异常 +让三处调用各自翻译一遍,只是把同一句中文抄三次。 +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Any, Iterable, Sequence + +from sqlalchemy import or_, select +from sqlalchemy.orm import Session + +from .. import models, serializers +from ..envelope import bad_request, forbidden +from . import autofill, dicts, formruntime, starters, titles + +#: 页面里「发起流程」那条路由(``frontend/src/router/index.ts`` 的 ``start``)。 +#: 接口把它连同 process / draft 一起回给调用方,省得每份对接文档各抄一遍拼法。 +START_PAGE = "/start" +#: 「分类/流程名」这种一行说清两个信息的写法。 +SEPARATOR = "/" +#: 参数清单里一条字段最多回多少个选项:字典项上千条时别把响应撑爆。 +MAX_OPTIONS = 50 +#: 报错时最多列出几个候选流程。 +MAX_CANDIDATES = 6 +#: 纯排版的字段类型:没有值也不接收值,参数清单里列出来只是噪音。 +LAYOUT_TYPES = ("divider", "description") +#: 开始环节的 type 取值,与 ``engine.definition.ACTIVITY_BEGIN`` 同一个字面量; +#: 这里不 import 引擎(引擎反过来 import 本模块,会绕成循环)。 +BEGIN_ACTIVITY = "begin" + + +# 下面这些函数里的 actor 一律是 engine.Actor:页面用 deps.actor_of(user) 拿, +# 开放平台用 OpenContext.as_actor(db, identity) 拿,两边本来就是同一个形状 +# (person_id / person_name / identity / unit / is_admin),再造一层 Owner 只是给 +# 同一个人发第二个户口。标题规则与发起范围都直接吃它,于是「谁建的草稿」和 +# 「谁发起的这张单」在代码里是同一个人,不会各算一遍。 +@dataclass +class Inspection: + """一次数据体检的结果:整理后的数据 + 三类要告诉调用方的话。 + + 三类分开存而不是揉成一句,是因为界面对它们的处理不一样:``unknown`` 与 + ``missing`` 是"这样存下去没问题",``problems`` 是"存下去到发起时会挡你"。 + """ + + data: dict[str, Any] = field(default_factory=dict) + #: 表单里没有的键:照样存,只是发起时不会被当成表单值。 + unknown: tuple[str, ...] = () + #: 这个环节必填但还没填的字段标题。 + missing: tuple[str, ...] = () + #: 现在看着没事、发起时一定过不了的取值问题。 + problems: tuple[str, ...] = () + #: 明细表里整行没填、已经丢掉的行数(字段标题 -> 行数)。 + dropped: tuple[tuple[str, int], ...] = () + + @property + def ok(self) -> bool: + return not (self.unknown or self.missing or self.problems or self.dropped) + + @property + def notices(self) -> list[str]: + """给人看的一版提醒,顺序按"要紧的先说"。""" + notices: list[str] = [] + if self.problems: + notices.append("发起时会被表单校验挡住:" + ";".join(self.problems[:6])) + if self.missing: + notices.append( + f"还差 {len(self.missing)} 项才提交得了:{'、'.join(self.missing[:12])}(草稿不拦,填全了再发起)" + ) + if self.unknown: + notices.append( + f"表单里没有这几个字段,草稿照样存着,但发起时不会当成表单值:{'、'.join(self.unknown[:12])}" + ) + for label, count in self.dropped: + notices.append(f"「{label}」里有 {count} 行整行没填,已经丢掉") + return notices + + +# --------------------------------------------------------------------------- +# 认流程:五种写法都认,歧义绝不替人猜 +# --------------------------------------------------------------------------- + + +def category_clause(value: str): + """分类这一栏既可以填 id 也可以填中文名。""" + text = str(value or "").strip() + return or_(models.Process.category == text, models.Process.category_name == text) + + +def _name_clause(value: str): + text = str(value or "").strip() + return or_(models.Process.name == text, models.Process.alias == text) + + +def _describe(rows: Sequence[models.Process]) -> str: + """把候选流程念成一句话,用于「到底要哪一条」的报错。""" + parts = [ + f"{row.name}(分类:{row.category_name or '未分类'})" + for row in list(rows)[:MAX_CANDIDATES] + ] + if len(rows) > MAX_CANDIDATES: + parts.append(f"等 {len(rows)} 条") + return "、".join(parts) + + +def _pick(db: Session, label: str, rows: Sequence[models.Process]) -> models.Process | None: + """命中一条就用,命中多条就把候选念回去让人改名。""" + if not rows: + return None + if len(rows) > 1: + raise bad_request( + f"「{label}」对上了 {len(rows)} 条流程:{_describe(rows)}。" + f"请用「分类/{rows[0].name}」这种写法,或直接传流程 id", + reason="PROCESS_AMBIGUOUS", + ) + return rows[0] + + +def _rows(db: Session, *clauses) -> list[models.Process]: + stmt = select(models.Process) + for clause in clauses: + if clause is None: + continue + stmt = stmt.where(clause) + return list(db.execute(stmt.order_by(models.Process.order_number, models.Process.name)).scalars().all()) + + +def _usable(process: models.Process, published_only: bool) -> models.Process: + if published_only and (not process.enabled or not process.published): + raise bad_request( + f"流程「{process.name}」还没有发布,不能创建草稿", + reason="PROCESS_NOT_PUBLISHED", + ) + return process + + +def resolve_process( + db: Session, ref: object, *, category: str = "", published_only: bool = True +) -> models.Process: + """按调用方给的任何一种写法找到那条流程。 + + 顺序从最确切到最宽松:id → 全名/别名 → 关键词模糊。撞名时宁可问清楚, + 绝不替调用方挑一条——草稿建到别的流程上,比建失败难查得多。 + + 「分类/流程名」不是一档独立的匹配,只是把分类限定写成了一行里:拆出来之后照样走 + 那三档,所以「行政办公/用印」这种半截关键词也认得出来。分类单独用 ``category`` + 参数传是同一件事,两处都给了以 ``category`` 为准。 + + ``published_only=False`` 是给设计器/脚本留的口子:还没发布的流程也想存张草稿 + 试试水时用,页面与开放平台一律走默认的 True。 + """ + value = str(ref or "").strip() + if not value: + raise bad_request( + "要说清楚建哪一类流程:流程 id、名称、别名,或者「分类/流程名」都认", + reason="PROCESS_REQUIRED", + ) + scoped = str(category or "").strip() + if SEPARATOR in value: + head, _, rest = value.partition(SEPARATOR) + if head.strip() and rest.strip(): + scoped = scoped or head.strip() + value = rest.strip() + row = db.get(models.Process, value) + if row is not None: + return _usable(row, published_only) + scope = category_clause(scoped) if scoped else None + exact = _pick(db, value, _rows(db, _name_clause(value), scope)) + if exact is not None: + return _usable(exact, published_only) + like = f"%{value}%" + fuzzy = _rows(db, or_(models.Process.name.like(like), models.Process.alias.like(like)), scope) + if not fuzzy: + raise bad_request( + f"没有名为「{value}」的流程" + (f",分类「{scoped}」里也没有" if scoped else ""), + reason="PROCESS_NOT_FOUND", + ) + return _usable(_pick(db, value, fuzzy), published_only) + + +def guard_startable(db: Session, process: models.Process, actor) -> None: + """发起范围这一关。与 ``POST /job`` 用的是同一把尺子(见 ``service/starters.py``)。 + + 以前存草稿不看这一眼,等于"发不起单的人也能先囤一张草稿"——界面上不报错, + 但他在发起页根本找不到这条流程,点提交才会被弹回来。既然现在把建草稿做成了一个 + 对外接口,就把这关补上,别让接口比页面松。 + """ + if starters.allowed(db, process, identities=starters.actor_identities(db, actor), is_admin=actor.is_admin): + return + raise forbidden( + f"「{process.name}」限定了可发起的人员,{actor.person_name or '这个人'}不在发起范围内", + reason="START_FORBIDDEN", + ) + + +def creatable( + db: Session, *, keyword: str = "", category: str = "", published_only: bool = True +) -> list[models.Process]: + """能拿来建草稿的流程清单(已发布,可按关键词与分类筛),按界面上的顺序排好。 + + 「这个人发不发得起」不在这里判——那要拿登录人的身份,交给调用方用 + ``starters.startable_map`` 过一次。清单本身只按"流程发没发布"筛: + 没发布的流程连发起页都不该出现,草稿自然也算不上。 + """ + stmt = select(models.Process) + if published_only: + stmt = stmt.where(models.Process.enabled.is_(True), models.Process.published.is_(True)) + if category: + stmt = stmt.where(category_clause(category)) + if keyword: + like = f"%{keyword}%" + stmt = stmt.where(or_(models.Process.name.like(like), models.Process.alias.like(like))) + return list(db.execute( + stmt.order_by(models.Process.order_number, models.Process.name) + ).scalars().all()) + + +# --------------------------------------------------------------------------- +# 参数清单:让调用方知道"对应的参数"到底是哪几个 +# --------------------------------------------------------------------------- + + +def form_fields(db: Session, process: models.Process) -> list[dict]: + """发起时要填的那张表单的字段清单。 + + 引擎发起时用的就是流程的默认表单(``engine.create_job`` 里的 ``begin_fields``), + 草稿当然按同一张表单算参数,不能自己去猜环节上挂的那一张。 + """ + return autofill.form_fields(db, process.latest_form) + + +def begin_perms(db: Session, process: models.Process) -> dict[str, str]: + """开始环节的字段权限:必填与只读的最终口径都在这里,不在字段自己身上。""" + begin = db.execute( + select(models.Activity) + .where(models.Activity.process == process.id, models.Activity.type == BEGIN_ACTIVITY) + .order_by(models.Activity.order_number) + ).scalars().first() + return formruntime.perms_of(begin.config if begin is not None else {}) + + +def _options(field: dict, cache: dicts.DictCache) -> tuple[list[dict], str]: + """这一格的合法取值。返回 (选项, 选项来源说明);来源为空表示没有选项约束。""" + code = str(field.get("dictCode") or "").strip() + if code: + items = cache.items(code) + source = f"字典 {code}" + else: + raw = field.get("options") + if not isinstance(raw, list) or not raw: + return [], "" + items = [item for item in raw if isinstance(item, dict)] + source = "表单内置选项" + out = [ + {"value": dicts.option_value(item), "label": dicts.option_label(item)} + for item in items + if dicts.option_value(item) + ] + return out[:MAX_OPTIONS], source + + +def _columns(field: dict, cache: dicts.DictCache) -> list[dict]: + """明细表的列:结构不同(值是一个数组,每个元素一行),单独说清楚。""" + out: list[dict] = [] + for column in formruntime.columns_of(field): + key = str(column.get("key") or "") + if not key: + continue + options, source = _options(column, cache) + item: dict[str, Any] = { + "key": key, + "label": str(column.get("label") or key), + "type": str(column.get("type") or "text"), + "required": bool(column.get("required")), + } + if options: + item["options"] = options + if source: + item["optionSource"] = source + default = formruntime.column_default(column) + if default is not None: + item["default"] = default + out.append(item) + return out + + +def param_specs( + db: Session, + process: models.Process, + *, + fields: Iterable[dict] | None = None, + cache: dicts.DictCache | None = None, +) -> list[dict]: + """这条流程要传哪些参数:一个字段一行,照着填就能建草稿。 + + ``required`` 已经折过了开始环节的字段权限(口径同 ``formruntime``),所以它说的 + 是"发起时到底要不要填",不是设计器上那个早就过时的勾选框。系统带出与公式那两类 + 标成 ``system``:值由系统给,调用方不用传,传了也会被引擎按真实数据重算掉。 + """ + items = list(fields) if fields is not None else form_fields(db, process) + perms = begin_perms(db, process) + bag = cache if cache is not None else dicts.DictCache(db) + specs: list[dict] = [] + for item in items: + key = str(item.get("key") or "") + kind = str(item.get("type") or "") + if not key or kind in LAYOUT_TYPES: + continue + perm = formruntime.effective_perm(item, perms) + options, source = _options(item, bag) + spec: dict[str, Any] = { + "key": key, + "label": str(item.get("label") or key), + "type": kind or "text", + "required": perm == formruntime.PERM_REQUIRED, + "writable": perm in (formruntime.PERM_EDITABLE, formruntime.PERM_REQUIRED), + "system": formruntime.system_filled(item), + } + if perm == formruntime.PERM_HIDDEN: + spec["hidden"] = True + if kind == "table": + spec["columns"] = _columns(item, bag) + min_rows = int(item.get("minRows") or 0) + max_rows = int(item.get("maxRows") or 0) + if min_rows: + spec["minRows"] = min_rows + if max_rows: + spec["maxRows"] = max_rows + elif options: + spec["options"] = options + if source: + spec["optionSource"] = source + if item.get("unit"): + spec["unit"] = str(item.get("unit")) + specs.append(spec) + return specs + + +def type_view( + db: Session, + process: models.Process, + *, + startable: bool = True, + with_params: bool = True, + cache: dicts.DictCache | None = None, +) -> dict: + """一条流程在接口上的样子(``GET /draft/types`` 与开放平台共用)。""" + payload: dict[str, Any] = { + "process": process.id, + "name": process.name, + "alias": process.alias, + # 这两句是给调用方抄的:照着拼出来的 process 参数一定认得出来 + "ref": process.id, + "refByName": f"{process.category_name}{SEPARATOR}{process.name}" if process.category_name else process.name, + "category": process.category, + "category_name": process.category_name, + "description": process.description, + "icon": process.icon, + "color": process.color, + "form": process.latest_form, + "form_name": process.latest_form_name, + "startable": bool(startable), + "page_path": f"{START_PAGE}?process={process.id}", + } + if with_params: + payload["params"] = param_specs(db, process, cache=cache) + return payload + + +# --------------------------------------------------------------------------- +# 数据体检 +# --------------------------------------------------------------------------- + + +def inspect_data( + db: Session, + process: models.Process, + data: dict | None, + *, + fields: Iterable[dict] | None = None, + perms: dict[str, str] | None = None, +) -> Inspection: + """把调用方给的表单数据过一遍:整型明细表、认生字段、查必填与取值。 + + **全程不改数据、不报错**,只出提醒:草稿允许缺东西,硬卡必填等于把"存草稿" + 变成了"发起"。唯一动数据的地方是明细表整型,那一步和引擎提交时做的是同一件事 + (丢空行、补齐列默认值、按 maxRows 截断),先做是为了让人现在就看见行数变了。 + """ + items = list(fields) if fields is not None else form_fields(db, process) + permissions = begin_perms(db, process) if perms is None else perms + payload = dict(data or {}) + if not items: + return Inspection(data=payload) + + known = {str(item.get("key") or "") for item in items} + unknown = tuple(key for key in payload if key not in known) + + dropped: list[tuple[str, int]] = [] + for item in items: + key = str(item.get("key") or "") + if str(item.get("type") or "") != "table" or not key or key not in payload: + continue + before = len(formruntime.rows_of(payload[key])) + payload[key] = formruntime.normalise_rows(payload[key], item) + lost = before - len(payload[key]) + if lost > 0: + dropped.append((str(item.get("label") or key), lost)) + + cache = dicts.DictCache(db) + # 必填:标题字段这一格由标题规则负责填,没填不能算成调用方的漏子。 + title_field = titles.form_title_field(items) or {} + title_label = str(title_field.get("label") or title_field.get("key") or "") + missing = [ + label for label in formruntime.missing_required(items, permissions, payload) + if label != title_label + ] + problems = [ + problem for problem in formruntime.selection_problems(items, permissions, payload, cache) + ] + return Inspection( + data=payload, + unknown=unknown, + missing=tuple(missing), + problems=tuple(problems), + dropped=tuple(dropped), + ) + + +# --------------------------------------------------------------------------- +# 建草稿 +# --------------------------------------------------------------------------- + + +def draft_title( + db: Session, + process: models.Process | None, + actor, + data: dict | None, + *, + given: str = "", + current: str = "", +) -> str: + """草稿标题:表单里的标题字段 > 调用方写的 > 标题规则生成的 > 「某某的XX流程」。 + + 口径原样搬自 ``api/support.py``,搬进 service 只为一个理由:拟稿箱里的单子名字 + 必须和发出去之后是同一句,页面存草稿、接口建草稿、发起这一刻算标题, + 三处必须走同一条代码,谁都不许自己拼一句。 + """ + typed = (titles.field_value(db, process, data) if process is not None else "") or str(given or "").strip() + if typed: + return typed + if process is not None: + generated = titles.preview( + # 空 config = 交给 titles 按「流程规则 > 表单字段规则 > 老口径」挑,别在这里替它定死 + db, process, {}, + data=data or {}, actor=actor, use_sample=False, + )["title"] + if generated: + return generated + if current: + return current + return f"{actor.person_name}的{process.name}" if process else "" + + +def build( + db: Session, + *, + process: models.Process, + actor, + data: dict | None = None, + title: str = "", + draft: models.Draft | None = None, +) -> tuple[models.Draft, Inspection]: + """算出草稿该长成什么样,**不落库**。 + + ``draft`` 传进来就是在它上面改(页面覆盖保存、接口改一张已有草稿), + 不传是新建。新建时主键在这里就生成好,为的是 ``dry_run`` 也能回一个像样的 + 预览——虽然那张草稿并不存在。 + + 改草稿时流程一般不换(页面就这么用的),但接口允许换:调用方发现类型选错了, + 换一条流程重存比让他删了重建友好。流程一换,老数据里那些新表单没有的键就变成 + "认不出来",这是提醒该说的,不是悄悄删数据的理由。 + """ + fields = form_fields(db, process) + inspection = inspect_data(db, process, data, fields=fields) + row = draft if draft is not None else models.Draft(id=models.new_id()) + row.title = draft_title( + db, process, actor, inspection.data, given=title, current=draft.title if draft is not None else "" + ) + row.process = process.id + row.process_name = process.name + row.category = process.category + row.category_name = process.category_name + row.form = process.latest_form + row.data = inspection.data + row.person = str(actor.person_id) + row.person_name = actor.person_name + row.identity = actor.identity + row.unit = actor.unit + return row, inspection + + +def preview( + db: Session, + *, + process: models.Process, + actor, + data: dict | None = None, + title: str = "", + current: str = "", +) -> tuple[str, Inspection]: + """标题会算成哪句 + 这份数据体检出什么,**不碰对象也不碰库**。 + + ``dry_run`` 走这一条:调用方想知道"照这么传会成什么样",最不想看到的副作用是 + 服务端顺手把库里那张草稿改了(``build(draft=row)`` 是直接改 ORM 对象的, + 一次自动 flush 就存下去了)。 + """ + fields = form_fields(db, process) + inspection = inspect_data(db, process, data, fields=fields) + return draft_title(db, process, actor, inspection.data, given=title, current=current), inspection + + +def create( + db: Session, + *, + process: models.Process, + actor, + data: dict | None = None, + title: str = "", + draft: models.Draft | None = None, + check_startable: bool = True, + commit: bool = True, +) -> tuple[models.Draft, Inspection]: + """建(或改)一张草稿。返回草稿本体和这次的数据体检结果。 + + 调用方管事务:页面直接 commit,脚本可以攒着一起提交,开放平台也是自己 commit。 + """ + if check_startable: + guard_startable(db, process, actor) + row, inspection = build(db, process=process, actor=actor, data=data, title=title, draft=draft) + if draft is None: + db.add(row) + if commit: + db.commit() + return row, inspection + + +def page_path(process_id: str, draft_id: str = "") -> str: + """这张草稿在页面路上的位置:发起页带着它,打开就是填好的那半张单。""" + if not draft_id: + return f"{START_PAGE}?process={process_id}" + return f"{START_PAGE}?process={process_id}&draft={draft_id}" + + +def with_page(db: Session, row: models.Draft) -> dict: + """出参 = 草稿本来的样子 + 页面路径。 + + ``serializers.draft`` 是界面列表一直在用的那份,不在这儿改字段:草稿箱、门户首页 + 都靠它,多塞一个只对接口调用方有意义的 ``page_path`` 会让所有列表都跟着变胖。 + """ + return {**serializers.draft(row), "page_path": page_path(row.process, row.id)} diff --git a/backend/app/service/processdata.py b/backend/app/service/processdata.py new file mode 100644 index 0000000..2f42558 --- /dev/null +++ b/backend/app/service/processdata.py @@ -0,0 +1,500 @@ +"""「从另一个流程带数据」的查询执行器 -- 数据源 ``provider=process`` 走这一层。 + +要解决的事很具体:填报销单时把上次那张批完的请假单里的出差日期、目的地点进来, +别让人再抄一遍。做法不是再造一套「自动带出」,而是把它做成**又一个数据源**: +入参仍是本表单字段(``{form.x}``),产出仍走 ``fetch.parse`` 那套 ``pick`` / +``map_extra``,所以字段级配置、多源合集、带出去向、调用留痕、提交时服务端覆盖 +一律是现成的(方案见 ``docs/form-data-integration-design.md`` §11)。 + +四条分寸: + +1. **默认只查调用人自己的单**(``scope=own``)。把别人的单据内容带到自己这张单上, + 是一件出事之前没人觉得有问题的事;要跨人查必须显式改成 ``scope=all``, + 并且这个源得配 ``min_permission``——保存时 :func:`validate` 挡一道, + 运行时 ``fetch.run`` 那道权限检查再挡一道。 +2. **默认只认审批走完的单**(``status=completed``)。在途单的数字随时会变, + 抄进另一张单等于拿草稿当依据;确实要带在途单,口径改成 ``running`` / ``any``。 +3. **「按表单里指定的人查」只在跨人档生效**,理由见 :func:`person_ref`。 +4. **匹配条件在内存里筛,而且只在最近 :data:`SCAN_LIMIT` 单里筛**。``work.data`` 是 + JSON 列,MySQL 在不同版本上把字符串 ``"1200"`` 与数字 ``1200`` 比大小的口径并不一致, + 与其赌一个隐式转换,不如把候选量卡住之后自己比——候选够不够,界面上一句话说得清。 +""" + +from __future__ import annotations + +from datetime import datetime, timedelta +from typing import TYPE_CHECKING, Any, Iterable + +from sqlalchemy import select +from sqlalchemy.orm import Session + +from .. import models + +if TYPE_CHECKING: # 只要类型标注:engine 那边已经 import 了 service.fetch,运行期不能反着引 + from ..engine.engine import Actor + +# --------------------------------------------------------------------------- +# 配置口径(界面、保存校验、运行时共用这一份) +# --------------------------------------------------------------------------- + +#: 只取调用人自己发起的单 +SCOPE_OWN = "own" +#: 不限发起人:能按表单里的编号把别人发起的立项单捞出来 +SCOPE_ALL = "all" +SCOPES = (SCOPE_OWN, SCOPE_ALL) + +#: 只认走完的单(归档表里还躺着终止与作废的,所以那一条要再按 status 挑一次) +STATUS_DONE = "completed" +#: 只认还在办的单 +STATUS_RUNNING = "running" +#: 都算 +STATUS_ANY = "any" +STATUSES = (STATUS_DONE, STATUS_RUNNING, STATUS_ANY) + +ORDER_LATEST = "latest" +ORDER_EARLIEST = "earliest" +ORDERS = (ORDER_LATEST, ORDER_EARLIEST) + +OP_EQ = "eq" +OP_NE = "ne" +OP_HAS = "contains" +OP_IN = "in" +OP_GT = "gt" +OP_GTE = "gte" +OP_LT = "lt" +OP_LTE = "lte" +OP_EMPTY = "empty" +OP_NOT_EMPTY = "notEmpty" +OPS = (OP_EQ, OP_NE, OP_HAS, OP_IN, OP_GT, OP_GTE, OP_LT, OP_LTE, OP_EMPTY, OP_NOT_EMPTY) + +#: 需要比较值的操作符:界面按这个决定给不给取值输入框,校验按这个决定取值能不能空 +VALUE_OPS = (OP_EQ, OP_NE, OP_HAS, OP_IN, OP_GT, OP_GTE, OP_LT, OP_LTE) + +#: 留空 = 按这里的默认档走,与 :func:`clean_match` 补的默认值一致 +DEFAULTS = { + "scope": SCOPE_OWN, + "status": STATUS_DONE, + "order": ORDER_LATEST, + "days": 0, + "limit": 20, +} + +#: 匹配条件是在最近这么多单里筛的(每张表各取这么多,再合起来按时间排) +SCAN_LIMIT = 300 +#: 列表型一次最多回几条 +MAX_LIMIT = 50 +#: 一条源最多几个匹配条件;再多说明该去对面做一个查询接口,而不是在这里堆条件 +MAX_FILTERS = 8 + +#: 单据本体那几个能带的字段(不是表单字段,界面上单独一档) +META_FIELDS = ( + ("work.serial", "单据编号"), + ("work.title", "单据标题"), + ("work.status", "单据状态"), + ("work.creatorName", "发起人"), + ("work.creatorUnitName", "发起部门"), + ("work.startTime", "发起时间"), + ("work.finishTime", "办结时间"), +) + + +# --------------------------------------------------------------------------- +# 配置整形与保存期校验 +# --------------------------------------------------------------------------- + +def clean_match(raw: dict | None) -> dict: + """把存下来(并渲染过)的配置补成字段齐全、取值安全的匹配配置。 + + 不认识的值一律退回默认档,**不猜「他想干什么」**:状态写错时退回「只认走完的单」 + 比退回「全部都算」安全,范围写错时退回「只查自己的单」同理。 + """ + src = raw if isinstance(raw, dict) else {} + scope = str(src.get("scope") or DEFAULTS["scope"]) + out: dict[str, Any] = { + "scope": scope if scope in SCOPES else DEFAULTS["scope"], + "person": src.get("person") if isinstance(src.get("person"), list) else str(src.get("person") or "").strip(), + "status": str(src.get("status") or DEFAULTS["status"]), + "order": str(src.get("order") or DEFAULTS["order"]), + "days": _as_int(src.get("days"), DEFAULTS["days"], 0, 3650), + "limit": _as_int(src.get("limit"), DEFAULTS["limit"], 1, MAX_LIMIT), + "filters": [], + } + if out["status"] not in STATUSES: + out["status"] = DEFAULTS["status"] + if out["order"] not in ORDERS: + out["order"] = DEFAULTS["order"] + for item in src.get("filters") or []: + if not isinstance(item, dict): + continue + field = str(item.get("field") or "").strip() + op = str(item.get("op") or OP_EQ).strip() + if not field or op not in OPS: + continue + out["filters"].append({"field": field, "op": op, "value": item.get("value")}) + out["filters"] = out["filters"][:MAX_FILTERS] + return out + + +def validate(row: models.DataSource, db: Session | None = None) -> list[str]: + """保存前检查:回一份人话问题清单,空表表示可以存。 + + 这里挡的全是**运行时只会报「取不到」**的那些事:流程选没了、条件字段是手打的 + 早就不存在了、跨人查却没配权限。放过去,用户要等到有人填单时才看见一句 + 「没找到符合条件的单据」。 + """ + problems: list[str] = [] + process_id = str(getattr(row, "src_process", "") or "").strip() + if not process_id: + problems.append("还没选要带出哪个流程的数据") + # 给了会话才查「条件字段还在不在表单里」,草稿试保存时不必为这件事多查几遍 + problems.extend(match_problems(getattr(row, "src_match", None), process_id, db, + str(getattr(row, "min_permission", "") or ""))) + return problems + + +def match_problems(raw: dict | None, process_id: str, db: Session | None = None, + min_permission: str = "") -> list[str]: + """匹配配置本身的毛病;``db`` 给了才查字段还在不在。""" + src = raw if isinstance(raw, dict) else {} + match = clean_match(src) + problems: list[str] = [] + if str(src.get("scope") or "") and str(src.get("scope")) not in SCOPES: + problems.append(f"带出范围只支持 {'、'.join(SCOPES)}") + if str(src.get("status") or "") and str(src.get("status")) not in STATUSES: + problems.append(f"单据状态只支持 {'、'.join(STATUSES)}") + if str(src.get("order") or "") and str(src.get("order")) not in ORDERS: + problems.append(f"取哪一单只支持 {ORDER_LATEST}(最近一单)/ {ORDER_EARLIEST}(最早一单)") + if str(src.get("scope") or SCOPE_OWN) != SCOPE_ALL and _has_person(src): + problems.append("「按表单里指定的人查」只在带出范围选「不限发起人」时才生效,现在这一条会被忽略") + if str(src.get("scope") or SCOPE_OWN) == SCOPE_ALL and not str(min_permission or "").strip(): + problems.append("要带出别人发起的单,要先在这个源上配「调用权限」,否则任何人都能按编号捞到别人的单据") + for item in src.get("filters") or []: + if not isinstance(item, dict): + problems.append("匹配条件里有不认识的行,重配一下") + continue + field = str(item.get("field") or "").strip() + op = str(item.get("op") or OP_EQ).strip() + if not field: + problems.append("匹配条件没选要比哪个字段") + if op not in OPS: + problems.append(f"匹配条件「{field or '未填字段'}」的操作符不支持:{op}") + if op in VALUE_OPS and not str(item.get("value") if item.get("value") is not None else "").strip(): + problems.append(f"匹配条件「{field or '未填字段'}」没填写值,这一条等于没写") + if db is not None and process_id: + known = {str(item.get("key") or "") for item in fields_of_process(db, process_id)} + for item in match["filters"]: + if known and item["field"] not in known: + problems.append(f"匹配条件里的字段「{item['field']}」在那个流程的表单里已经找不到了") + return problems + + +def _has_person(src: dict) -> bool: + raw = src.get("person") + if isinstance(raw, (list, tuple, set)): + return any(str(item or "").strip() for item in raw) + return bool(str(raw or "").strip()) + + +# --------------------------------------------------------------------------- +# 查询 +# --------------------------------------------------------------------------- + +def person_ref(match: dict, actor: Actor | None, work: Any) -> str: + """按「谁的单」去查。表单里指定那个人**只在 ``scope=all`` 时才生效**。 + + 这是这条通道上唯一一处真隐私边界:选人字段里存的是身份 DN,而那个值来自填单页面, + 要是 ``scope=own`` 也认它,任何人都能把这一格改成别人的 DN、借「带出」读别人的单据。 + 所以默认档只认「当前这张单的发起人 / 调用人自己」;要按表单指定的人查,就必须显式 + 走跨人档(``scope=all`` + 这个源上的 ``min_permission``)。 + + 交出来的只是一个参照值:表单选人字段给的是身份 DN,``oa_work.creator`` 存的是人员 id, + 认哪一列由 :func:`candidates` 两列一起认,这里不猜。回空串=**不按人筛**(只可能出在 + 「不限发起人且没指定人」这一档,这时候再拿调用人去筛就成了另一回事)。 + """ + if match.get("scope") == SCOPE_ALL: + raw = match.get("person") + if isinstance(raw, (list, tuple, set)): + raw = next(iter(raw), "") + return str(raw or "").strip() + creator = str(getattr(work, "creator", "") or "").strip() + if creator: + return creator + return str(getattr(actor, "person_id", "") or "").strip() + + +def _models_for(status: str) -> list[Any]: + """去哪张表捞。办结的单在归档表里,``oa_work`` 那一行早被搬走了。""" + if status == STATUS_DONE: + return [models.WorkCompleted] + if status == STATUS_RUNNING: + return [models.Work] + return [models.Work, models.WorkCompleted] + + +def candidates(db: Session, match: dict, *, process_id: str, person: str = "") -> list[Any]: + """按流程 / 发起人 / 状态 / 时间窗捞候选并排好序;匹配条件留给 :func:`pick` 筛。 + + 能落到索引的条件先进 SQL,剩下那些比 JSON 里字段值的条件在 Python 里比 + (理由见模块开头第 4 条)。 + """ + rows: list[Any] = [] + newest_first = str(match.get("order") or ORDER_LATEST) != ORDER_EARLIEST + window = datetime.now() - timedelta(days=int(match.get("days") or 0)) if int(match.get("days") or 0) else None + for model in _models_for(str(match.get("status") or STATUS_DONE)): + stmt = select(model).where(model.process == process_id) + if person: + # 人员 id 与身份 DN 都认:调用方手里是哪一种,取决于这一条的值从哪儿来 + stmt = stmt.where((model.creator == person) | (model.creator_identity == person)) + if model is models.WorkCompleted: + if match.get("status") == STATUS_DONE: + # 归档表里还躺着终止与作废的单,「只认走完的」不能把它们一起算进来 + stmt = stmt.where(model.status == "completed") + if window is not None: + stmt = stmt.where(model.finish_time >= window) + order_column = model.finish_time + else: + stmt = stmt.where(model.deleted.is_(False)) + if window is not None: + stmt = stmt.where(model.start_time >= window) + order_column = model.start_time + stmt = stmt.order_by(order_column.desc() if newest_first else order_column.asc()).limit(SCAN_LIMIT) + rows.extend(db.execute(stmt).scalars().all()) + rows.sort(key=_time_key, reverse=newest_first) + return rows + + +def _time_key(row: Any) -> datetime: + """排序用的时间:归档件按办结时间,在途件按发起时间;都当没有就当最早。""" + value = getattr(row, "finish_time", None) or getattr(row, "start_time", None) + return value if isinstance(value, datetime) else datetime.min + + +def pick(rows: Iterable[Any], match: dict, *, current_job: str = "") -> list[Any]: + """按匹配条件筛,并排掉「就是当前这张单」本身。 + + 排掉自身是硬要求:报销单带出报销单这种自引用配错时,不排掉就等于 + 「把自己这张单刚填的值再带一遍」,而且一次都不会报错。 + """ + out: list[Any] = [] + filters = match.get("filters") or [] + for row in rows: + if current_job and str(getattr(row, "job", "") or "") == current_job: + continue + data = getattr(row, "data", None) + if not isinstance(data, dict): + data = {} + if all(_hit(data.get(str(item["field"])), item) for item in filters): + out.append(row) + return out + + +def find( + db: Session, + row: models.DataSource, + match: dict, + *, + actor: Actor | None = None, + work: Any = None, + many: bool = False, +) -> tuple[Any, str]: + """执行一次「从流程带数据」,回 ``(候选单 / 候选单列表, 错误信息)``。 + + 错误信息是给人看的那一句。没选流程、流程没了、没带身份、一条都没找到, + 在界面上长得完全不一样,不能都塞进「取数失败」这四个字。 + """ + process_id = str(getattr(row, "src_process", "") or "").strip() + if not process_id: + return None, "还没选要带出哪个流程的数据" + if db.get(models.Process, process_id) is None: + return None, "要带出数据的那个流程已经被删除了" + cross = match.get("scope") == SCOPE_ALL + person = person_ref(match, actor, work) + if not person and not cross: + return None, "没带调用人身份,不知道要查谁的单" + rows = pick(candidates(db, match, process_id=process_id, person=person), match, + current_job=str(getattr(work, "job", "") or "")) + if not rows: + return None, "没找到符合条件的单据" + ("(换一下状态或匹配条件试试)" if match.get("filters") else "") + limit = int(match.get("limit") or DEFAULTS["limit"]) + return (rows[:limit] if many else rows[0]), "" + + +# --------------------------------------------------------------------------- +# 结果整形:喂给 fetch.parse 的那份「响应」 +# --------------------------------------------------------------------------- + +def meta_of(row: Any) -> dict[str, Any]: + """单据本体那几个字段(编号、标题、时间…),与表单字段分开列。""" + return { + "id": str(getattr(row, "id", "") or ""), + "job": str(getattr(row, "job", "") or ""), + "serial": str(getattr(row, "serial", "") or ""), + "title": str(getattr(row, "title", "") or ""), + "status": str(getattr(row, "status", "") or ""), + "processName": str(getattr(row, "process_name", "") or ""), + "creatorName": str(getattr(row, "creator_person", "") or getattr(row, "creator_identity_name", "") or ""), + "creatorUnitName": str(getattr(row, "creator_unit_name", "") or ""), + "startTime": _dt(getattr(row, "start_time", None)), + "finishTime": _dt(getattr(row, "finish_time", None)), + } + + +def payload_of(row: Any) -> dict[str, Any]: + """单值型(``kind=fetch``)那份「响应」:``{"work": {...}, "data": {...}}``。 + + 刻意做成和外部接口响应同一种形状:``pick`` 写 ``data.amount``、``map_extra`` 写 + ``{"amount": "data.amount"}``,于是 ``fetch.parse`` 一行都不用改,外部接口那一套 + 解析、连通性测试、留痕在这条通道上照样能用。 + """ + data = getattr(row, "data", None) + return {"work": meta_of(row), "data": dict(data) if isinstance(data, dict) else {}} + + +def search_payload(rows: list[Any]) -> dict[str, Any]: + """列表型(``kind=search``)那份「响应」:``{"works": [{"id","title","data":{…}}]}``。 + + 每一项里也嵌一份 ``data``,这样 ``map_extra`` 的写法与单值型完全一样(都是 + ``data.<字段>``)——同一份「勾选要带出哪些字段」的界面,不必按 kind 换两套路径前缀。 + """ + return {"works": [{**meta_of(item), "data": payload_of(item)["data"]} for item in rows]} + + +# --------------------------------------------------------------------------- +# 设计期:目标流程能带出哪些字段 +# --------------------------------------------------------------------------- + +def fields_of_process(db: Session, process_id: str) -> list[dict[str, str]]: + """那个流程能带出哪些字段:默认表单 + 各环节表单,按键去重、按首次出现排序。 + + 环节表单里的字段同样落进同一份 ``work.data``,只列默认表单会漏掉一批真能带的字段。 + """ + form_ids: list[str] = [] + for form_id in _process_form_ids(db, process_id): + if form_id and form_id not in form_ids: + form_ids.append(form_id) + default_id = form_ids[0] if form_ids else "" + out: list[dict[str, str]] = [] + seen: set[str] = set() + for form_id in form_ids: + form = db.get(models.FormElement, form_id) + if form is None: + continue + for item in _content_fields(form.content): + key = str(item.get("key") or "").strip() + if not key or key in seen: + continue + seen.add(key) + out.append({ + "key": key, + "label": str(item.get("label") or key), + "type": str(item.get("type") or ""), + "form": form_id, + "formName": form.name or "", + "default": "1" if form_id == default_id else "", + }) + out.extend({"key": path, "label": label, "type": "meta", "form": "", "formName": "单据本体", "default": ""} + for path, label in META_FIELDS) + return out + + +def _process_form_ids(db: Session, process_id: str) -> list[str]: + """流程用到的表单:默认表单排最前,然后按环节顺序。""" + process = db.get(models.Process, process_id) + ids = [str(getattr(process, "latest_form", "") or "")] if process is not None else [] + activities = db.execute( + select(models.Activity).where(models.Activity.process == process_id).order_by(models.Activity.order_number) + ).scalars().all() + ids.extend(str(getattr(item, "form", "") or "") for item in activities) + return [item for item in ids if item] + + +def _content_fields(content: Any) -> list[dict]: + """表单内容里的字段定义,兼容 ``{fields: [...]}`` 与裸数组两种存法(与 fetch 同一口径)。""" + if isinstance(content, dict): + return [item for item in (content.get("fields") or []) if isinstance(item, dict)] + if isinstance(content, list): + return [item for item in content if isinstance(item, dict)] + return [] + + +# --------------------------------------------------------------------------- +# 比较:JSON 里的值什么形状都有,比之前先归一 +# --------------------------------------------------------------------------- + +def _hit(value: Any, item: dict) -> bool: + """一个匹配条件命中了吗。列表值(选人、多选部门)按「其中任一项」算。""" + op = str(item.get("op") or OP_EQ) + want = item.get("value") + if op == OP_EMPTY: + return _blank(value) + if op == OP_NOT_EMPTY: + return not _blank(value) + if _blank(value): + return False + parts = value if isinstance(value, (list, tuple, set)) else [value] + return any(_compare(one, op, want) for one in parts) + + +def _compare(one: Any, op: str, want: Any) -> bool: + if op == OP_IN: + return any(_equals(one, option) for option in _in_options(want)) + if op in (OP_GT, OP_GTE, OP_LT, OP_LTE): + left, right = _number(one), _number(want) + if left is None or right is None: + # 比不了数就按文本比:日期串(YYYY-MM-DD)这样比仍然是对的时间顺序 + left, right = str(one if one is not None else "").strip(), str(want if want is not None else "").strip() + return {"gt": left > right, "gte": left >= right, "lt": left < right, "lte": left <= right}[op] + same = _equals(one, want) + if op == OP_EQ: + return same + if op == OP_NE: + return not same + return str(want if want is not None else "").strip() in str(one if one is not None else "").strip() + + +def _equals(one: Any, want: Any) -> bool: + left, right = _number(one), _number(want) + if left is not None and right is not None: + return left == right + return str(one if one is not None else "").strip() == str(want if want is not None else "").strip() + + +def _in_options(want: Any) -> list[Any]: + if isinstance(want, (list, tuple, set)): + return list(want) + return [item.strip() for item in str(want if want is not None else "").replace(",", ",").split(",") if item.strip()] + + +def _number(value: Any) -> float | None: + """能当数看就当数看;``"1,200.00"`` 这种带分隔符的也认(金额字段常常这么存)。""" + if isinstance(value, bool): + return None + if isinstance(value, (int, float)): + return float(value) + text = str(value if value is not None else "").strip().replace(",", "") + if not text: + return None + try: + return float(text) + except ValueError: + return None + + +def _blank(value: Any) -> bool: + if value is None or value == "" or value == [] or value == {}: + return True + if isinstance(value, str): + return not value.strip() + return False + + +def _as_int(value: Any, default: int, floor: int, ceil: int) -> int: + try: + number = int(float(str(value).strip())) + except (TypeError, ValueError): + return default + return max(floor, min(ceil, number)) + + +def _dt(value: Any) -> str: + return value.strftime("%Y-%m-%d %H:%M:%S") if isinstance(value, datetime) else "" diff --git a/backend/app/service/simulator.py b/backend/app/service/simulator.py new file mode 100644 index 0000000..9c50738 --- /dev/null +++ b/backend/app/service/simulator.py @@ -0,0 +1,1465 @@ +"""流程试跑:选好发起人、填好表单,先把这一单预先走一遍。 + +设计器的「校验」只看得见解得开画布的问题——缺出口、分支没有默认分支、环节不可达。 +一张单真跑起来会落在谁手上、哪一环会因为找不到人自动通过、条件分支实际走哪一支、 +并联汇聚等不等得齐、明细会拆出几条支线,光看图是看不出来的,只能等真发一单。 +本模块按运行时的口径空跑一遍:找人、算条件、免审、去重、兜底全部直接调 ``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]: + """往前走的路由:退回(``goBack``)不参与预测,那是人按下「退回」之后的事。""" + return [route for route in self.definition.routes_from(node.id) if self._decision(node, route) != "goBack"] + + def _single(self, node: ActivityNode) -> RouteNode | None: + routes = self._forward(node) + return routes[0] if routes else None + + def _guard_ok(self, route: RouteNode, context: dict) -> bool: + """出口上写的适用条件现在成不成立;口径同 ``engine.route_guard_ok``。""" + from ..engine import expressions + + expression = str(route.expression or "").strip() + if not expression: + return True + try: + return bool(expressions.evaluate_condition(expression, context)) + except Exception as exc: # noqa: BLE001 - 与引擎一致:算不出来当不成立 + self._warn( + f"路由 {route.name} 的适用条件算不出来:{exc}。真跑的时候这一条会被拦住", + activity=route.to_activity, + kind="route_guard", + ) + return False + + def _condition_hit(self, expression: str, context: dict, *, where: str) -> bool: + from ..engine import expressions + + try: + return bool(expressions.evaluate_condition(expression, context)) + except Exception as exc: # noqa: BLE001 - 条件写坏时按不命中处理,和运行时一致 + self._warn(f"{where}的条件算不出来,按不命中处理:{exc}", kind="expression") + return False + + 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]) == "goBack": + # 整环跳过时引擎沿「第一条出口」往下走,第一条恰好是退回路由, + # 等于这张单会被自动打回——设计者多半没意识到,够格报一条错。 + 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 + + outcomes = [ + { + "route": route.id, + "name": route.alias or route.name, + "decision": self._decision(node, route), + "guard_ok": self._guard_ok(route, context), + "explored": True, + } + for route in routes_all + ] + blocked_exits = [item["name"] for item in outcomes if not item["guard_ok"]] + if blocked_exits and len(routes) > 1: + self._info( + f"环节 {node.name} 的出口「{'、'.join(blocked_exits)}」当前不满足适用条件,审批人这一次点不了", + activity=node.id, + kind="route_guard", + ) + if len(routes) > 1: + notes.append("出口由审批人选择:" + "、".join(route.alias or route.name for route in routes)) + + 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 route in routes[1:]: + 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}:{route.alias or route.name}", + via=route.id, + prev=tuple(item["identity"] for item in handlers) or token.prev, + ) + ) + token.prev = tuple(item["identity"] for item in handlers) or token.prev + return routes[0] + + 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: + row = db.get(models.FormElement, form_id) if form_id else None + return dict(getattr(row, "content", None) or {}) if row is not None else {} + + +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_identity(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.identity, + 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: + threshold_module.apply_check(db, fields, work.data, work=work, actor=actor) + except Exception as exc: # noqa: BLE001 - 阈值挡住提交,本身就是要报出来的一条 + runtime_notes.append((LEVEL_ERROR, 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): + identities = [actor.identity] + for row in org.person_identities(db, person.id): + if row.distinguished_name and row.distinguished_name not in identities: + identities.append(row.distinguished_name) + if not starters.allowed(db, process, identities=identities, 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.identity, + "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()), + } diff --git a/backend/scripts/advance_offset.py b/backend/scripts/advance_offset.py new file mode 100644 index 0000000..c590e70 --- /dev/null +++ b/backend/scripts/advance_offset.py @@ -0,0 +1,278 @@ +#!/usr/bin/env python3 +"""把「一张报销单一次冲多笔备用金」配到费用报销单上(额度台账多选冲销)。 + + cd backend/scripts + python3 -m advance_offset --check # 干跑:只说会改什么、后端认不认,不落库 + python3 -m advance_offset # 配上:冲销明细逐行挂备用金额度 + python3 -m advance_offset --show # 看现在配成了什么样 + python3 -m advance_offset --revert # 撤掉额度控制,明细表回到纯手填 + +前置:先跑 ``python3 -m advance_cash --quota`` 把备用金额度定义配好——备用金申请单 +办结即自动生成一行「应冲销额度」,台账不用人建。本脚本只做一件事:把这份额度挂到 +费用报销单的冲销明细表上;缺的「备用金单号」「本次冲销金额」两列由它补出来。 + +配完之后报销单是这样用的:冲销明细的「备用金单号」变成额度下拉,只列本人名下还没 +冲销完的备用金;选中一笔,借款金额 / 已冲销 / 还可冲自己落到这一行;再填本次冲销金额。 +一行冲一笔,一张单可以填几行冲几笔。合计与超支都由后端按台账算:同一笔的多行合起来 +判、合起来记,超了哪笔就点名挡哪笔。方案出处 ``docs/quota-control-design.md``。 +""" + +from __future__ import annotations + +import argparse +import json +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +from advance_cash import PROCESS_NAME, QUOTA, QUOTA_CODE # noqa: E402 +from expense.common import admin, ok # noqa: E402 + +FORM_NAME = "费用报销单" +TABLE_KEY = "offsetItems" +#: 选台账那一列 / 本次金额那一列(库里没有就按这两个键名补建,也可以用参数改) +PICK_COLUMN = "loanNo" +AMOUNT_COLUMN = "offsetAmount" +#: 额度维度键,与 advance_cash.QUOTA["dims"] 对上:一笔备用金一个维度 +DIM_KEY = "advanceNo" +#: 行内三列(选中台账后由后端写) +ROW_SHOW = {"total": "loanAmount", "used": "loanUsed", "avail": "loanRemain"} +#: 表头三格:这张单在这几笔备用金上的合计 +HEAD_SHOW = {"total": "advanceTotal", "used": "advanceUsed", "avail": "advanceRemain"} +ROW_TOTAL = ("借款金额", 2) +ROW_COLUMNS = {"loanUsed": ("已冲销", 2), "loanRemain": ("还可冲", 2)} +HEAD_COLUMNS = {"advanceTotal": ("涉及借款合计", 4), "advanceUsed": ("提交前已冲合计", 4), + "advanceRemain": ("本次之后剩余", 4)} + + +def quota_config(pick: str = PICK_COLUMN, amount: str = AMOUNT_COLUMN) -> dict: + """挂在明细表字段上的那份额度配置(后端只认这一份)。""" + return { + "def": QUOTA_CODE, + "rows": {"dims": {DIM_KEY: pick}, "amount": amount, "show": dict(ROW_SHOW)}, + "show": dict(HEAD_SHOW), + "over": "hard", + "message": "这笔备用金共 {total} 元,已冲 {used} 元,还可冲 {avail} 元,本次多冲 {over} 元", + } + + +def ensure_def(token: str) -> None: + """额度定义在不在;不在就按备用金那份建出来(办结生成额度那一套照抄)。""" + defs = {row["code"]: row for row in ok("GET", "/design/quotas/defs", token)} + if QUOTA_CODE in defs: + print(f" 额度定义 {QUOTA_CODE}({defs[QUOTA_CODE]['name']}):已存在,不动") + return + process = next((row for row in ok("GET", "/process/processes", token, params={"page_size": 200}) + if row.get("name") == PROCESS_NAME), None) + if process is None: + raise SystemExit(f"库里没有「{PROCESS_NAME}」,也还没有额度定义 {QUOTA_CODE}:" + "先跑 python3 -m advance_cash --quota 把备用金那套配好") + ok("POST", "/design/quotas/defs", token, dict(QUOTA, issue_process=process["id"])) + print(f" 额度定义 {QUOTA_CODE}({QUOTA['name']}):新建,备用金办结自动生成额度") + + +def find_form(token: str, name: str) -> dict: + for row in ok("GET", "/process/forms", token, params={"page_size": 200}): + if row["name"] == name: + return ok("GET", f"/process/forms/{row['id']}", token) + raise SystemExit(f"库里还没有表单「{name}」,先跑 python3 -m cost_reimburse 建出来") + + +def fields_of(form: dict) -> list[dict]: + return [dict(item) for item in (form.get("content") or {}).get("fields") or []] + + +def table_field(fields: list[dict], table_key: str) -> dict: + for item in fields: + if str(item.get("key") or "") == table_key: + if str(item.get("type") or "") != "table": + raise SystemExit(f"字段「{table_key}」不是明细表,逐行冲额度挂不上去") + return item + raise SystemExit(f"这张表单里找不到明细表「{table_key}」,本脚本不敢乱配" + "(要看这张单有哪些表,用 --show 配合改 --table)") + + +def patch_table(table: dict, pick: str, amount: str) -> tuple[list[str], bool]: + """该有的列补齐 + 挂额度配置,返回 (动了哪几处, 是否新建了选台账那一列)。""" + done: list[str] = [] + created_pick = False + columns = table.setdefault("columns", []) + + def at(key: str) -> int: + return next((index for index, item in enumerate(columns) + if str(item.get("key") or "") == key), -1) + + if at(pick) < 0: + columns.insert(max(at(amount), 0), {"key": pick, "label": "备用金单号", "type": "select", + "required": True, "span": 3}) + created_pick = True + done.append("补了「备用金单号」列:填报时从额度台账里选(这张单原来没有这一列)") + elif columns[at(pick)].get("type") != "select": + columns[at(pick)]["type"] = "select" + done.append("「备用金单号」改成下拉选台账(选项由额度台账供,不用配字典)") + + if at(amount) < 0: + columns.append({"key": amount, "label": "本次冲销金额", "type": "money", + "required": True, "span": 2, "min": 0}) + done.append("补了「本次冲销金额」列:只有这一列的钱才真扣到台账上") + + total = ROW_SHOW["total"] + if at(total) < 0: + columns.insert(max(at(amount), 0), {"key": total, "label": ROW_TOTAL[0], "type": "money", + "readonly": True, "span": ROW_TOTAL[1], "min": 0}) + done.append(f"补了「{ROW_TOTAL[0]}」列(后端按台账写)") + elif not columns[at(total)].get("readonly"): + columns[at(total)]["readonly"] = True + done.append(f"「{ROW_TOTAL[0]}」设为只读:以台账为准,人手改不动") + + for key, (label, span) in ROW_COLUMNS.items(): + if at(key) >= 0: + columns[at(key)]["readonly"] = True + continue + columns.insert(max(at(amount), 0), {"key": key, "label": label, "type": "money", + "readonly": True, "span": span, "min": 0}) + done.append(f"补了「{label}」列(后端写,前端改不动)") + + table["quota"] = quota_config(pick, amount) + done.append(f"挂上额度控制:{QUOTA_CODE} 逐行冲(一行一笔,同一笔的多行合起来算)") + return done, created_pick + + +PICK_HINT = (" 注意:「备用金单号」是新加的列,之前填过的冲销明细行里没有它。" + "配完之后那些行再次提交会被挡(填了本次金额却没选台账),要么补选要么删行。") + + +def patch_header(fields: list[dict], table_key: str) -> list[str]: + """表头那三格:这张单在这几笔备用金上的合计。""" + done: list[str] = [] + known = {str(item.get("key") or "") for item in fields} + at = next(index for index, item in enumerate(fields) if str(item.get("key") or "") == table_key) + for offset, (key, (label, span)) in enumerate(HEAD_COLUMNS.items(), start=1): + if key in known: + continue + fields.insert(at + offset, {"key": key, "label": label, "type": "money", "readonly": True, + "span": span}) + done.append(f"表头补了「{label}」") + return done + + +def validate(token: str, form: dict, fields: list[dict]) -> dict: + """过一遍后端那道设计期闸门:配歪了当场说,别等发起人点提交才发现根本没生效。""" + content = dict(form.get("content") or {}, fields=fields) + problems = ok("POST", "/process/forms/validate", token, {"content": content}).get("problems", []) + if problems: + raise SystemExit("这样存会被后端挡下来:" + ";".join(problems)) + return content + + +def save(token: str, form: dict, fields: list[dict]) -> None: + ok("PUT", f"/process/forms/{form['id']}", token, + {"name": form["name"], "description": form.get("description") or "", + "content": validate(token, form, fields)}) + + +def check(token: str, opts: argparse.Namespace) -> None: + """干跑:只读表单 + 过后端校验,一句库都不写。""" + print("=== 备用金多选冲销(干跑,不落库)===") + defs = {row["code"]: row for row in ok("GET", "/design/quotas/defs", token)} + print(f" 额度定义 {QUOTA_CODE}:{'已存在' if QUOTA_CODE in defs else '还没有,正式配时按备用金那份建'}") + form = find_form(token, opts.form) + fields = fields_of(form) + done, created_pick = patch_table(table_field(fields, opts.table), opts.pick, opts.amount) + done += patch_header(fields, opts.table) + if QUOTA_CODE not in defs: + # 定义还没有时后端必然报「额度定义不存在」,那不是配置配歪了,别拿它吓人 + for line in done: + print(f" - {line}") + print(" 额度定义还没建,正式配时先按备用金那份建出来再存,这里跳过后端校验。") + if created_pick: + print(PICK_HINT) + return + validate(token, form, fields) + for line in done: + print(f" - {line}") + print(" 后端校验通过。要真配上去掉 --check 再跑一次。") + if created_pick: + print(PICK_HINT) + + +def apply_config(token: str, opts: argparse.Namespace) -> None: + print("=== 备用金多选冲销 ===") + ensure_def(token) + form = find_form(token, opts.form) + fields = fields_of(form) + done, created_pick = patch_table(table_field(fields, opts.table), opts.pick, opts.amount) + done += patch_header(fields, opts.table) + save(token, form, fields) + for line in done: + print(f" - {line}") + print(f" 「{opts.form}」已保存:冲销明细里选备用金即可,一张单可填多行冲多笔。") + if created_pick: + print(PICK_HINT) + + +def revert(token: str, opts: argparse.Namespace) -> None: + print("=== 撤掉备用金额度控制 ===") + form = find_form(token, opts.form) + fields = fields_of(form) + table = table_field(fields, opts.table) + cfg = table.pop("quota", None) + if cfg: + print(f" - 摘掉「{opts.table}」上的额度控制") + # 选台账那一列是为额度才改成下拉的;摘了额度还留着下拉就成了「没选项也没字典」, + # 表单直接存不回去,所以按配置里记的列名退回文本列 + rows = cfg.get("rows") if isinstance(cfg.get("rows"), dict) else {} + dims = rows.get("dims") if isinstance(rows.get("dims"), dict) else {} + picks = {str(value).strip() for value in dims.values() if str(value or "").strip()} or {opts.pick} + for column in table.get("columns") or []: + key = str(column.get("key") or "") + sourced = bool(str(column.get("dictCode") or "").strip()) or bool(column.get("options")) + if key in picks and str(column.get("type") or "") == "select" and not sourced: + column["type"] = "text" + print(f" - 列「{column.get('label') or key}」退回文本填写") + else: + print(" 本来就没挂额度控制,没动") + for key in HEAD_SHOW.values(): + if any(str(item.get("key") or "") == key for item in fields): + fields = [item for item in fields if str(item.get("key") or "") != key] + print(f" - 移除表头「{HEAD_COLUMNS[key][0]}」") + save(token, form, fields) + print(" 明细表回到手填。多出来的金额列留着(历史单据里存过值),台账与流水一分不动。") + + +def show(token: str, opts: argparse.Namespace) -> None: + form = find_form(token, opts.form) + table = table_field(fields_of(form), opts.table) + cfg = table.get("quota") or {} + print(f"「{opts.form}」的 {opts.table}.quota =") + print(json.dumps(cfg, ensure_ascii=False, indent=2) if cfg else " (没配)") + print(" 列:", "、".join(str(item.get("label") or item.get("key")) + for item in table.get("columns") or [])) + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--form", default=FORM_NAME, help=f"目标表单名(默认 {FORM_NAME})") + parser.add_argument("--table", default=TABLE_KEY, help=f"冲销明细表字段名(默认 {TABLE_KEY})") + parser.add_argument("--pick", default=PICK_COLUMN, help="选台账那一列的列名") + parser.add_argument("--amount", default=AMOUNT_COLUMN, help="本次金额那一列的列名") + parser.add_argument("--check", action="store_true", help="干跑:看会改什么,不落库") + parser.add_argument("--revert", action="store_true", help="撤掉额度控制") + parser.add_argument("--show", action="store_true", help="只看现在的配置") + opts = parser.parse_args() + token = admin() + if opts.show: + show(token, opts) + elif opts.check: + check(token, opts) + elif opts.revert: + revert(token, opts) + else: + apply_config(token, opts) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/backend/scripts/advance_offset_demo.py b/backend/scripts/advance_offset_demo.py new file mode 100644 index 0000000..8efb355 --- /dev/null +++ b/backend/scripts/advance_offset_demo.py @@ -0,0 +1,362 @@ +#!/usr/bin/env python3 +"""备用金「一次申请、多次冲销」的测试数据:配好额度,再造几张真单据进去。 + + cd backend/scripts + python3 -m advance_offset_demo # 配额度 + 造数据 + 打印台账与单据对照 + python3 -m advance_offset_demo --report # 只读:把现在的台账和流水打出来 + python3 -m advance_offset_demo --clean # 按标题前缀清掉本批数据(单据 + 台账 + 流水) + +写的是当前实例连的那个库(接口地址沿用 EXPENSE_BASE,默认本机 8000;库名看 +backend/config.dev.toml),跑之前确认那是开发库。配置那一步直接复用 +``advance_offset.py``,已配过就是空转,可以反复跑。 + +数据是这么摆的(备用金三笔都压在 5000 以下,走「小额免部门主管」那条线;报销单走哪条岔线 +由流程上的条件说了算,脚本只把想走的分支名递过去,递不上就交回引擎按条件挑): + + 备用金 A 4000 / B 3000 / C 1500 三张单各自办结,长三行台账 + 报销①一次冲两笔 A 冲 1500 + B 冲 3000 → 办结:A 还剩 2500,B 冲满自动关闭 + 报销②同一笔拆两行 A 两行 2000 + 1000 → 被挡:两行合起来比 2500 多冲 500 + 报销③第二行漏选 A 冲 300 + 空选 500 → 被挡:那 500 没挂在任何一笔台账上 + 报销④收尾冲完 A 剩的 2500 一笔冲掉 → 办结:A 自动关闭 + C 的 1500 故意留着不冲,界面上正好有一笔「还可冲 1500」的活台账可以试 + D 2600 / E 900 造在最后、一律不冲:A、B 冲完就关闭了,下拉里只剩 C 一笔,想试 + 「一张单选两笔」手里得先有两笔活的 + +审批全程由系统管理员点:财务经理 / 财务总监 / 总经理 / 执行董事四个岗位临时挂到管理员 +名下,跑完原样还原(挂之前先把原名单打出来,万一中途断在那儿也照着设回去)。 +""" + +from __future__ import annotations + +import argparse +import json +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +import advance_offset as ao # noqa: E402 复用那份 quota 配置与「缺列自己补」的写法 +from advance_cash import ROLES, restore_roles, staff_roles_with_admin # noqa: E402 +from expense import common # noqa: E402 +from expense.common import ok # noqa: E402 + +#: 标题都带这个前缀,--clean 靠它认出哪些是本脚本造的;改了老数据就清不掉了 +PREFIX = "备用金冲销演示" +LOAN_PROCESS = "备用金申请流程" +REIMB_PROCESS = "费用报销流程" +#: 报销单的「相关核算项目」走字典 pms_project,值同时是 PMS 取数的入参;报销单上还有一格 +#: 「PMS 项目预算余额」是 onError=block 的取数,所以提交前那个假上游(scripts/ +#: pms_balance_stub.py,默认 9099)必须在跑,不然整张单会因为取不到数提交不了。 +PROJECT_DICT = "pms_project" +PROJECT_WANTED = "P00001" +#: 想让它走哪条岔线就先把那条名字递过去,别照着 route_name_list[0] 盲点——那样走出来的单子 +#: 根本不是这条数据线。库里没有这条分支时(各家用自己的条件改过流程)自动交回引擎判断。 +LOAN_ROUTES = ("小额免部门主管",) +REIMB_ROUTES = ("全额冲销免部门主管", "小额直达归档") + +#: (标题后缀, 借款金额, 借款类型, 借款事由) +LOANS: list[tuple[str, float, str, str]] = [ + ("备用金A展会现场", 4000.0, "petty", "上海展会现场三天的临时支出"), + ("备用金B现场采购", 3000.0, "purchase", "深圳客户现场补采线材与支架"), + ("备用金C驻场押金", 1500.0, "other", "客户机房驻场的门禁卡押金"), +] +#: 造在最后、故意不冲的两笔:冲完的那几笔台账会自动关闭,下拉里就挑不出两笔来了 +EXTRA_LOANS: list[tuple[str, float, str, str]] = [ + ("备用金D留着多冲试", 2600.0, "petty", "客户驻场第二期的现场备用金"), + ("备用金E留着多冲试", 900.0, "travel", "下个月出差的市内交通备用金"), +] + + +# -------------------------------------------------------------------------- +# 接口薄封装:提交要能拿到「被挡下来那句话」,所以不能一律走 ok() +# -------------------------------------------------------------------------- + +def process_id(token: str, name: str) -> str: + for row in ok("GET", "/process/processes", token, params={"page_size": 200}): + if row["name"] == name: + return row["id"] + raise SystemExit(f"库里没有「{name}」,先跑 python3 -m advance_cash / cost_reimburse 建流程") + + +def project_code(token: str, want: str) -> str: + """核算项目照字典来:优先用 --project 指定的,字典里没有就退第一个启用的项目。""" + raw = ok("GET", f"/process/dicts/{PROJECT_DICT}/items", token) + items = raw["items"] if isinstance(raw, dict) else raw + codes = [str(item.get("value")) for item in items or [] if item.get("enabled", True)] + if not codes: + raise SystemExit(f"字典「{PROJECT_DICT}」是空的,报销单连核算项目都选不出来") + if want in codes: + return want + print(f" 核算项目「{want}」不在字典里,改用「{codes[0]}」") + return codes[0] + + +def submit(session: dict, process: str, data: dict) -> tuple[str, str]: + """提交一张单;被校验挡下来时返回 (空, 提示语),别让整个脚本跟着炸。""" + status, payload = common.api("POST", "/job", session["access_token"], + {"process": process, "data": dict(data)}) + if status != 200 or payload.get("code") != 0: + message = str(payload.get("message") or payload) + if "外部数据取不到" in message: + message += "(报销单上那格 PMS 余额是 onError=block 的取数," \ + "先把 backend/scripts/pms_balance_stub.py 起来)" + return "", message + return payload["data"]["job"], "" + + +def drive(session: dict, job: str, prefer: tuple[str, ...] = (), limit: int = 12) -> dict: + """一路点同意点到归档,只认待办列表不认岗位名单(岗位已临时挂在管理员名下)。""" + token = session["access_token"] + trace: list[str] = [] + for _ in range(limit): + detail = common.wait_activity(token, job, seconds=40) + if detail["status"] != "running": + detail["trace"] = trace + detail["routes"] = [line["route_name"] for line in common.logs(token, job) + if line.get("route_name")] + return detail + if not detail.get("tasks"): + raise SystemExit(f"{job}:停在 running 却又没有待办,去界面上看一眼") + for task in detail["tasks"]: + routes = task.get("route_name_list") or [] + named = next((name for name in prefer if name in routes), "") + route = named or (routes[0] if len(routes) == 1 else "") + common.execute(session, task, route, "同意(测试数据)") + trace.append(task["activity_name"]) + raise SystemExit(f"{job}:点了 {limit} 拍还没归档,已点到 {trace}") + + +def quota_rows(token: str) -> list[dict]: + return ok("GET", "/design/quotas", token, + params={"defCode": ao.QUOTA_CODE, "page_size": 200}) or [] + + +def quota_row(token: str, dim_value: str) -> dict: + """按额度维度取值(这里就是备用金单号)找回台账那一行。""" + for row in quota_rows(token): + if str((row.get("dims") or {}).get(ao.DIM_KEY)) == str(dim_value): + return row + return {} + + +def fmt_row(row: dict) -> str: + if not row: + return "(台账里找不到!)" + return (f"共 {row['total']:,.2f}|已冲 {row['used']:,.2f}|在途 {row['occupied']:,.2f}" + f"|还可冲 {row['available']:,.2f}|{row['status']}") + + +# -------------------------------------------------------------------------- +# 造数据 +# -------------------------------------------------------------------------- + +def loan_data(tail: str, amount: float, loan_type: str, reason: str) -> dict: + label = {"petty": "备用金", "purchase": "采购借款", "other": "其它"}.get(loan_type, "备用金") + return { + "title": f"{PREFIX}|{tail}", "loanType": "petty", "unoffsetAmount": 0, + "loanReason": reason, + "loanItems": [{"loanNote": reason, "loanType": loan_type, "loanTypeName": label, + "loanAmount": amount, "returnDate": "2026-12-31"}], + "payItems": [{"payee": "系统管理员", "bankName": "不适用", "bankAccount": "现金", + "payAmount": amount, "payWay": "cash"}], + } + + +def reimburse_data(tail: str, lines: list[tuple[str, float]], offsets: list[dict], + project: str) -> dict: + """费用明细按 (费目, 金额) 给,费目取字典 costProject:差旅 travel、杂费 otherExpenses。""" + return { + "title": f"{PREFIX}|{tail}", "applicant": "系统管理员", + "reimburseType": "reimbursePettyCash", "accountProject": project, + "expenseItems": [{"itemSubject": subject, "amount": amount, + "amountDetial": "演示费用"} for subject, amount in lines], + "offsetItems": offsets, + "payMethod": "cash", "payAccount": "备用金", "bankName": "不适用", + } + + +def offset_row(no: str, detail: str, loan_total: float, amount: float) -> dict: + """冲销明细的一行:loanNo 那一列存的就是额度维度值(备用金单号)。""" + return {"loanNo": no, "loanDetail": detail, "loanAmount": loan_total, "offsetAmount": amount} + + +def make_loans(session: dict, process: str, + items: list[tuple[str, float, str, str]] = None) -> list[dict]: + """备用金:提交 → 点到归档 → 把办结长出来的那行台账读回来。""" + token = session["access_token"] + created: list[dict] = [] + for tail, amount, loan_type, reason in (items if items is not None else LOANS): + job, msg = submit(session, process, loan_data(tail, amount, loan_type, reason)) + if not job: + raise SystemExit(f"「{tail}」提交就被挡:{msg}") + detail = drive(session, job, LOAN_ROUTES) + serial = detail.get("serial") or "" + created.append({"tail": tail, "job": job, "serial": serial, "amount": amount, + "row": quota_row(token, serial)}) + print(f" {PREFIX}|{tail} 单号 {serial}|{detail['status']}" + f"|走线:{' / '.join(detail['routes'])}") + print(f" 台账:{fmt_row(created[-1]['row'])}") + return created + + +def show_doc(token: str, job: str, tail: str) -> None: + data = (common.job_detail(token, job) or {}).get("data") or {} + lines = [f"{item.get('loanDetail')}:本次 {float(item.get('offsetAmount') or 0):,.2f}" + f"(共 {float(item.get('loanAmount') or 0):,.2f}/还可冲 " + f"{float(item.get('loanRemain') or 0):,.2f})" for item in data.get("offsetItems") or []] + print(f" 表头合计:涉及 {float(data.get('advanceTotal') or 0):,.2f}" + f"|提交前已冲 {float(data.get('advanceUsed') or 0):,.2f}" + f"|本次之后剩 {float(data.get('advanceRemain') or 0):,.2f}") + for line in lines: + print(f" 行内:{line}") + print(f" (单号 {job},标题「{PREFIX}|{tail}」)") + + +def make_reimbursements(session: dict, process: str, loans: list[dict], project: str) -> None: + token = session["access_token"] + a, b, c = loans + + print("\n=== 报销①一张单一次冲两笔(A 1500 + B 3000,全额冲销)===") + data = reimburse_data("一次冲两笔", [("travel", 1500), ("otherExpenses", 3000)], + [offset_row(a["serial"], "展会现场支出", a["amount"], 1500), + offset_row(b["serial"], "现场采购支出", b["amount"], 3000)], project) + job, msg = submit(session, process, data) + if not job: + raise SystemExit(f"一次冲两笔没提交上去:{msg}") + detail = drive(session, job, REIMB_ROUTES) + print(f" 办结 {detail['status']}|走线:{' / '.join(detail['routes'])}") + show_doc(token, job, "一次冲两笔") + print(f" A 现在:{fmt_row(quota_row(token, a['serial']))}") + print(f" B 现在:{fmt_row(quota_row(token, b['serial']))}(一次冲满,自动关闭)") + + print("\n=== 报销②同一笔拆两行想多冲(A 两行 2000 + 1000,只剩 2500)===") + data = reimburse_data("同一笔多冲", [("otherExpenses", 3000)], + [offset_row(a["serial"], "多冲一", a["amount"], 2000), + offset_row(a["serial"], "多冲二", a["amount"], 1000)], project) + expect_blocked(session, process, data, "多冲 500.00") + + print("\n=== 报销③第二行填了钱却没选台账 ===") + data = reimburse_data("漏选台账", [("otherExpenses", 800)], + [offset_row(a["serial"], "有单号", a["amount"], 300), + {"loanDetail": "忘了选", "loanAmount": 0, "offsetAmount": 500}], project) + expect_blocked(session, process, data, "没选要冲的台账") + + print("\n=== 报销④把 A 剩下的 2500 收尾冲完 ===") + data = reimburse_data("收尾冲完", [("travel", 2500)], + [offset_row(a["serial"], "展会余下支出", a["amount"], 2500)], project) + job, msg = submit(session, process, data) + if not job: + raise SystemExit(f"收尾这张没提交上去:{msg}") + detail = drive(session, job, REIMB_ROUTES) + print(f" 办结 {detail['status']}|走线:{' / '.join(detail['routes'])}") + show_doc(token, job, "收尾冲完") + print(f" A 现在:{fmt_row(quota_row(token, a['serial']))}") + print(f" C 现在:{fmt_row(quota_row(token, c['serial']))}(留着不冲,界面上可以自己试)") + + +def expect_blocked(session: dict, process: str, data: dict, keyword: str) -> None: + """这张按口径就该挡下来:挡下来才算数,放行反而是事故。""" + _job, msg = submit(session, process, data) + if keyword not in msg: + raise SystemExit(f"「{data['title']}」本该被「{keyword}」挡下,实际:{msg[:200]}") + print(f" 按预期挡下:{msg[:200]}") + + +# -------------------------------------------------------------------------- +# 台账报告 / 清理 +# -------------------------------------------------------------------------- + +def report(token: str) -> None: + rows = quota_rows(token) + print(f"=== 额度台账 {ao.QUOTA_CODE}({len(rows)} 行)===") + for row in rows: + print(f" {(row.get('dims') or {}).get(ao.DIM_KEY)} {row['title']}") + print(f" {fmt_row(row)}") + for entry in ok("GET", f"/design/quotas/{row['id']}/ledger", token) or []: + print(f" {entry['createdAt']} {entry['kind']:<9}{entry['amount']:>12,.2f}" + f" 余额 {entry['balanceAfter']:>10,.2f} {entry.get('activityName') or ''}" + f" {entry.get('job') or ''}") + if not rows: + print(" (还没有台账:备用金申请单办结才会有)") + + +def clean() -> int: + """按标题前缀清场:先摘台账与流水,再让 purge 摘单据,别留对不上账的尾巴。""" + sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + from sqlalchemy import select # noqa: PLC0415 + + from app import db, models # noqa: PLC0415 + + print(f"=== 清掉「{PREFIX}」开头的测试数据 ===") + session = db.SessionLocal() + try: + works = [row for model in (models.Work, models.WorkCompleted) + for row in session.execute(select(model)).scalars().all() + if str(row.title or "").startswith(PREFIX)] + jobs = {row.job for row in works} + quotas = session.execute(select(models.Quota).where( + models.Quota.source_job.in_(jobs))).scalars().all() + ledgers = session.execute(select(models.QuotaLedger).where( + models.QuotaLedger.job.in_(jobs))).scalars().all() + for row in ledgers: + session.delete(row) + for row in quotas: + session.delete(row) + session.commit() + print(f" 台账删 {len(quotas)} 行,流水删 {len(ledgers)} 条") + finally: + session.close() + from expense.purge import purge # noqa: PLC0415 + + result = purge([PREFIX]) + print(f" 单据删 {len(result['jobs'])} 张:{json.dumps(result['counts'], ensure_ascii=False)}") + return 0 + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--report", action="store_true", help="只读:打印台账与流水") + parser.add_argument("--clean", action="store_true", help=f"清掉「{PREFIX}」开头的测试数据") + parser.add_argument("--project", default=PROJECT_WANTED, + help=f"报销单用的核算项目编码(字典 {PROJECT_DICT},默认 {PROJECT_WANTED})") + opts = parser.parse_args() + if opts.clean: + return clean() + + token = common.admin() + if opts.report: + report(token) + return 0 + + print("=== 1. 额度与表单配置(跑过就是空转)===") + ao.apply_config(token, argparse.Namespace(form=ao.FORM_NAME, table=ao.TABLE_KEY, + pick=ao.PICK_COLUMN, amount=ao.AMOUNT_COLUMN)) + loan_process, reimb_process = process_id(token, LOAN_PROCESS), process_id(token, REIMB_PROCESS) + session = common.login(common.ADMIN_ACCOUNT, common.ADMIN_PASSWORD) + + roles = {row["name"]: row for row in ok("GET", "/org/roles", token)} + print("\n=== 2. 审批岗临时挂到系统管理员(跑完还原,中途断了照这里设回去)===") + for name, _ in ROLES: + print(f" {name}:{(roles.get(name) or {}).get('list_auth') or '(空)'}") + backup = staff_roles_with_admin(token) + try: + print("\n=== 3. 三笔备用金:办结自动长台账 ===") + loans = make_loans(session, loan_process) + project = project_code(token, opts.project) + print(f"\n报销单用的核算项目:{project}(PMS 取数也按它查余额)") + make_reimbursements(session, reimb_process, loans, project) + print("\n=== 4. 再补两笔留着不冲(界面上试多选用的活台账)===") + make_loans(session, loan_process, EXTRA_LOANS) + print("\n=== 5. 最终台账 ===") + report(token) + print(f"\n界面上看:我的申请 / 单据列表里搜「{PREFIX}」;" + "额度台账在「设计 - 额度台账」;清场跑 python3 -m advance_offset_demo --clean") + finally: + restore_roles(token, backup) + print("\n审批岗位名单已还原") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/backend/scripts/dedupe_reads.py b/backend/scripts/dedupe_reads.py new file mode 100644 index 0000000..ce30848 --- /dev/null +++ b/backend/scripts/dedupe_reads.py @@ -0,0 +1,89 @@ +#!/usr/bin/env python3 +"""把待阅里「同一个人、同一张单据、同一类待阅」的重复条目并成一条。 + + python3 scripts/dedupe_reads.py --dry-run # 先看要并哪些,库里一个字节都不动 + python3 scripts/dedupe_reads.py # 真的并 + +合条的规则从 2026-10 起引擎自己在派待阅时就做了(见 ``engine.create_reads``:同单同类 +再抄一次只把已有那条更新成最新内容)。这条脚本管的是那之前已经堆下来的旧数据: +抄送规则常常挂在好几个环节上(进入财务经理抄一次、归档再抄一次),一个人的待阅列表 +里就摆出两条一模一样的单据,看的人分不清哪条才是新的。 + +并法:留最早那一条(它决定这条待阅在列表里排第几,别把它洗到最新去),内容换成 +最新一次的来龙去脉,其余删除。「要求处理」的标记只要其中有一条要求过就保留。 +""" +from __future__ import annotations + +import argparse +import sys +from collections import defaultdict +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[0].parent)) + +from sqlalchemy import select # noqa: E402 + +from app import models # noqa: E402 +from app.db import SessionLocal # noqa: E402 + + +def merge_group(rows: list[models.Read]) -> list[models.Read]: + """把一个重复组并成一条,返回被删掉的那些行。""" + keep, rest = rows[0], rows[1:] + latest = max(rest, key=lambda row: row.start_time) + keep.activity = latest.activity + keep.activity_name = latest.activity_name + keep.current_activity_name = latest.current_activity_name + keep.completed = bool(latest.completed) + keep.work_completed = latest.work_completed + keep.sender = latest.sender + keep.source_identity = latest.source_identity + if latest.opinion: + keep.opinion = latest.opinion + keep.requires_action = any(row.requires_action for row in rows) + return rest + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("--dry-run", action="store_true", help="只报告,不改动库里任何一行") + args = parser.parse_args() + + merged = 0 + dropped = 0 + with SessionLocal() as db: + rows = db.execute( + select(models.Read).order_by( + models.Read.work, models.Read.identity, models.Read.read_type, models.Read.start_time + ) + ).scalars().all() + groups: dict[tuple[str, str, str], list[models.Read]] = defaultdict(list) + for row in rows: + groups[(row.work, row.identity, row.read_type)].append(row) + + for (work, identity, kind), group in groups.items(): + if len(group) < 2: + continue + print( + f" {group[0].serial or work[:8]}|{group[0].identity_name}|{kind}|" + f"{len(group)} 条 -> 1 条(留 {group[0].start_time},内容取 {group[-1].activity_name})" + ) + merged += 1 + if args.dry_run: + dropped += len(group) - 1 + continue + for row in merge_group(group): + db.delete(row) + dropped += 1 + if not args.dry_run: + db.commit() + + if not merged: + print("待阅里没有重复条目,无需处理") + return 0 + print(f"{'(试运行,未改动)' if args.dry_run else ''}合并 {merged} 组,删除 {dropped} 条重复待阅") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/docs/approval-dedup-design.md b/docs/approval-dedup-design.md new file mode 100644 index 0000000..a937d75 --- /dev/null +++ b/docs/approval-dedup-design.md @@ -0,0 +1,260 @@ +# 同一张单上同一个人只签一次:口径、边界与设计期体检 + +> 状态:已落地。运行时口径在 `backend/app/engine/engine.py`(`approval_flags` / `repeat_policy` / +> `ahead_scope` / `_approved_persons`)与 `backend/app/engine/lookahead.py`,设计期体检在 +> `backend/app/service/dedupaudit.py`,界面在流程设计器(`ProcessDesignerView.vue` + +> `components/oa/design/DedupAuditPanel.vue`)。README「引擎能力 → 流转语义」那几条是本文的浓缩版。 + +## 0. 一页看完 + +- 一张单上同一个人出现在好几个环节是常态(发起人自己也是初审人、总监在两个环节都要签)。 + 配的时候只需要回答一个问题:**这单他签几次、签在哪一次**——所以界面上是**一档策略四选一**, + 不是两个各开各的开关。 +- 两条规则方向相反但不互相抵消:**往回看**(前面真批过 → 这一环自动过)以已办为凭, + **往前看**(后面还要他批 → 这一环跳过)不产生已办。于是同一个人这一单**一定至少真签一次**。 +- 「批过」认的是**亲手表态**:或签里被系统代结的、转办出去的、走退回路由回去的那一票都不算 + (`_approved_persons`)。这一条是本轮修正——以前这些人会被当成「批过」而免掉后面的签字。 +- 路由上写的条件也算图的一部分:条件分支按这一单的表单收敛成引擎真会走的那一条,退回路由不算 + 往前走,免审条件只按人判。以前这些都摊平成「可能走」,配得再死的分支也只换来一句 + 「后面有一条分支不经过他」。 +- 新增的是**设计期就能看见结果**:`POST /process/processes/{id}/dedup-audit` 拿画布上 + 当前这份设计(含还没保存的改动)试算一遍,右栏「审批体检」页签逐个人给结论,画布上的环节 + 挂角标,工具栏那个红色数字是还没管住的组数,发布前再拦一句。发现「会签两次」时可以直接 + 一键改成建议的那档,改完体检自己重算,当场看见红点变绿。 + +## 1. 四档策略,不是两个开关 + +存储沿用原来那两个键(不迁移、不动老数据): + +| 位置 | 往回看 | 往前看 | +| --- | --- | --- | +| 流程级 `approval_config` | `dedup: none\|all` | `dedupAhead: none\|all\|any`(`all`/`any` 是口径,不是开关) | +| 环节 `config` | `skipApproved?: boolean` | `skipAhead?: boolean`(+ `skipAheadScope` 单独改口径) | + +界面上折成一档策略,四选一: + +| 策略 | 含义 | 折算出来的两个开关 | +| --- | --- | --- | +| `each` 每次都签 | 每一环都派待办 | 两个都关 | +| `first` 只签第一次 | 真签过一次之后,后面再遇到他的环节自动过 | 往回看开 | +| `last` 只签最后一次 | 前面先跳过,签在后面那一次 | 往前看开 | +| `once` 只签一次 | 两头都收:能提前跳的跳掉,真签过一次之后后面也自动过 | 两个都开 | + +- 折算是同一份口径的两个实现:后端 `engine.repeat_policy`、前端 `utils/approvalDedup.ts`。 +- 继承**按方向一个个来**:环节只钉了往回看那半边时,往前看照旧跟流程默认走。所以右栏显示的 + 是算完流程默认之后**真正生效**的那一档,只钉一半时下面会写明为什么和单独钉的那档不一样。 +- 「跟随流程设置」=把那两个键删掉(不是写成 `false`)。写成 `false` 是显式要求「这一环不许跳」。 +- `last` 不是 `once` 的省流版:有躲不掉的环节(起草环节、退回到达的环节一律不许往前看跳过, + 命中必批规则保下的人也不跳)时,`last` 会签两次。想让人只签一次就选 `once`。 + +## 2. 「前面批过」认什么 + +`_approved_persons()` 只把这三种历史当成「批过」,比「手上有一条已办」严一档: + +1. `TaskCompleted.processing_type == 'normal'`:或签 / 按比例会签凑够票后被系统结掉的那几张、 + 转办、加签、终止,都不是他亲手表的态。把他算成批过,等于一张单上凭空少一个真签字。 +2. 走退回路由的那一票不算:他把单子打回去,不等于他批完了,后面再遇到得真看一遍。 +3. `DEDUP_SINCE_KEY` 基线之前的老票不算:退回重走要重新表态。 + +第 2 条是给没经过退回入口的路由补的口径——退回本身已经把 `dedupSince` 推到此刻,但 +「环节上配了多条路由、其中一条是退回」这类图里,光靠基线盖不住。 + +## 3. 「后面还要他批」凭什么敢跳 + +`engine/lookahead.py` 是纯图分析,不碰库、不猜运行时;要读库、算表单的两件事由调用方以回调 +传进来(`upcoming` 的 `routes` / `droppable`)。默认口径 `all` 要求**后面每一条走得通的路径 +都一定经过他**才免掉前面这一环,「走得通」是这一轮的重点: + +- **条件分支按这份表单收敛**(`engine.forecast_routes`,口径同 `_pick_choice`):引擎只会走 + 第一条成立的那条分支,前瞻就只按那一条算;适用条件不成立的出口(`route_guard_ok` 会拦的那几条) + 先剪掉。以前把所有出口都当可能走,画了条件分支就等于永远「有一条路不经过他」,设计者把分支 + 配得再死也免不掉重复签字。 +- **条件算不出来=说不准,那条出口留着**:字段还没填、式子写坏了,都不能当成「这条走不了」。 + 引擎放行时算不出来按不成立拦下,前瞻时反过来——把一条可能走得通的路当成走不通,就等于敢在 + 说不准的地方免掉一个人的签字。 +- **退回路由不算往前走**(含环节上 `routeDecisions` 改标的那几条):退回是把单子打回去,不是 + 批完,退回去重走哪几环说不准。把它当正常出口,几乎所有配了「驳回」的流程就再也免不掉重复签字。 + 口径与试跑 `service/simulator.py:_forward` 一致。前面那一环会不会因此少一次「他本来可以驳回」? + 会——但「往后看跳过」本来就意味着这一票挪到后面那一次去表,他在后面那一环照样能驳回。 +- **或签(`any`)、按比例会签**凑够票就把别人结掉了,不算「他一定会批」;环节就他一个人时才算。 +- **免审条件只按人判**:这一环配了免审规则,只有「这条规则可能碰到他」(整环都免、名单说不准、 + 或者就叫到他名字)才算这一环不一定有他;规则点的是别人,他这一票照样跑不掉。规则碰得到谁算在 + `engine.rule_reach`,只按规则点名的人算、不去跑它的条件(条件要等这一单的表单填出来才算得准), + 前瞻与设计期体检共用这一份。 +- `any` 是「有一条后续路径可能用到他就跳」,省待办更狠,但分支一拐弯他可能一次都没批过, + 激进口径必须显式配出来才生效(写个不认识的值一律退回 `all`); +- `dedupAheadKeepOne`:整环的人都被前瞻免掉时,留第一个人在这一环签,不让整环一个人都没留下。 + +## 4. 设计期体检:画完就能看见谁被跳过 + +运行时早就有这套规矩,缺的是**在设计器里看见结果**。以前要判断「张三会不会被自动跳过」, +只能真发一单,或者自己在脑子里走一遍图。`service/dedupaudit.py` 把同一套判定挪到设计期跑一遍: +拿画布上当前的环节与路由(含还没保存的改动)+ 组织现在的找人结果试算,逐个环节给结论。 + +**刻意不复算规则**:三个开关、前瞻口径直接调 `engine.repeat_policy` / `ahead_scope` / +`approval_flags`(延迟 import 防环)。只有「后面这一环躲不躲得开」是这里按图自己算的, +口径与 `lookahead` 的必经判定一致——成环、没走完、解析不出人,一律按「不敢断定」处理。 + +### 4.1 画布上的重复分三种,确定程度完全不同 + +| 形状 | 结论 | 为什么 | +| --- | --- | --- | +| 一前一后(后面那个能从前面走到) | 判得准 | 策略管不管得住,静态就能算 | +| 互斥分支(互相走不到,也没有并行环节同时展开两支) | `branch` 不算重复 | 这一单根本不会都走到 | +| 并行 / 数据拆分的两支(会同时展开) | `watch` 待确认 | 运行时两边都派待办,去重两头都够不着 | +| 分支条件对不上(走到前一环的前提与通往后一环的分支互相矛盾) | 不算重复,单列 `impasses` | 同一张单根本走不到一起,但要写清凭什么排除 | + +### 4.2 图分析在问什么 + +`_Graph` 一次建图,边带着路由上写的条件(`conditions.parse` 读过的式子)与决定值,问五件事: +`reachable`(结构上可达,条件一律当可能走)、`possible`(按条件走得到的可达,用来判「这一对到底 +重不重复」)、`must_pass`(往后每一条走得通的路是否必经,带环检测与步数上限)、`concurrent` +(两个环节会不会被同一个并行/拆分同时展开)、`order`(按最浅深度排的展示顺序,用来把「谁在前 +谁在后」说清楚)。判不出来的那一支在两种问题里都站在保守一侧:问「能不能走到」时不敢说不可能, +问「必经吗」时不敢说一定——所以「判不准」只会多问一句,不会把一次真重复悄悄抹掉。 +`entry(node)` 给「走到这一环得先满足什么」,分支条件要能用,靠的就是它把上游的前提带下来。 +上限 `MAX_NODES=300` / `MAX_WALK=20000`,再离谱的图也不卡。 + +### 4.3 四种结论 + +逐对判 `double`(两处都要他签)/ `later`(后面那环自动跳过)/ `earlier`(前面这环自动跳过)/ +`unknown`(判不准),再折回人和环节两层: + +- 按人汇总成一个 `verdict`:`open` 还会签两次 / `watch` 要人确认 / `covered` 都管住了 / + `branch` 落在互斥分支上不算重复; +- 按环节汇成角色:`sign` 要他签 / `skip` 自动跳过 / `double` 照旧要签 / `watch` 判不准, + 并附一句「凭什么叫他签两次、凭什么跳」(另一处环节名也带上)。 + +判定的先后顺序和引擎一致:先问往前看、再问往回看。前瞻跳掉的那一环不产生已办, +所以往前看成立时轮不到往回看表态。 + +**判不成重复的两种情形分开记**:`branch` 是图的结构上互斥(互相走不到、又没有并行祖先), +`impasses` 是分支条件对不上——后者是按配的条件算出来的,所以每条都带 `entry`(走到前一环的前提) +与 `blockers`(通往后一环的那条出口要什么)。一句「不会两次都走到」得能追到凭据。 + +**「不敢跳」也要说清是哪一条**:`ahead_unproven` 那一对带 `blockers`,点名「哪个环节的哪条出口 +不经过他、这条要看哪个字段」(`hint` 是字段名,`detail` 是这条条件的一句话);确实没写条件的分支 +标 `blank`,那是画出来的两条路、不是条件没配好。必经证成了、只是后面那一环说不准(或签、免审 +碰得到他),措辞换成另一句——两种原因别混成「有一条分支」。 + +**一对重复带三个字段,别把它们混成一件事**:`outcome` 是落法、`certain` 是这两个环节的人 +现在定没定得下来、`settled` 是**「管住了」这件事换成人还成立吗**。总评只看 `settled`:往回看 +认的是「他在这张单上真批过一次」,运行时换成谁都管得住,所以它管住的一对即使名单是试算出来的 +也算 `covered`;往前看认的是「后面每条路都要他批」,这句话依赖后面那一环落到几个人身上, +只有**后面那个环节**动态时才降级成 `watch`(前面那环自己动态不影响这条结论)。 + +`cause` 说清是哪一档没管住,界面上那一键修法照它挑:`policy_off` 两档都没开 / +`ahead_unproven` 往前看开着但后面有条分支不经过他 / `first_node` 前面那环是起草环节躲不掉 / +`concurrent` 并行同展 / `must_rule` 后面那环配了必批规则。前三种是「开一档往回看就管得住」, +后两种不是配置没配好,一键修法不碰它们。 + +### 4.4 找人算不出人时降级,不硬判 + +发起人上级、上一环节处理人、表单字段、找人脚本这类环节要等这一单真跑起来才定得下来 +(`RUNTIME_KINDS`)。这类环节标 `dynamic`:照样用样例身份试算出人来给人看,涉及它的那一条 +带上「这条是试算」。但**降级降的是「判得准不准」,不是「管没管住」**——一档真管得住的策略 +不该因为名单是试算的就报成「要人确认」(此前正是这一条把明明配了 `last` 的流程一直挂在橙灯上, +改哪儿都不亮)。环节自己的 `notes`(还没配找人方式、脚本要等表单填完、按某个人试算)原样 +带出去,界面上收在「试算说明」里。 + +### 4.5 界面 + +- **入口**:工具栏「审批体检」按钮(带红点=`open + watch` 组数)、右栏第四个页签,两处同一个动作。 +- **面板**:上面说清「流程默认那一档 + 按谁试算 + 什么时候算的、画布改过就标待重算」, + 中间最多四个数(重复出现 / 会签两次 / 要人确认,最后再补一个「按条件走不到」—— + 有被分支条件排除掉的配对才占一格,没有就不显示,免得看成一盏新警灯),下面逐个人一卡: + 环节链按流程顺序排开, + 颜色区分要签 / 跳过 / 照旧要签 / 判不准,点环节直接跳到画布上那一环并居中。用到分支条件的 + 那条结论挂一个「按分支条件判」标,底下补两行小字:走到前面那一环的前提、以及挡路的那几条出口。 + 另有一叠收起来的「按分支条件走不到一起」,逐条说明凭什么不算重复——排除了却不说,设计者只会 + 以为体检漏了一笔。 +- **一键修法**:有「开一档往回看就管得住」的对子时挑一个**最小改动**推给用户——流程默认还是 + `each` 就建议改 `first`(比直接上 `once` 保守,往后看会连前面该签的那环一起跳掉,不该由体检 + 替人做主);已经是 `last` 就建议改 `once`;往回看开着了还漏,说明是后面那一环自己钉死了 + 「不许跳」,那就只把挡路的几环退回跟随流程设置。挑对象看的是 `cause`,**橙色的 `watch` 组里 + 那种「往后看不敢跳」的对子同样给修法**——以前只对红色 `open` 出声,于是配了 `last`、被分支 + 卡住的那一类只能看着灯亮干瞪眼。改完画布变了 → 体检自己重算 → 角标当场减少。 + 口径在 `utils/dedupAudit.dedupRecommendation`。 +- **发布前**:算过且还有 `open`,发布确认框里补一句「还有 N 个人会在这张单上签两次」。 + 只问一句、不挡路——重复签字也可能是故意的(两个人各签一道同名同姓的巧合也算正常)。 +- **自动补算只在页签开着时**:拖一下框不该打后端;结论与当前画布对不上时标「待重算」, + 要不要重算由人点。 + +### 4.6 接口 + +``` +POST /api/v1/process/processes/{id}/dedup-audit + 权限 design:process + body { activities?, routes?, approval?, asIdentity? } # 全部可选:没传的那部分读库里的设计稿 + → { policy, ahead_scope, keep_one, as_identity_name, + nodes[]: 每个手工环节的生效开关与试算名单, + groups[]: 逐个人的结论(nodes / pairs / verdict / doubles / unclear / branch / conditional), + 每条 pair 带 outcome / certain / settled / cause / reason / conditional / entry / blockers[], + impasses[]: 按分支条件走不到一起的那几对(entry / blockers / reason), + stats: { manual, resolved, people, groups, open, watch, branch, conditional, impossible } } + +`blockers[]` 一条是一个出口:`at`(哪个环节)、`route`(哪条路由)、`to`(通向哪儿)、 +`hint`(要看哪个字段)、`detail`(这条条件的一句话)、`blank`(没写条件)、`goback`(退回路由)。 +``` + +`activities` / `routes` 认下划线与驼峰两种写法,环节上多带的 `x` / `y` / `form` 一律不看; +画布传来的那份优先,所以「还没保存的改动」也算得出来。响应形状与前端 `types/index.ts` +里那组 `DedupAudit*` 类型逐字对齐。 + +## 5. 边界与不做的事 + +- **不替人改配置**。体检只报结论 + 给一个可以按下去的建议,从不自己动环节;建议也只有一个, + 不做「一键全部修好」那种一屏复选框。 +- **不承诺运行时的准确**。试算用的是**此刻**的组织和**此刻**的表单,真跑起来时上级换了人、 + 表单填了另一个人,名单就会变。所以动态找人一律降级,界面上也一直写着「按谁试算」。 + 路由条件同样按此刻的表单算:跳掉前面那一环之后,如果经办人又把那个字段改了、分支拐到不经过他 + 的那一条,这一单就少他这一票——跟「后面那一环的名单按此刻组织算」是同一类已知误差, + 要绝对稳就在这一环把前瞻关掉。 +- **不算并行分支上的重复该不该跳**。并行两边都派待办是引擎行为,体检只把它标成「要人确认」, + 要不要为此改掉拆分形状是设计问题,不是去重能救的。 +- **不做历史单据的回溯体检**。发布后的流程版本照旧按当时那份配置走,体检只对着画布上这份草稿。 +- **不动存储、不动老配置**。四档策略是界面上的折算,两个键的老写法继续有效。 + +## 6. 代码地图 + +| 关心的事 | 在哪 | +| --- | --- | +| 生效的那三个开关 | `engine/engine.py: approval_flags` | +| 折成一档策略 | `engine/engine.py: repeat_policy` ↔ `utils/approvalDedup.ts` | +| 前瞻口径 | `engine/engine.py: ahead_scope` ↔ `utils/approvalDedup.ts: aheadScopeOf` | +| 「真批过」的名单 | `engine/engine.py: _approved_persons` | +| 往后看怎么跳、哪些环节躲不掉 | `engine/lookahead.py` | +| 路由条件读成可比对的式子(`decide` / `pick` / 矛盾检查) | `engine/conditions.py` | +| 往后看时哪些出口当下真走得通 | `engine/engine.py: forecast_routes`(口径同 `_pick_choice`) | +| 免审 / 必批规则碰得到谁 | `engine/engine.py: rule_reach` | +| 设计期体检 | `service/dedupaudit.py`、`api/design.py: audit_duplicate_approvers` | +| 体检结论折成建议 / 画布角标 | `utils/dedupAudit.ts` | +| 体检状态与自动补算 | `composables/useDedupAudit.ts` | +| 体检界面 | `components/oa/design/DedupAuditPanel.vue` | + +本仓库不留测试代码,所以这三块是落地时按 `backend` 目录下的临时脚本逐条跑真库验的(整体回滚、 +库里不留数据),要点记在这儿,改动时照单子复查: + +- **图形状**:一前一后(判得准)、互斥分支(不算重复)、并行 / 拆分同展(降级待确认)、成环、 + 必经走不通、动态找人降级、`activities` 缺省时读库兜底; +- **条件参与判定**(本轮补的三张用例单):条件分支没前提 → `double + ahead_unproven` 且点名那条 + 没写条件的出口;走到前一环的前提把分支收窄成一条 → `earlier + covered`;前一环挂着退回路由 → + 照样 `covered`;后面那一环或签两人 → 不敢跳,措辞说「说不准轮到他批」;后面那一环的免审规则 + 只点别人 → 不拖住整环;两档都没开 → `double + policy_off`;前提与分支条件互相矛盾 → 进 + `impasses` 并给出 `entry` / `blockers`;只有退回之后才会再遇到他 → 仍然报成重复(判不准不许 + 变成漏报);`forecast_routes` 与 `_pick_choice` 对齐(成立的分支赢过写在前面的默认分支、 + 算不出来的条件两条都留、人工环节只剪适用条件不成立的出口); +- **两边口径同步**:拿试跑(`service/simulator.py`,全程只读)跑同一份合成流程,条件成立时那一环 + 要写出「审批人去重:X(后面还要在「Y」批)后面还要批一次,本环节自动通过」——设计期说已管住、 + 运行时却不跳,就是两边口径分了家; +- **接口形状**:`/dedup-audit` 返回的每一个键都对得上 `types/index.ts` 的 `DedupAudit*`, + 并且吃得下设计器发的那份带 `x` / `y` / `form` 的环节与带 `decision` / `expression` 的连线; + 只传 `approval` 时图回退到库里的设计稿;流程不存在报 404; +- **运行时口径**:或签凑票被系统代结、转办、加签都不算「批过」,真批过之后后面那一环才自动跳过 + (`engine._approved_persons` 的注释就是这三条的清单); +- **降级只降判准**:同一组重复在 `each` / `last` / `once` 三档下分别应当报成 + `double+policy_off` / `double+ahead_unproven` / `later+covered`,且动态名单只把前两种带到 + `watch`,`later+covered` 必须是 `covered`(印章使用申请流程按部门负责人+执行董事试算即是这条 + 的实景:13 个部门扫下来 `open`/`watch` 都是 0)。 + +最后更新:2026-10-16 diff --git a/docs/draft-create-api.md b/docs/draft-create-api.md new file mode 100644 index 0000000..403c8e6 --- /dev/null +++ b/docs/draft-create-api.md @@ -0,0 +1,204 @@ + +# 创建流程草稿接口 + +一句话:**调一次接口,就能给任意类型的流程建出一张草稿,人在页面草稿箱里点开接着填。** + +面向两类人:本系统前端(登录态)、外部系统(应用令牌)。两条路共用同一套口径 +([backend/app/service/drafts.py](../backend/app/service/drafts.py)),差别只在"以谁的身份" +怎么给:页面用登录会话,外部系统用 `identity` 点名。 + +| 接口 | 谁用 | 干什么 | +| --- | --- | --- | +| `GET /api/v1/draft/types` | 调用方 | 查有哪些流程类型、每个类型要传哪些参数 | +| `POST /api/v1/draft` | 页面 / 脚本 | 建一张草稿(带 `dryRun` 只体检不落库) | +| `GET /api/v1/draft` | 页面 | 我的草稿箱 | +| `PUT /api/v1/draft/{id}` | 页面 / 调用方 | 改草稿(顺带换流程类型也可以) | +| `DELETE /api/v1/draft/{id}` | 页面 | 删草稿 | +| `POST /api/v1/open/drafts` | 外部系统 | 替某个身份建草稿 | +| `GET /api/v1/open/drafts` | 外部系统 | 查某个身份的草稿 | + +## 1. 通用约定 + +* 前缀 `/api/v1`,统一响应体 `{"code": 0, "message": "", "data": ...}`,`code != 0` 即失败。 +* 页面侧鉴权:`Authorization: Bearer `,令牌来自 `POST /api/v1/auth/login`。 +* 请求体下划线与驼峰两种写法都收(`dryRun` == `dry_run`),未定义的键一律忽略。 +* 时间是本地时区的 `YYYY-MM-DD HH:mm:ss`。 +* 草稿只属于建它的那个人:`person` 决定谁能在草稿箱看到它,别人的接口碰不到它。 + +## 2. 建草稿:`POST /api/v1/draft` + +| 参数 | 类型 | 必填 | 说明 | +| --- | --- | --- | --- | +| `process` | string | 是 | 建哪一类流程。**五种写法都认**:流程 id、名称、别名、`分类/流程名`、关键词 | +| `category` | string | 否 | 分类限定(分类 id 或中文名),用来区分同名流程 | +| `title` | string | 否 | 草稿标题。不传就按标题规则生成,再兜底成「某某的XX流程」 | +| `data` | object | 否 | 表单值,键取 `params[].key` | +| `dry_run` | bool | 否 | `true` 时只体检不落库,库里一个字都不写 | + +请求与响应(`data` 为节选): + +```bash +curl -X POST http://127.0.0.1:8000/api/v1/draft \ + -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \ + -d '{"process":"印章使用申请","title":"(示例)合同用印申请", + "data":{"sealCount":2,"reason":"合同用印","no_such":1}}' +``` + +```json +{ + "code": 0, + "data": { + "id": "c0031464eecf45879dcb6456519f0efe", + "title": "(示例)合同用印申请", + "process": "7e5f00a1185a4cff846678b63df4f41d", + "process_name": "印章使用申请流程", + "category_name": "行政办公", + "form": "b8f6545e45704451a3cb6d97af8fa3db", + "data": {"sealCount": 2, "reason": "合同用印", "no_such": 1}, + "person_name": "系统管理员", + "identity": "优尼森科技\\综合管理部\\系统管理员\\localadmin", + "create_time": "2026-10-16 09:08:35", + "update_time": "2026-10-16 09:08:35", + "page_path": "/start?process=7e5f...&draft=c00314...", + "notices": [ + "还差 3 项才提交得了:印章申请分类、用印类型、印章形式(草稿不拦,填全了再发起)", + "表单里没有这几个字段,草稿照样存着,但发起时不会当成表单值:no_such" + ] + } +} +``` + +`page_path` 是本站相对路径,拼上站点地址就能点开;只带 `?draft=` 也认,流程由草稿自己反查。 + +`dry_run=true` 时回的是同一份体检结果,但没有 `id`: + +```json +{"code": 0, "data": {"dry_run": true, "process": "7e5f...", "process_name": "印章使用申请流程", + "title": "系统管理员的印章使用申请流程", "data": {}, "notices": ["还差 4 项…"], + "page_path": "/start?process=7e5f..."}} +``` + +### 错误码 + +| HTTP | `reason` | 什么时候 | +| --- | --- | --- | +| 400 | `PROCESS_REQUIRED` | `process` 空着 | +| 400 | `PROCESS_NOT_FOUND` | 这个写法找不到流程(带分类时会说清是哪个分类里也没有) | +| 400 | `PROCESS_AMBIGUOUS` | 撞上多条同名流程,消息里把候选念出来让人改名。**宁可报错也不替你猜**:草稿建错流程比建失败难查得多 | +| 400 | `PROCESS_NOT_PUBLISHED` | 流程还没发布 | +| 403 | `START_FORBIDDEN` | 这个人不在该流程的发起范围里(与 `POST /job` 同一把尺子) | +| 401 | `UNAUTHORIZED` | 没带令牌或令牌过期 | + +## 3. 查类型与参数:`GET /api/v1/draft/types` + +| 参数 | 说明 | +| --- | --- | +| `process` | 只查某一个类型(写法同上),传了就回单个对象 | +| `keyword` / `category` | 清单过滤 | +| `params` | 默认 `true`,带参数清单;只想要类型清单时传 `false` | + +清单只列这个人**发得起来**的流程——发不起的列出去也建不了。类型对象里值得注意的几个键: + +| 键 | 说明 | +| --- | --- | +| `ref` | 流程 id,直接拿去当 `process` 传最稳 | +| `refByName` | `分类/流程名`,人话写法,同样认 | +| `page_path` | 这个类型的发起页 | +| `params` | 参数清单,见下 | + +`params[]` 一条就是一个表单字段: + +| 键 | 说明 | +| --- | --- | +| `key` | 传 `data` 时用的键名 | +| `label` | 界面上显示的名字(`notices` 里报的就是它) | +| `type` | 字段类型,取值形状见第 6 节 | +| `required` | 发起时是否必填(已折过开始环节的字段权限,不是设计器上那个老勾选框) | +| `writable` | `false` = 这一格发起环节改不动(只读/隐藏),传了也不生效 | +| `system` | `true` = 值由系统带出或公式算出,不用传 | +| `options` / `optionSource` | 合法取值与来源(`字典 loanType` 或 `表单内置选项`),最多回 50 条 | +| `columns` / `minRows` / `maxRows` | 明细表(`type=table`)才有;行的键取 `columns[].key` | +| `unit` | 金额、数字那类的单位后缀,只是展示用 | + +## 4. 改与删 + +* `PUT /api/v1/draft/{id}`:请求体同 `POST`。不带 `process` 就是原地改数据;带了就把流程类型一起换掉 + (换类型后老数据里新表单没有的键会进 `notices` 提示,不悄悄删)。只能改自己的草稿。 +* `DELETE /api/v1/draft/{id}`:删自己的草稿(管理员可删别人的)。 +* 草稿被 `POST /api/v1/job` 用 `draft_id` 发起成功后,这张草稿自动删掉。 + +## 5. 外部系统这条路 + +先换访问令牌,再调数据面: + +```bash +curl -X POST http://127.0.0.1:8000/api/v1/open/token \ + -H "Content-Type: application/json" -d '{"app_key":"oa_xxx","app_secret":"xxx"}' + +curl -X POST http://127.0.0.1:8000/api/v1/open/drafts \ + -H "Authorization: Bearer $ACCESS_TOKEN" -H "Content-Type: application/json" \ + -d '{"identity":"优尼森科技\\研发部\\张三\\zhangsan","process":"备用金申请", + "title":"张三的备用金申请","data":{"loanReason":"出差备用"}}' +# → {"code":0,"data":{"draft":{"id":"...","identity":"...","pagePath":"/start?process=...&draft=...", ...}, +# "notices":["还差 1 项才提交得了:借款类型(草稿不拦,填全了再发起)"]}} +``` + +* 应用要在开放平台里勾上 **`draft:write`**(建草稿)/**`draft:read`**(查某人的草稿)。 + 读写分两档是刻意的:草稿是还没提交的半张单,"能替别人铺一张"和"能翻看别人写了什么"是两回事。 +* `identity` 必填,必须是本系统里存在且在职的身份;**没有"以管理员身份"这种兜底**。 +* 发起范围照样生效:那个人发不起这个流程,接口就 403。 +* `data` 与 `notices` 的口径和第 2 节完全一样;字段名在这条路上是驼峰(`processName`、`pagePath`)。 +* 超速率回 **429**(按应用配置的每分钟上限,读留痕计数判定,多副本一致)。 +* `GET /api/v1/open/drafts?identity=...&limit=50` 查他草稿箱,`limit` 上限 200。 + +## 6. 各类型字段的取值形状 + +| `type` | 传什么 | +| --- | --- | +| `text` `textarea` `mobile` `email` `idcard` `url` `address` | 字符串 | +| `number` `money` `rate` | 数字(别带单位、千分位、货币符号) | +| `date` / `datetime` / `time` | `"2026-10-16"` / `"2026-10-16 09:00"` / `"09:00"` | +| `daterange` | `["2026-10-16", "2026-10-20"]` | +| `select` `radio` | 选项的 **value**(`params[].options[].value`,不是中文名) | +| `checkbox` | value 的字符串数组 | +| `switch` | `true` / `false` | +| `cascader` | 从顶级一路到末级的字典项 value 数组,半条路径会被挡 | +| `dept` `user` | 部门路径 / 人员身份 DN(只有发起环节放开时才轮得到你传,照 `GET /draft` 里页面存过的写法最稳) | +| `attachment` `image` | 附件对象数组,至少含 `id`:先 `POST /api/v1/attachment` 上传再拿 id | +| `relation` | 关联单据的 `job` | +| `signature` | PNG 的 data URL 字符串 | +| `table` | 行对象数组,行的键取 `columns[].key` | +| `title` | 字符串;传了顶掉标题规则(表单里有标题字段时优先看这一格) | +| `auto` `formula` | 不用传(`system: true`),传了会被服务端按真实数据重算掉 | + +## 7. `notices` 这三类话 + +不是错误,草稿已经存好了;分三类是按"到发起那一刻会不会挡你"排的: + +1. `发起时会被表单校验挡住:…` —— 取值本身不合法(选项值早就不在字典里、级联没选到末级)。现在说,是省一趟返工。 +2. `还差 N 项才提交得了:…(草稿不拦,填全了再发起)` —— 必填还没填。草稿的意义就是先存一半。 +3. `表单里没有这几个字段…` / `「XX」里有 N 行整行没填,已经丢掉` —— 前者照样存着但不算表单值(引擎也是这个口径,不替调用方丢数据);后者是明细表整型,跟提交时做的是同一件事。 + +界面只在发起页提示,不当红色警告弹;外部系统建议把第 1 类当失败处理,第 2 类按需忽略。 + +## 8. 几个容易踩的地方 + +* **草稿不卡必填,也不启动流转**。要直接发起用 `POST /api/v1/job`(页面)或 `POST /open/works`(外部); + 别为了省事硬凑假数据发起——发出去的单子要退回、要终止,比多存一张草稿麻烦得多。 +* **外部建的草稿由本人在页面发起**。开放平台的 `POST /open/works` 不带 `draft_id`,外部铺的单子 + 要本人点开 `pagePath` 确认后自己提交。 +* **同名流程一律报错不猜**。别把 `process` 写成"流程"这种到处都命中的词,用 `refByName` 或直接传 id。 +* **`data` 会原样存**,只有一处例外:明细表按引擎口径整型(丢空行、补列默认值、按 `maxRows` 截断)。 +* **流程下架或发起范围收紧之后**,老草稿还在草稿箱里,但点开会被提示发不起——这是有意留着让人自己确认, + 不是悄悄删数据。 +* 草稿箱没有分页:`GET /api/v1/draft` 一次回全部,拟稿箱不是归档处。 + +## 9. 代码落点 + +* 口径:[backend/app/service/drafts.py](../backend/app/service/drafts.py)(认流程、参数清单、数据体检、标题、落库) +* 页面侧接口:[backend/app/api/support.py](../backend/app/api/support.py) +* 外部侧接口:[backend/app/api/openapi.py](../backend/app/api/openapi.py),授权范围在 + [backend/app/service/openauth.py](../backend/app/service/openauth.py) +* 标题口径:[backend/app/service/titles.py](../backend/app/service/titles.py);发起范围: + [backend/app/service/starters.py](../backend/app/service/starters.py) +* 字段权限与明细表整型:[backend/app/service/formruntime.py](../backend/app/service/formruntime.py) diff --git a/frontend/src/components/oa/FieldRefInput.vue b/frontend/src/components/oa/FieldRefInput.vue new file mode 100644 index 0000000..bf46b68 --- /dev/null +++ b/frontend/src/components/oa/FieldRefInput.vue @@ -0,0 +1,105 @@ + + + diff --git a/frontend/src/components/oa/design/ApproverRuleEditor.vue b/frontend/src/components/oa/design/ApproverRuleEditor.vue new file mode 100644 index 0000000..555701c --- /dev/null +++ b/frontend/src/components/oa/design/ApproverRuleEditor.vue @@ -0,0 +1,312 @@ +