init 初始化
parent
8f9df3953e
commit
5ff8c1eada
|
|
@ -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)
|
||||
|
|
@ -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
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -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)}
|
||||
|
|
@ -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 ""
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -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())
|
||||
|
|
@ -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())
|
||||
|
|
@ -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())
|
||||
|
|
@ -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
|
||||
|
|
@ -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 <access_token>`,令牌来自 `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)
|
||||
|
|
@ -0,0 +1,105 @@
|
|||
<template>
|
||||
<div class="min-w-0 flex-1">
|
||||
<div class="flex items-end gap-1.5">
|
||||
<Input
|
||||
class="min-w-0 flex-1"
|
||||
:model-value="modelValue"
|
||||
:label="label"
|
||||
:placeholder="placeholder"
|
||||
:compact="compact"
|
||||
:disabled="disabled"
|
||||
@update:model-value="emit('update:modelValue', String($event ?? ''))"
|
||||
/>
|
||||
<Select
|
||||
class="w-28 flex-shrink-0"
|
||||
:model-value="''"
|
||||
:options="options"
|
||||
:placeholder="t('form.pickField')"
|
||||
:compact="compact"
|
||||
:disabled="disabled || !options.length"
|
||||
searchable
|
||||
@update:model-value="pick"
|
||||
/>
|
||||
</div>
|
||||
<p v-if="!options.length" class="input-hint">{{ hint }}</p>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 「填一个表单字段引用」的输入框:手写仍然可以,但默认让人从字段清单里挑。
|
||||
*
|
||||
* 额度取值写成 ``{form.amount}``、拆分路径写成 ``detail``、报文映射写成
|
||||
* ``{form.costCenter}``——三种写法各有前缀,所以模板由调用方给(template)。
|
||||
* 之所以保留手写框:老配置、上游字段、``{cents:form.x}`` 这类带前缀的写法都还得能填,
|
||||
* 但没人应该凭记忆去猜字段名——挑一个和敲一个是完全不同的出错率。
|
||||
*/
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import Input from '@/components/common/Input.vue'
|
||||
import Select from '@/components/common/Select.vue'
|
||||
import { fieldTypeLabel, pickableFormFields, type Translate } from '@/utils/approverTargets'
|
||||
import type { FormFieldDef } from '@/types'
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
modelValue: string
|
||||
/** 能挑的表单字段(已经按这一处用得上的类型筛过) */
|
||||
fields?: FormFieldDef[]
|
||||
/** 挑中字段后写进输入框的写法,默认 ``{form.字段名}`` */
|
||||
template?: (key: string, field: FormFieldDef) => string
|
||||
label?: string
|
||||
placeholder?: string
|
||||
compact?: boolean
|
||||
disabled?: boolean
|
||||
/** 没有字段可挑时的说明,各处的原因不一样,由调用方说清楚 */
|
||||
emptyHint?: string
|
||||
}>(),
|
||||
{
|
||||
fields: () => [],
|
||||
template: undefined,
|
||||
label: '',
|
||||
placeholder: '',
|
||||
compact: false,
|
||||
disabled: false,
|
||||
emptyHint: ''
|
||||
}
|
||||
)
|
||||
|
||||
const emit = defineEmits<{ (e: 'update:modelValue', value: string): void }>()
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
/** 挑中一个字段后写进输入框的默认写法。 */
|
||||
function tokenOf(key: string): string {
|
||||
return `{form.${key}}`
|
||||
}
|
||||
|
||||
const options = computed(() => {
|
||||
const list: FormFieldDef[] = pickableFormFields(props.fields as FormFieldDef[])
|
||||
const out: { value: string; label: string; sub: string }[] = []
|
||||
list.forEach((field) => {
|
||||
const key = String(field.key)
|
||||
const label = field.label || key
|
||||
const sub = [fieldTypeLabel(t as Translate, field.type), key].filter(Boolean).join(' · ')
|
||||
const base = (props.template ?? tokenOf)(key, field)
|
||||
out.push({ value: base, label, sub })
|
||||
// 金额顺手给一个分单位写法:对接上游时多半要的是分,而不是让人自己记这个前缀
|
||||
if (field.type === 'money') {
|
||||
out.push({
|
||||
value: `{cents:${base.slice(1)}`,
|
||||
label: `${label} (${t('form.quotaCentsSuffix')})`,
|
||||
sub
|
||||
})
|
||||
}
|
||||
})
|
||||
return out
|
||||
})
|
||||
|
||||
const hint = computed(() => props.emptyHint || t('form.pickFieldNone'))
|
||||
|
||||
function pick(value: string | number | boolean | null) {
|
||||
const token = String(value ?? '')
|
||||
if (token) emit('update:modelValue', token)
|
||||
}
|
||||
</script>
|
||||
|
|
@ -0,0 +1,312 @@
|
|||
<template>
|
||||
<div class="rounded-xl border border-gray-200 p-2.5 dark:border-dark-600">
|
||||
<div class="flex flex-wrap items-baseline justify-between gap-1">
|
||||
<label class="input-label">{{ t(titleKey) }}</label>
|
||||
<button type="button" class="btn btn-ghost btn-sm" @click="addRule">
|
||||
<Icon name="plus" class="mr-1 h-3.5 w-3.5" />
|
||||
{{ t(addKey) }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<p class="input-hint">{{ t(hintKey) }}</p>
|
||||
<p v-if="!rules.length" class="text-xs text-gray-500 dark:text-dark-400">{{ t(emptyKey) }}</p>
|
||||
|
||||
<div
|
||||
v-for="(rule, index) in rules"
|
||||
:key="rule.id || index"
|
||||
class="mb-2 space-y-2.5 rounded-xl border border-gray-200 bg-gray-50/60 p-2.5 last:mb-0 dark:border-dark-600 dark:bg-dark-900/40"
|
||||
>
|
||||
<div class="flex items-center justify-between gap-2">
|
||||
<span class="badge badge-primary">{{ t('process.ruleN', { n: index + 1 }) }}</span>
|
||||
<div class="flex items-center gap-1">
|
||||
<button
|
||||
v-if="index > 0"
|
||||
type="button"
|
||||
class="btn btn-ghost btn-icon"
|
||||
:aria-label="t('common.moveUp')"
|
||||
@click="move(index, -1)"
|
||||
>
|
||||
<Icon name="chevronUp" class="h-4 w-4" />
|
||||
</button>
|
||||
<button
|
||||
v-if="index < rules.length - 1"
|
||||
type="button"
|
||||
class="btn btn-ghost btn-icon"
|
||||
:aria-label="t('common.moveDown')"
|
||||
@click="move(index, 1)"
|
||||
>
|
||||
<Icon name="chevronDown" class="h-4 w-4" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="btn btn-ghost btn-icon text-red-600"
|
||||
:aria-label="t('common.delete')"
|
||||
@click="removeRule(index)"
|
||||
>
|
||||
<Icon name="trash" class="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Input v-model="rule.name" :label="t('process.skipRuleName')" :placeholder="t(namePlaceholderKey)" />
|
||||
|
||||
<div v-if="kind === 'skip'">
|
||||
<label class="input-label">{{ t('process.skipScope') }}</label>
|
||||
<div class="flex gap-1.5">
|
||||
<button
|
||||
v-for="option in scopeOptions"
|
||||
:key="option.value"
|
||||
type="button"
|
||||
class="btn btn-sm flex-1"
|
||||
:class="rule.scope === option.value ? 'btn-primary' : 'btn-secondary'"
|
||||
@click="rule.scope = option.value"
|
||||
>
|
||||
{{ option.label }}
|
||||
</button>
|
||||
</div>
|
||||
<p class="input-hint">
|
||||
{{ rule.scope === 'all' ? t('process.skipScopeAllHint') : t('process.skipScopeMatchedHint') }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<!-- 免审条件:与分支条件同一套搭建器,存的也是同一种表达式文本 -->
|
||||
<div>
|
||||
<div class="flex items-center justify-between gap-2">
|
||||
<label class="input-label !mb-0">{{ t(conditionLabelKey) }}</label>
|
||||
<button
|
||||
v-if="conditionFields.length"
|
||||
type="button"
|
||||
class="btn btn-ghost btn-sm"
|
||||
@click="builderIndex = index"
|
||||
>
|
||||
<Icon name="cog" class="mr-1 h-3.5 w-3.5" />
|
||||
{{ rule.expression ? t('process.condEdit') : t('process.condSetup') }}
|
||||
</button>
|
||||
</div>
|
||||
<div class="mt-1.5 rounded-xl border border-gray-200 px-2.5 py-2 dark:border-dark-600">
|
||||
<p v-if="readableOf(rule.expression)" class="text-xs text-gray-700 dark:text-dark-200">
|
||||
{{ t(conditionHitKey) }} {{ readableOf(rule.expression) }}
|
||||
</p>
|
||||
<p v-else-if="rule.expression" class="break-all font-mono text-[11px] text-gray-500 dark:text-dark-400">
|
||||
{{ rule.expression }}
|
||||
</p>
|
||||
<p v-else-if="!conditionFields.length" class="text-xs text-gray-400">
|
||||
{{ t('process.skipConditionNoForm') }}
|
||||
</p>
|
||||
<p v-else class="text-xs text-amber-600 dark:text-amber-400">{{ t('process.skipConditionNone') }}</p>
|
||||
</div>
|
||||
<!-- 本环节拿不到字段清单(还没定默认表单)时才让手写:老配置与外部字段名总得有条路 -->
|
||||
<div v-if="!conditionFields.length" class="mt-1.5">
|
||||
<TextArea
|
||||
:model-value="rule.expression"
|
||||
:rows="2"
|
||||
:placeholder="t('process.skipConditionPlaceholder')"
|
||||
@update:model-value="rule.expression = String($event ?? '')"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ApproverValueRows
|
||||
v-if="kind === 'must' || rule.scope === 'matched'"
|
||||
v-model="rule.targets"
|
||||
:directory="directory"
|
||||
:fields="fields"
|
||||
:label="t(kind === 'must' ? 'process.mustTargets' : 'process.skipTargets')"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<ConditionBuilderDialog
|
||||
:show="builderIndex >= 0"
|
||||
:fields="conditionFields"
|
||||
:expression="builderIndex >= 0 ? rules[builderIndex]?.expression ?? '' : ''"
|
||||
:title-key="condDialogTitleKey"
|
||||
:intro-key="condDialogIntroKey"
|
||||
:result-prefix-key="conditionHitKey"
|
||||
empty-result-key="process.condEmptyRule"
|
||||
@close="builderIndex = -1"
|
||||
@apply="applyExpression"
|
||||
@clear="applyExpression('')"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 环节的「条件免审 / 条件必批」规则编辑器(同一形状,kind 决定方向)。
|
||||
*
|
||||
* 规则落在 activity.config.skipRules:命中条件时,这一环按 scope 决定是整环免审还是
|
||||
* 只免掉 taskValues 点到的人。被免掉的人不会收到待办,也就不可能被消息打扰;
|
||||
* 谁被为什么免掉,引擎写成一条日志,审批记录里看得见(见 utils/approvalRecord.ts)。
|
||||
*/
|
||||
import { computed, reactive, ref, watch } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import Icon from '@/components/icons/Icon.vue'
|
||||
import Input from '@/components/common/Input.vue'
|
||||
import TextArea from '@/components/common/TextArea.vue'
|
||||
import ApproverValueRows from '@/components/oa/ApproverValueRows.vue'
|
||||
import ConditionBuilderDialog from './ConditionBuilderDialog.vue'
|
||||
import { fromEngineRows, toEngineRows, type ApproverValueRow } from '@/utils/approverTargets'
|
||||
import {
|
||||
COND_OP_LABEL_KEYS,
|
||||
describeRuleSet,
|
||||
parseRuleSet,
|
||||
type RuleContext
|
||||
} from '@/utils/routeExpression'
|
||||
import type { ActivityValue, ApproverOptions, ConditionField, FormFieldDef, SkipRule } from '@/types'
|
||||
|
||||
interface RuleRow {
|
||||
id: string
|
||||
name: string
|
||||
expression: string
|
||||
scope: 'matched' | 'all'
|
||||
targets: ApproverValueRow[]
|
||||
}
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
/** skip = 条件免审,must = 条件必批;两套规则同一形状,只差方向与必填项 */
|
||||
kind?: 'skip' | 'must'
|
||||
modelValue?: SkipRule[]
|
||||
directory?: ApproverOptions | null
|
||||
/** 本环节的表单字段:免审对象选「表单字段」时按它列可挑的字段 */
|
||||
fields?: FormFieldDef[]
|
||||
/** 条件里能引用的字段,与分支条件用的是同一份清单 */
|
||||
conditionFields?: ConditionField[]
|
||||
}>(),
|
||||
{ kind: 'skip', modelValue: () => [], directory: null, fields: () => [], conditionFields: () => [] }
|
||||
)
|
||||
|
||||
const emit = defineEmits<{ (e: 'update:modelValue', value: SkipRule[]): void }>()
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
/** 两套规则各自的文案键,界面骨架只有一份。 */
|
||||
const titleKey = computed(() => (props.kind === 'must' ? 'process.mustRules' : 'process.skipRules'))
|
||||
const addKey = computed(() => (props.kind === 'must' ? 'process.mustRuleAdd' : 'process.skipRuleAdd'))
|
||||
const hintKey = computed(() => (props.kind === 'must' ? 'process.mustRuleHint' : 'process.skipRuleHint'))
|
||||
const emptyKey = computed(() => (props.kind === 'must' ? 'process.mustEmpty' : 'process.skipEmpty'))
|
||||
const namePlaceholderKey = computed(() =>
|
||||
props.kind === 'must' ? 'process.mustNamePlaceholder' : 'process.skipNamePlaceholder'
|
||||
)
|
||||
/** 两套规则的条件说两套话:必批那一格不能顶着「免审条件」的名字。 */
|
||||
const conditionLabelKey = computed(() => (props.kind === 'must' ? 'process.mustCondition' : 'process.skipCondition'))
|
||||
const conditionHitKey = computed(() => (props.kind === 'must' ? 'process.mustConditionHit' : 'process.skipConditionHit'))
|
||||
const condDialogTitleKey = computed(() =>
|
||||
props.kind === 'must' ? 'process.condDialogTitleMust' : 'process.condDialogTitleSkip'
|
||||
)
|
||||
const condDialogIntroKey = computed(() =>
|
||||
props.kind === 'must' ? 'process.condDialogIntroMust' : 'process.condDialogIntroSkip'
|
||||
)
|
||||
|
||||
const rules = reactive<RuleRow[]>([])
|
||||
const builderIndex = ref(-1)
|
||||
|
||||
const scopeOptions = computed(() => [
|
||||
{ value: 'matched' as const, label: t('process.skipScopeMatched') },
|
||||
{ value: 'all' as const, label: t('process.skipScopeAll') }
|
||||
])
|
||||
|
||||
const ruleCtx = computed<RuleContext>(() => ({
|
||||
label: (field) => props.conditionFields.find((item) => item.value === field)?.label ?? field,
|
||||
type: (field) => props.conditionFields.find((item) => item.value === field)?.type ?? '',
|
||||
optionLabel: (field, value) =>
|
||||
props.conditionFields.find((item) => item.value === field)?.options?.find((option) => String(option.value) === value)
|
||||
?.label ?? ''
|
||||
}))
|
||||
|
||||
/** 条件读成人话;手写的式子读不懂就照原样显示,不藏信息。 */
|
||||
function readableOf(expression: string): string {
|
||||
if (!expression) return ''
|
||||
const parsed = parseRuleSet(expression)
|
||||
if (!parsed) return ''
|
||||
return describeRuleSet(parsed, ruleCtx.value, (op) => t(COND_OP_LABEL_KEYS[op] ?? 'process.condOp'))
|
||||
}
|
||||
|
||||
function toRule(row: RuleRow): SkipRule {
|
||||
const whole = props.kind === 'skip' && row.scope === 'all'
|
||||
return {
|
||||
id: row.id,
|
||||
name: row.name,
|
||||
expression: row.expression,
|
||||
...(props.kind === 'must' ? {} : { scope: whole ? ('all' as const) : ('matched' as const) }),
|
||||
...(whole ? {} : { taskValues: toEngineRows(row.targets) as ActivityValue[] })
|
||||
}
|
||||
}
|
||||
|
||||
function fromRule(rule: SkipRule): RuleRow {
|
||||
return {
|
||||
id: rule.id || newRuleId(),
|
||||
name: rule.name ?? '',
|
||||
expression: rule.expression ?? '',
|
||||
scope: rule.scope === 'all' ? 'all' : 'matched',
|
||||
targets: fromEngineRows((rule.taskValues ?? []) as { type?: string; data?: (string | number)[] }[])
|
||||
}
|
||||
}
|
||||
|
||||
function newRuleId(): string {
|
||||
return `${props.kind}_${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`
|
||||
}
|
||||
|
||||
function syncFromProps(list: SkipRule[]) {
|
||||
rules.splice(0, rules.length, ...(list ?? []).map(fromRule))
|
||||
}
|
||||
|
||||
function addRule() {
|
||||
rules.push({
|
||||
id: newRuleId(),
|
||||
name: '',
|
||||
expression: '',
|
||||
scope: props.kind === 'must' ? 'matched' : 'matched',
|
||||
targets: props.kind === 'must' ? [{ type: 'role', data: [], identities: [], containsSub: true }] : []
|
||||
})
|
||||
}
|
||||
|
||||
function removeRule(index: number) {
|
||||
rules.splice(index, 1)
|
||||
if (builderIndex.value === index) builderIndex.value = -1
|
||||
else if (builderIndex.value > index) builderIndex.value -= 1
|
||||
}
|
||||
|
||||
function move(index: number, offset: number) {
|
||||
const target = index + offset
|
||||
if (target < 0 || target >= rules.length) return
|
||||
const [row] = rules.splice(index, 1)
|
||||
rules.splice(target, 0, row)
|
||||
builderIndex.value = -1
|
||||
}
|
||||
|
||||
function applyExpression(expression: string) {
|
||||
const row = rules[builderIndex.value]
|
||||
if (row) row.expression = expression
|
||||
builderIndex.value = -1
|
||||
}
|
||||
|
||||
/**
|
||||
* 与 CcRuleEditor 同一套防回声写法:父端每次读取都会重建数组,
|
||||
* 本地用 reactive 行编辑,按内容比对才能断掉「发出 -> 回流 -> 再发出」。
|
||||
*/
|
||||
let emitted = ''
|
||||
|
||||
watch(
|
||||
() => props.modelValue,
|
||||
(list) => {
|
||||
const incoming = JSON.stringify((list ?? []).map(fromRule).map(toRule))
|
||||
if (incoming === emitted) return
|
||||
emitted = incoming
|
||||
syncFromProps(list ?? [])
|
||||
},
|
||||
{ immediate: true, deep: true }
|
||||
)
|
||||
|
||||
watch(
|
||||
rules,
|
||||
() => {
|
||||
const next = rules.map(toRule)
|
||||
const serialized = JSON.stringify(next)
|
||||
if (serialized === emitted) return
|
||||
emitted = serialized
|
||||
emit('update:modelValue', next)
|
||||
},
|
||||
{ deep: true }
|
||||
)
|
||||
</script>
|
||||
|
|
@ -0,0 +1,295 @@
|
|||
<template>
|
||||
<div class="space-y-3">
|
||||
<!-- 顶部:这一份结论是什么时候算的 -->
|
||||
<div class="flex items-start justify-between gap-2">
|
||||
<p class="min-w-0 flex-1 text-xs leading-5 text-gray-500 dark:text-dark-400">{{ headline }}</p>
|
||||
<button type="button" class="btn btn-secondary btn-sm shrink-0" :disabled="running" @click="emit('run')">
|
||||
<Icon name="refresh" class="mr-1 h-3.5 w-3.5" :class="running ? 'animate-spin' : ''" />
|
||||
{{ t(running ? 'process.dedupAuditRunning' : 'process.dedupAuditRun') }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<p v-if="failed" class="rounded-xl border border-red-200 bg-red-50 px-3 py-2 text-xs text-red-700 dark:border-red-900/50 dark:bg-red-950/40 dark:text-red-300">
|
||||
{{ t('process.dedupAuditFailed') }}
|
||||
</p>
|
||||
|
||||
<!-- 生效的流程默认:体检结论全靠这一档,所以先把它摆明处 -->
|
||||
<div v-if="result" class="rounded-xl border border-gray-200 px-3 py-2.5 dark:border-dark-600">
|
||||
<div class="flex items-center justify-between gap-2">
|
||||
<p class="text-xs text-gray-500 dark:text-dark-400">{{ t('process.dedupAuditFlowPolicy') }}</p>
|
||||
<span class="badge badge-gray">{{ policyLabel }}</span>
|
||||
</div>
|
||||
<p class="input-hint">{{ t(`process.repeatPolicyHint.${flowPolicy}`) }}</p>
|
||||
<button type="button" class="btn btn-ghost btn-sm mt-1.5 w-full" @click="emit('open-meta')">
|
||||
<Icon name="cog" class="mr-1 h-3.5 w-3.5" />
|
||||
{{ t('process.dedupAuditEditPolicy') }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- 统计条 -->
|
||||
<div v-if="result" class="grid gap-1.5" :class="stats.length > 3 ? 'grid-cols-4' : 'grid-cols-3'">
|
||||
<div v-for="stat in stats" :key="stat.key" class="rounded-lg bg-gray-50 px-2 py-1.5 text-center dark:bg-dark-900/60">
|
||||
<p class="text-sm font-semibold tabular-nums" :class="stat.tone">{{ stat.value }}</p>
|
||||
<p class="mt-0.5 truncate text-[10px] text-gray-500 dark:text-dark-400">{{ stat.label }}</p>
|
||||
</div>
|
||||
</div>
|
||||
<p v-if="unresolved" class="text-[11px] leading-4 text-gray-400 dark:text-dark-500">
|
||||
{{ t('process.dedupAuditUnresolved', { count: unresolved }) }}
|
||||
</p>
|
||||
|
||||
<!-- 一处重复都没有 -->
|
||||
<div
|
||||
v-if="result && !result.groups.length"
|
||||
class="flex items-start gap-2 rounded-xl border border-emerald-200 bg-emerald-50 px-3 py-2.5 dark:border-emerald-900/50 dark:bg-emerald-950/40"
|
||||
>
|
||||
<Icon name="checkCircle" class="mt-0.5 h-4 w-4 shrink-0 text-emerald-600 dark:text-emerald-400" />
|
||||
<div class="min-w-0">
|
||||
<p class="text-xs font-medium text-emerald-800 dark:text-emerald-300">{{ t('process.dedupAuditClean') }}</p>
|
||||
<p class="mt-0.5 text-[11px] leading-4 text-emerald-700/80 dark:text-emerald-400/80">
|
||||
{{ t('process.dedupAuditCleanHint') }}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 修法建议:一次改动就能把「还要签两次」抹平的那一下 -->
|
||||
<div v-if="fix" class="rounded-xl border border-indigo-200 bg-indigo-50/70 px-3 py-2.5 dark:border-indigo-900/50 dark:bg-indigo-950/30">
|
||||
<p class="text-xs leading-5 text-indigo-900 dark:text-indigo-200">{{ fixText }}</p>
|
||||
<button type="button" class="btn btn-primary btn-sm mt-2 w-full" @click="emit('apply-fix', fix)">
|
||||
<Icon name="sparkles" class="mr-1 h-3.5 w-3.5" />
|
||||
{{ applyLabel }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- 逐个人 -->
|
||||
<div v-for="group in groups" :key="group.person" class="rounded-xl border border-gray-200 px-3 py-2.5 dark:border-dark-600">
|
||||
<button type="button" class="flex w-full items-center gap-1.5 text-left" @click="toggle(group)">
|
||||
<Icon :name="VERDICT_ICONS[group.verdict]" class="h-3.5 w-3.5 shrink-0" :class="VERDICT_TONES[group.verdict]" />
|
||||
<span class="min-w-0 flex-1 truncate text-sm font-medium text-gray-900 dark:text-white">{{ group.name }}</span>
|
||||
<span v-if="group.dynamic" class="badge badge-gray shrink-0">{{ t('process.dedupAuditRuntime') }}</span>
|
||||
<span class="badge shrink-0" :class="VERDICT_BADGES[group.verdict]">{{ t(VERDICT_KEYS[group.verdict]) }}</span>
|
||||
<Icon :name="open.has(group.person) ? 'chevronDown' : 'chevronRight'" class="h-3.5 w-3.5 shrink-0 text-gray-400" />
|
||||
</button>
|
||||
|
||||
<div v-if="open.has(group.person)" class="mt-2 space-y-2">
|
||||
<!-- 这一单上他会走到的环节:点了直接跳到画布上那一环 -->
|
||||
<div class="flex flex-wrap items-center gap-1">
|
||||
<template v-for="(node, index) in group.nodes" :key="node.id">
|
||||
<Icon v-if="index" name="chevronRight" class="h-3 w-3 shrink-0 text-gray-300 dark:text-dark-500" />
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-md border px-1.5 py-0.5 text-[11px] leading-4 transition hover:border-current"
|
||||
:class="[ROLE_CLASSES[node.role], node.inherited ? '' : 'font-medium']"
|
||||
:title="nodeTitle(node)"
|
||||
@click="emit('focus', node.id)"
|
||||
>
|
||||
{{ node.name }}
|
||||
</button>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<!-- 逐对结论:凭什么叫他签两次、凭什么自动跳过 -->
|
||||
<ul v-if="group.pairs.length" class="space-y-1">
|
||||
<li
|
||||
v-for="(pair, index) in group.pairs"
|
||||
:key="`${pair.from}-${pair.to}-${index}`"
|
||||
class="flex items-start gap-1 text-[11px] leading-4 text-gray-500 dark:text-dark-400"
|
||||
>
|
||||
<Icon :name="pair.settled ? 'infoCircle' : 'exclamationTriangle'" class="mt-0.5 h-3 w-3 shrink-0" :class="pair.settled ? '' : 'text-amber-500'" />
|
||||
<span class="min-w-0">
|
||||
{{ pair.from_name }} → {{ pair.to_name }}:{{ pair.reason }}
|
||||
<span v-if="!pair.certain" class="text-amber-600 dark:text-amber-400">{{ t('process.dedupAuditUncertain') }}</span>
|
||||
<span v-if="pair.conditional" class="badge badge-gray ml-1 align-middle">{{ t('process.dedupAuditConditional') }}</span>
|
||||
<span v-if="pair.entry" class="mt-0.5 block text-gray-400 dark:text-dark-500">
|
||||
{{ t('process.dedupAuditEntry', { entry: pair.entry }) }}
|
||||
</span>
|
||||
<span v-for="(blocker, bi) in pair.blockers" :key="bi" class="mt-0.5 block text-gray-400 dark:text-dark-500">
|
||||
· {{ t('process.dedupAuditBlocker', { ...blocker }) }}
|
||||
</span>
|
||||
</span>
|
||||
</li>
|
||||
</ul>
|
||||
<p v-else class="text-[11px] leading-4 text-gray-500 dark:text-dark-400">{{ t('process.dedupAuditBranchHint') }}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 按分支条件排除掉的重复:不算重复,但要让人看见是凭什么排除的 -->
|
||||
<div v-if="impasses.length" class="rounded-xl border border-gray-200 px-3 py-2.5 dark:border-dark-600">
|
||||
<button type="button" class="flex w-full items-center gap-1 text-left text-xs text-gray-600 dark:text-dark-300" @click="impassesVisible = !impassesVisible">
|
||||
<Icon :name="impassesVisible ? 'chevronDown' : 'chevronRight'" class="h-3.5 w-3.5" />
|
||||
{{ t('process.dedupImpassTitle', { count: impasses.length }) }}
|
||||
</button>
|
||||
<template v-if="impassesVisible">
|
||||
<p class="mt-1 text-[11px] leading-4 text-gray-500 dark:text-dark-400">{{ t('process.dedupImpassHint') }}</p>
|
||||
<ul class="mt-1.5 space-y-1">
|
||||
<li v-for="item in impasses" :key="`${item.from}-${item.to}`" class="text-[11px] leading-4 text-gray-500 dark:text-dark-400">
|
||||
<button type="button" class="font-medium text-gray-700 hover:underline dark:text-dark-200" @click="emit('focus', item.from)">
|
||||
{{ item.name }}
|
||||
</button>
|
||||
:{{ item.from_name }} → {{ item.to_name }}——{{ item.reason }}
|
||||
</li>
|
||||
</ul>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<!-- 试算本身的边界:找人没定、动态找人这些,一句一句摊开 -->
|
||||
<div v-if="notes.length" class="rounded-xl border border-gray-200 px-3 py-2.5 dark:border-dark-600">
|
||||
<button type="button" class="flex w-full items-center gap-1 text-left text-xs text-gray-600 dark:text-dark-300" @click="notesVisible = !notesVisible">
|
||||
<Icon :name="notesVisible ? 'chevronDown' : 'chevronRight'" class="h-3.5 w-3.5" />
|
||||
{{ t('process.dedupAuditNotes', { count: notes.length }) }}
|
||||
</button>
|
||||
<ul v-if="notesVisible" class="mt-1.5 space-y-1">
|
||||
<li v-for="(note, index) in notes" :key="index" class="text-[11px] leading-4 text-gray-500 dark:text-dark-400">
|
||||
· {{ note }}
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, reactive, ref, watch } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import Icon from '@/components/icons/Icon.vue'
|
||||
import { formatTime } from '@/utils/format'
|
||||
import { DEDUP_POLICIES, DEDUP_POLICY_KEYS, type DedupPolicy } from '@/utils/approvalDedup'
|
||||
import { dedupNodeNotes, type DedupFix } from '@/utils/dedupAudit'
|
||||
import type { DedupAuditGroup, DedupAuditGroupNode, DedupAuditResult, DedupRole } from '@/types'
|
||||
|
||||
const props = defineProps<{
|
||||
result: DedupAuditResult | null
|
||||
running: boolean
|
||||
failed: boolean
|
||||
/** 上一次试算落在什么时候,用来判断这份结论还新不新 */
|
||||
ranAt: Date | null
|
||||
/** 算完之后画布又动过:这一份结论对不上当下那张图了 */
|
||||
stale: boolean
|
||||
/** 一键能按下去的那个修法,没有就不显示建议 */
|
||||
fix: DedupFix | null
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'run'): void
|
||||
(e: 'focus', id: string): void
|
||||
(e: 'apply-fix', fix: DedupFix): void
|
||||
(e: 'open-meta'): void
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const VERDICT_KEYS: Record<string, string> = {
|
||||
open: 'process.dedupVerdictOpen',
|
||||
watch: 'process.dedupVerdictWatch',
|
||||
covered: 'process.dedupVerdictCovered',
|
||||
branch: 'process.dedupVerdictBranch'
|
||||
}
|
||||
const VERDICT_BADGES: Record<string, string> = {
|
||||
open: 'badge-danger',
|
||||
watch: 'badge-warning',
|
||||
covered: 'badge-success',
|
||||
branch: 'badge-gray'
|
||||
}
|
||||
const VERDICT_TONES: Record<string, string> = {
|
||||
open: 'text-red-500',
|
||||
watch: 'text-amber-500',
|
||||
covered: 'text-emerald-500',
|
||||
branch: 'text-gray-400'
|
||||
}
|
||||
const VERDICT_ICONS: Record<string, 'ban' | 'exclamationTriangle' | 'checkCircle' | 'shuffle'> = {
|
||||
open: 'ban',
|
||||
watch: 'exclamationTriangle',
|
||||
covered: 'checkCircle',
|
||||
branch: 'shuffle'
|
||||
}
|
||||
/** 环节在结论里的角色:这一环到底要不要他签。 */
|
||||
const ROLE_KEYS: Record<DedupRole, string> = {
|
||||
sign: 'process.dedupRoleSign',
|
||||
skip: 'process.dedupRoleSkip',
|
||||
double: 'process.dedupRoleDouble',
|
||||
watch: 'process.dedupRoleWatch'
|
||||
}
|
||||
const ROLE_CLASSES: Record<DedupRole, string> = {
|
||||
sign: 'border-gray-200 text-gray-700 dark:border-dark-600 dark:text-dark-200',
|
||||
skip: 'border-emerald-200 bg-emerald-50 text-emerald-700 dark:border-emerald-900/60 dark:bg-emerald-950/40 dark:text-emerald-300',
|
||||
double: 'border-red-200 bg-red-50 text-red-700 dark:border-red-900/50 dark:bg-red-950/40 dark:text-red-300',
|
||||
watch: 'border-amber-200 bg-amber-50 text-amber-700 dark:border-amber-900/50 dark:bg-amber-950/40 dark:text-amber-300'
|
||||
}
|
||||
|
||||
const groups = computed(() => props.result?.groups ?? [])
|
||||
const impasses = computed(() => props.result?.impasses ?? [])
|
||||
const notes = computed(() => dedupNodeNotes(props.result))
|
||||
const notesVisible = ref(false)
|
||||
const impassesVisible = ref(false)
|
||||
|
||||
/** 判得准的先展开,「已管住 / 分支互斥」收着,别让一屏全是绿勾看不到重点。 */
|
||||
const open = reactive(new Set<string>())
|
||||
watch(
|
||||
groups,
|
||||
(list) => {
|
||||
list.forEach((group) => {
|
||||
if (group.verdict === 'open' || group.verdict === 'watch') open.add(group.person)
|
||||
})
|
||||
},
|
||||
{ immediate: true }
|
||||
)
|
||||
|
||||
const flowPolicy = computed<DedupPolicy>(() => {
|
||||
const raw = String(props.result?.policy ?? 'each')
|
||||
return (DEDUP_POLICIES as string[]).includes(raw) ? (raw as DedupPolicy) : 'each'
|
||||
})
|
||||
const policyLabel = computed(() => t(`process.${DEDUP_POLICY_KEYS[flowPolicy.value]}`))
|
||||
|
||||
const headline = computed(() => {
|
||||
if (props.running) return t('process.dedupAuditRunningNow')
|
||||
if (!props.result) return t('process.dedupAuditNever')
|
||||
const base = t('process.dedupAuditAt', {
|
||||
at: props.ranAt ? formatTime(props.ranAt) : '--:--',
|
||||
who: props.result.as_identity_name || t('process.dedupAuditSelf')
|
||||
})
|
||||
return props.stale ? `${base} · ${t('process.dedupAuditStale')}` : base
|
||||
})
|
||||
|
||||
const stats = computed(() => {
|
||||
const s = props.result?.stats
|
||||
if (!s) return []
|
||||
const good = 'text-emerald-600 dark:text-emerald-400'
|
||||
return [
|
||||
{ key: 'people', value: s.groups, label: t('process.dedupStatPeople'), tone: s.groups ? 'text-gray-900 dark:text-white' : good },
|
||||
{ key: 'open', value: s.open, label: t('process.dedupStatOpen'), tone: s.open ? 'text-red-600 dark:text-red-400' : good },
|
||||
{ key: 'watch', value: s.watch, label: t('process.dedupStatWatch'), tone: s.watch ? 'text-amber-600 dark:text-amber-400' : good },
|
||||
// 分支条件互斥、根本走不到一起的那些:不是问题,但要说一声,别以为体检没看条件
|
||||
...(s.impossible
|
||||
? [{ key: 'impossible', value: s.impossible, label: t('process.dedupStatImpass'), tone: 'text-gray-900 dark:text-white' }]
|
||||
: [])
|
||||
]
|
||||
})
|
||||
|
||||
/** 当场算不出人的环节:这一部分没算进结论,得说在前面,别让人以为「没有重复」是满屏算完的。 */
|
||||
const unresolved = computed(() => {
|
||||
const s = props.result?.stats
|
||||
return s ? Math.max(0, s.manual - s.resolved) : 0
|
||||
})
|
||||
|
||||
const fixText = computed(() => {
|
||||
const fix = props.fix
|
||||
if (!fix) return ''
|
||||
return fix.kind === 'flow'
|
||||
? t('process.dedupFixFlowHint', { policy: t(`process.${DEDUP_POLICY_KEYS[fix.policy]}`) })
|
||||
: t('process.dedupFixFollowHint', { count: fix.nodeIds.length })
|
||||
})
|
||||
const applyLabel = computed(() => (props.fix?.kind === 'flow' ? t('process.dedupFixFlowApply') : t('process.dedupFixFollowApply')))
|
||||
|
||||
function toggle(group: DedupAuditGroup) {
|
||||
if (open.has(group.person)) open.delete(group.person)
|
||||
else open.add(group.person)
|
||||
}
|
||||
|
||||
/** 环节那一格的全名:角色 + 生效的那一档 + 凭什么。 */
|
||||
function nodeTitle(node: DedupAuditGroupNode): string {
|
||||
const known = (DEDUP_POLICIES as string[]).includes(node.policy)
|
||||
const policy = known
|
||||
? `${t('process.dedupAuditNodePolicy')}:${t(`process.${DEDUP_POLICY_KEYS[node.policy as DedupPolicy]}`)}` +
|
||||
(node.inherited ? `(${t('process.dedupPolicyFollow')})` : `(${t('process.dedupAuditPinned')})`)
|
||||
: ''
|
||||
return [t(ROLE_KEYS[node.role]), policy, node.note].filter(Boolean).join('\n')
|
||||
}
|
||||
</script>
|
||||
|
|
@ -0,0 +1,111 @@
|
|||
<template>
|
||||
<div :class="dense ? 'grid grid-cols-2 gap-1.5' : 'space-y-2'">
|
||||
<div>
|
||||
<span v-if="showLabel" class="input-label">{{ t('form.relationCategory') }}</span>
|
||||
<Select
|
||||
:model-value="category"
|
||||
:options="categoryOptions"
|
||||
:placeholder="t('form.relationCategoryAll')"
|
||||
:compact="dense"
|
||||
@update:model-value="pickCategory(String($event))"
|
||||
/>
|
||||
<p v-if="showLabel" class="input-hint">{{ t('form.relationCategoryHint') }}</p>
|
||||
</div>
|
||||
<div>
|
||||
<span v-if="showLabel" class="input-label">{{ label }}</span>
|
||||
<Select
|
||||
:model-value="modelValue"
|
||||
:options="processOptions"
|
||||
:placeholder="placeholder"
|
||||
:loading="loading"
|
||||
searchable
|
||||
:compact="dense"
|
||||
@update:model-value="emit('update:modelValue', String($event))"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 「先选流程类型,再选具体流程」的两级选择器。
|
||||
*
|
||||
* 关联审批单、带出另一个流程的数据,都是要先挑一条流程出来的地方。流程多了以后
|
||||
* 光看名字挑不准——同名环节、只有一字之差的报销单,选错了要等单子发出去才发现。
|
||||
* 所以这里把类型(流程分类)摆在前面当第一道筛子:选完类型,下面那一列就只剩这一类的流程。
|
||||
*
|
||||
* 存下来的仍然只有流程 id:类型只是找流程时的筛子,不是配置的一部分,
|
||||
* 分类改了、挪了,已配好的关联关系跟着流程走,不会跟着散架。
|
||||
*/
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import Select from '@/components/common/Select.vue'
|
||||
import { UNCATEGORISED, categoryOf, processCatalog } from '@/utils/processCatalog'
|
||||
import type { Category, ProcessDef } from '@/types'
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
modelValue: string
|
||||
label?: string
|
||||
placeholder?: string
|
||||
/** 明细表列那种窄地方:两栏并排、不放标题 */
|
||||
dense?: boolean
|
||||
loading?: boolean
|
||||
}>(),
|
||||
{ label: '', placeholder: '', dense: false, loading: false }
|
||||
)
|
||||
const emit = defineEmits<{ (e: 'update:modelValue', value: string): void }>()
|
||||
const { t } = useI18n()
|
||||
|
||||
const categories = ref<Category[]>([])
|
||||
const processes = ref<ProcessDef[]>([])
|
||||
const category = ref('')
|
||||
|
||||
const showLabel = computed(() => !props.dense)
|
||||
const visible = computed(() =>
|
||||
category.value ? processes.value.filter((item) => categoryOf(item) === category.value) : processes.value
|
||||
)
|
||||
const categoryOptions = computed(() => {
|
||||
const used = new Set(processes.value.map(categoryOf))
|
||||
const rows = categories.value
|
||||
.filter((item) => used.has(item.id))
|
||||
.map((item) => ({
|
||||
value: item.id,
|
||||
label: `${item.name}(${processes.value.filter((row) => categoryOf(row) === item.id).length})`
|
||||
}))
|
||||
if (used.has(UNCATEGORISED)) {
|
||||
rows.push({
|
||||
value: UNCATEGORISED,
|
||||
label: `${t('form.relationUncategorised')}(${processes.value.filter((row) => !row.category).length})`
|
||||
})
|
||||
}
|
||||
return [{ value: '', label: t('form.relationCategoryAll') }, ...rows]
|
||||
})
|
||||
const processOptions = computed(() =>
|
||||
visible.value.map((item) => ({
|
||||
value: item.id,
|
||||
label: item.published ? item.name : `${item.name} · ${t('form.relationDraft')}`
|
||||
}))
|
||||
)
|
||||
|
||||
/** 选中了哪条流程,类型就跟着钉到那一类:回显时下面那一列一定能看到当前选中的流程。 */
|
||||
watch(
|
||||
() => [props.modelValue, processes.value.length],
|
||||
() => {
|
||||
const row = processes.value.find((item) => item.id === props.modelValue)
|
||||
if (row) category.value = categoryOf(row)
|
||||
},
|
||||
{ immediate: true }
|
||||
)
|
||||
|
||||
function pickCategory(value: string) {
|
||||
category.value = value
|
||||
const row = processes.value.find((item) => item.id === props.modelValue)
|
||||
if (row && value && categoryOf(row) !== value) emit('update:modelValue', '')
|
||||
}
|
||||
|
||||
processCatalog().then((rows) => {
|
||||
categories.value = rows.categories
|
||||
processes.value = rows.processes
|
||||
})
|
||||
</script>
|
||||
|
|
@ -0,0 +1,471 @@
|
|||
<template>
|
||||
<BaseDialog :show="show" :title="t('process.simulateTitle')" width="extra-wide" @close="emit('close')">
|
||||
<div class="grid gap-4 lg:grid-cols-[minmax(300px,1fr)_minmax(420px,1.3fr)]">
|
||||
<!-- 左:这一单由谁发起、填了什么 -->
|
||||
<div class="min-w-0 space-y-3">
|
||||
<div>
|
||||
<label class="input-label">{{ t('process.simulateStarter') }}</label>
|
||||
<PeoplePicker
|
||||
:model-value="starter"
|
||||
:multiple="false"
|
||||
:placeholder="t('process.simulateStarterPlaceholder')"
|
||||
@update:model-value="onStarter"
|
||||
/>
|
||||
<p class="input-hint">{{ t('process.simulateStarterHint') }}</p>
|
||||
</div>
|
||||
<div class="max-h-[52vh] overflow-y-auto rounded-xl border border-gray-200 px-3 py-2 dark:border-dark-600">
|
||||
<FormRenderer
|
||||
v-if="schema"
|
||||
:schema="schema"
|
||||
:model-value="data"
|
||||
:process="processId"
|
||||
:process-name="processName"
|
||||
:as-identity="starterIdentity"
|
||||
@update:model-value="data = $event"
|
||||
/>
|
||||
<p v-else class="py-6 text-center text-sm text-gray-400">{{ t('process.simulateFormEmpty') }}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 右:预测结论 -->
|
||||
<div class="min-w-0 space-y-3">
|
||||
<div v-if="running && !result" class="flex items-center justify-center gap-2 rounded-xl bg-gray-50 py-10 text-sm text-gray-500 dark:bg-dark-900/60 dark:text-dark-400">
|
||||
<Icon name="sync" class="h-4 w-4 animate-spin" />
|
||||
{{ t('process.simulateRunning') }}
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-else-if="result"
|
||||
class="rounded-xl border px-3 py-2.5"
|
||||
:class="VERDICT_BOX[result.verdict]"
|
||||
>
|
||||
<div class="flex items-start gap-2">
|
||||
<Icon :name="VERDICT_ICONS[result.verdict]" class="mt-0.5 h-4 w-4 shrink-0" :class="VERDICT_TONES[result.verdict]" />
|
||||
<div class="min-w-0 flex-1">
|
||||
<p class="text-sm font-medium" :class="VERDICT_TONES[result.verdict]">{{ t(VERDICT_KEYS[result.verdict]) }}</p>
|
||||
<p class="mt-0.5 text-[11px] leading-4 opacity-80">{{ verdictHint }}</p>
|
||||
<p class="mt-1 text-[11px] leading-4 opacity-70">
|
||||
{{ t('process.simulateStats', {
|
||||
reached: result.summary.reached,
|
||||
total: result.summary.nodes,
|
||||
skipped: result.summary.skipped,
|
||||
paths: result.summary.paths,
|
||||
starter: result.starter.name || '--'
|
||||
}) }}
|
||||
</p>
|
||||
</div>
|
||||
<button type="button" class="btn btn-secondary btn-sm shrink-0" :disabled="running" @click="run(true)">
|
||||
<Icon name="refresh" class="mr-1 h-3.5 w-3.5" :class="running ? 'animate-spin' : ''" />
|
||||
{{ t(running ? 'process.simulateRunning' : 'process.simulateRun') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p v-if="failed" class="rounded-xl border border-red-200 bg-red-50 px-3 py-2 text-xs text-red-700 dark:border-red-900/50 dark:bg-red-950/40 dark:text-red-300">
|
||||
{{ t('process.simulateFailed') }}
|
||||
</p>
|
||||
<p v-else-if="stale" class="text-[11px] leading-4 text-amber-600 dark:text-amber-400">
|
||||
{{ t('process.simulateStale') }}
|
||||
</p>
|
||||
|
||||
<div class="tabs">
|
||||
<button type="button" class="tab" :class="{ 'tab-active': view === 'flow' }" @click="view = 'flow'">
|
||||
{{ t('process.simulateTabFlow') }}
|
||||
</button>
|
||||
<button type="button" class="tab" :class="{ 'tab-active': view === 'steps' }" @click="view = 'steps'">
|
||||
{{ t('process.simulateTabSteps') }}
|
||||
</button>
|
||||
<button type="button" class="tab" :class="{ 'tab-active': view === 'issues' }" @click="view = 'issues'">
|
||||
{{ t('process.simulateTabIssues', { count: result?.findings.length ?? 0 }) }}
|
||||
<span v-if="errorCount" class="badge badge-danger ml-1">{{ errorCount }}</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="max-h-[52vh] overflow-y-auto">
|
||||
<FlowTrajectory
|
||||
v-if="view === 'flow' && result"
|
||||
mode="predict"
|
||||
:flow="result.flow"
|
||||
:routes="trajectoryRoutes"
|
||||
:height="330"
|
||||
@select="emit('focus', $event)"
|
||||
/>
|
||||
<p v-else-if="view === 'flow'" class="py-10 text-center text-sm text-gray-400">{{ t('process.simulateEmpty') }}</p>
|
||||
|
||||
<div v-else-if="view === 'steps'" class="space-y-2">
|
||||
<div
|
||||
v-for="step in result?.steps ?? []"
|
||||
:key="`${step.index}-${step.activity}`"
|
||||
class="rounded-xl border border-gray-200 px-3 py-2.5 dark:border-dark-600"
|
||||
:class="step.state === 'blocked' || step.state === 'stopped' ? 'border-red-200 dark:border-red-900/50' : ''"
|
||||
>
|
||||
<button type="button" class="flex w-full items-center gap-1.5 text-left" @click="emit('focus', step.activity)">
|
||||
<span class="h-2 w-2 shrink-0 rounded-full" :class="STATE_DOTS[step.state]"></span>
|
||||
<span class="w-5 shrink-0 text-[11px] tabular-nums text-gray-400">{{ step.index }}</span>
|
||||
<span class="min-w-0 flex-1 truncate text-sm font-medium text-gray-900 dark:text-white">{{ step.name }}</span>
|
||||
<span v-if="step.branch" class="badge badge-gray shrink-0 max-w-[38%] truncate">{{ step.branch }}</span>
|
||||
<span class="badge shrink-0" :class="STATE_BADGES[step.state]">{{ t(STATE_KEYS[step.state]) }}</span>
|
||||
</button>
|
||||
<div class="mt-1.5 space-y-1 pl-[26px] text-[11px] leading-4">
|
||||
<p v-if="step.via" class="text-gray-400">{{ t('process.simulateVia', { name: step.via }) }}</p>
|
||||
<p v-if="step.handlers.length" class="flex flex-wrap items-center gap-1 text-gray-600 dark:text-dark-300">
|
||||
<Icon name="userCheck" class="h-3 w-3 shrink-0 text-gray-400" />
|
||||
<span v-for="person in step.handlers" :key="person.identity" class="rounded bg-gray-100 px-1.5 py-0.5 dark:bg-dark-700">
|
||||
{{ person.name }}<span v-if="person.unit" class="text-gray-400"> · {{ person.unit }}</span
|
||||
><span v-if="person.reason" class="text-amber-600 dark:text-amber-400"> · {{ person.reason }}</span>
|
||||
</span>
|
||||
<span v-if="step.mode" class="text-gray-400">{{ modeLabel(step.mode) }}</span>
|
||||
</p>
|
||||
<p v-else-if="step.state === 'passed' || step.state === 'skipped'" class="text-gray-400">
|
||||
{{ t('process.simulateNobody') }}
|
||||
</p>
|
||||
<p v-if="step.dropped.length" class="flex flex-wrap items-center gap-1 text-gray-500 dark:text-dark-400">
|
||||
<Icon name="ban" class="h-3 w-3 shrink-0 text-gray-400" />
|
||||
<span v-for="person in step.dropped" :key="`${person.name}-${person.reason}`" class="rounded bg-amber-50 px-1.5 py-0.5 text-amber-700 dark:bg-amber-900/30 dark:text-amber-200">
|
||||
{{ person.name }}:{{ person.reason }}
|
||||
</span>
|
||||
</p>
|
||||
<p v-if="step.watchers.length" class="flex flex-wrap items-center gap-1 text-gray-500 dark:text-dark-400">
|
||||
<Icon name="mail" class="h-3 w-3 shrink-0 text-gray-400" />
|
||||
{{ t('process.simulateCc') }}:{{ step.watchers.map((item) => item.name).join('、') }}
|
||||
</p>
|
||||
<p
|
||||
v-for="outcome in step.outcomes.filter((item) => !item.guard_ok)"
|
||||
:key="outcome.route"
|
||||
class="text-amber-600 dark:text-amber-400"
|
||||
>
|
||||
{{ t('process.simulateGuardOff', { name: outcome.name }) }}
|
||||
</p>
|
||||
<p v-if="step.note" class="text-gray-500 dark:text-dark-400">{{ step.note }}</p>
|
||||
</div>
|
||||
</div>
|
||||
<p v-if="result && !result.steps.length" class="py-10 text-center text-sm text-gray-400">{{ t('process.simulateEmpty') }}</p>
|
||||
</div>
|
||||
|
||||
<div v-else class="space-y-1.5">
|
||||
<button
|
||||
v-for="(finding, index) in result?.findings ?? []"
|
||||
:key="`${finding.level}-${index}`"
|
||||
type="button"
|
||||
class="flex w-full items-start gap-2 rounded-xl border px-3 py-2 text-left text-xs leading-5 transition"
|
||||
:class="[LEVEL_BOX[finding.level], finding.activity ? 'hover:border-current' : 'cursor-default']"
|
||||
@click="finding.activity && emit('focus', finding.activity)"
|
||||
>
|
||||
<Icon :name="LEVEL_ICONS[finding.level]" class="mt-0.5 h-3.5 w-3.5 shrink-0" :class="LEVEL_TONES[finding.level]" />
|
||||
<span class="min-w-0 flex-1">{{ finding.message }}</span>
|
||||
<Icon v-if="finding.activity" name="cornerDownRight" class="mt-0.5 h-3.5 w-3.5 shrink-0 opacity-50" />
|
||||
</button>
|
||||
<div
|
||||
v-if="result && !result.findings.length"
|
||||
class="flex items-start gap-2 rounded-xl border border-emerald-200 bg-emerald-50 px-3 py-2.5 dark:border-emerald-900/50 dark:bg-emerald-950/40"
|
||||
>
|
||||
<Icon name="checkCircle" class="mt-0.5 h-4 w-4 shrink-0 text-emerald-600 dark:text-emerald-400" />
|
||||
<p class="text-xs text-emerald-800 dark:text-emerald-300">{{ t('process.simulateClean') }}</p>
|
||||
</div>
|
||||
<p v-if="!result" class="py-10 text-center text-sm text-gray-400">{{ t('process.simulateEmpty') }}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<template #footer>
|
||||
<p class="mr-auto hidden text-[11px] leading-4 text-gray-400 sm:block">{{ t('process.simulateSafeHint') }}</p>
|
||||
<button type="button" class="btn btn-secondary" @click="emit('close')">{{ t('common.close') }}</button>
|
||||
<button type="button" class="btn btn-primary" :disabled="running" @click="run(true)">
|
||||
<Icon name="play" class="mr-1 h-4 w-4" :class="running ? 'animate-pulse' : ''" />
|
||||
{{ t(running ? 'process.simulateRunning' : 'process.simulateRun') }}
|
||||
</button>
|
||||
</template>
|
||||
</BaseDialog>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 流程试跑弹窗:左边「谁发起 + 填了什么」,右边「这一单会怎么走」。
|
||||
*
|
||||
* 预测全在后端 ``service/simulator.py`` 里按运行时口径算(找人、条件、免审、去重、兜底),
|
||||
* 这里只负责把结果念给人看:三档结论、一张预测轨迹图、逐环节记录、按严重度排好的问题清单。
|
||||
* 弹窗只在打开时算,改表单或换发起人后按防抖补算一次——试跑是设计期动作,不该每敲一个字
|
||||
* 就打后端一枪。
|
||||
*/
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import { useDebounceFn } from '@vueuse/core'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import BaseDialog from '@/components/common/BaseDialog.vue'
|
||||
import Icon from '@/components/icons/Icon.vue'
|
||||
import type { IconName } from '@/components/icons/Icon.vue'
|
||||
import FlowTrajectory from '@/components/oa/FlowTrajectory.vue'
|
||||
import FormRenderer from '@/components/oa/FormRenderer.vue'
|
||||
import PeoplePicker from '@/components/oa/PeoplePicker.vue'
|
||||
import { designAPI } from '@/api'
|
||||
import { autoPresetShape, isAutoPreset } from '@/utils/autoPreset'
|
||||
import { toSheet } from '@/utils/formLayout'
|
||||
import { dnParts } from '@/utils/personLabel'
|
||||
import type {
|
||||
Activity,
|
||||
FormSchema,
|
||||
ProcessApproval,
|
||||
ProcessSimulation,
|
||||
RouteDef,
|
||||
SimulationLevel,
|
||||
SimulationStepState,
|
||||
SimulationVerdict
|
||||
} from '@/types'
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
show: boolean
|
||||
processId: string
|
||||
processName?: string
|
||||
/** 流程默认表单;没有它就只能按画布结构预测 */
|
||||
schema?: FormSchema | null
|
||||
/** 画布上当前这份设计(含还没保存的改动) */
|
||||
activities: Activity[]
|
||||
routes: RouteDef[]
|
||||
approval: ProcessApproval
|
||||
/** 默认拿当前登录人试算 */
|
||||
defaultIdentity?: string
|
||||
}>(),
|
||||
{ processName: '', schema: null, defaultIdentity: '' }
|
||||
)
|
||||
|
||||
const emit = defineEmits<{ (event: 'close'): void; (event: 'focus', activity: string): void }>()
|
||||
|
||||
const { t } = useI18n()
|
||||
const starter = ref<string[]>([])
|
||||
const data = ref<Record<string, unknown>>({})
|
||||
const result = ref<ProcessSimulation | null>(null)
|
||||
const running = ref(false)
|
||||
const failed = ref(false)
|
||||
const view = ref<'flow' | 'steps' | 'issues'>('flow')
|
||||
/** 上一次预测用的是哪一份输入,用来判断结论过没过时。 */
|
||||
const sentKey = ref('')
|
||||
|
||||
const VERDICT_KEYS: Record<SimulationVerdict, string> = {
|
||||
ok: 'process.simulateOk',
|
||||
risk: 'process.simulateRisk',
|
||||
blocked: 'process.simulateBlocked'
|
||||
}
|
||||
const VERDICT_HINTS: Record<SimulationVerdict, string> = {
|
||||
ok: 'process.simulateOkHint',
|
||||
risk: 'process.simulateRiskHint',
|
||||
blocked: 'process.simulateBlockedHint'
|
||||
}
|
||||
const VERDICT_ICONS: Record<SimulationVerdict, IconName> = {
|
||||
ok: 'checkCircle',
|
||||
risk: 'exclamationTriangle',
|
||||
blocked: 'xCircle'
|
||||
}
|
||||
const VERDICT_BOX: Record<SimulationVerdict, string> = {
|
||||
ok: 'border-emerald-200 bg-emerald-50 dark:border-emerald-900/50 dark:bg-emerald-950/40',
|
||||
risk: 'border-amber-200 bg-amber-50 dark:border-amber-900/50 dark:bg-amber-950/30',
|
||||
blocked: 'border-red-200 bg-red-50 dark:border-red-900/50 dark:bg-red-950/40'
|
||||
}
|
||||
const VERDICT_TONES: Record<SimulationVerdict, string> = {
|
||||
ok: 'text-emerald-800 dark:text-emerald-300',
|
||||
risk: 'text-amber-800 dark:text-amber-300',
|
||||
blocked: 'text-red-800 dark:text-red-300'
|
||||
}
|
||||
|
||||
const STATE_KEYS: Record<SimulationStepState, string> = {
|
||||
passed: 'process.simulateStatePassed',
|
||||
skipped: 'process.simulateStateSkipped',
|
||||
waiting: 'process.simulateStateWaiting',
|
||||
blocked: 'process.simulateStateBlocked',
|
||||
stopped: 'process.simulateStateStopped'
|
||||
}
|
||||
const STATE_BADGES: Record<SimulationStepState, string> = {
|
||||
passed: 'badge-success',
|
||||
skipped: 'badge-gray',
|
||||
waiting: 'badge-primary',
|
||||
blocked: 'badge-danger',
|
||||
stopped: 'badge-danger'
|
||||
}
|
||||
const STATE_DOTS: Record<SimulationStepState, string> = {
|
||||
passed: 'bg-emerald-500',
|
||||
skipped: 'bg-gray-400',
|
||||
waiting: 'bg-primary-500',
|
||||
blocked: 'bg-red-500',
|
||||
stopped: 'bg-red-500'
|
||||
}
|
||||
|
||||
const LEVEL_ICONS: Record<SimulationLevel, IconName> = {
|
||||
error: 'xCircle',
|
||||
warn: 'exclamationTriangle',
|
||||
info: 'infoCircle'
|
||||
}
|
||||
const LEVEL_TONES: Record<SimulationLevel, string> = {
|
||||
error: 'text-red-600 dark:text-red-400',
|
||||
warn: 'text-amber-600 dark:text-amber-400',
|
||||
info: 'text-gray-400'
|
||||
}
|
||||
const LEVEL_BOX: Record<SimulationLevel, string> = {
|
||||
error: 'border-red-200 bg-red-50/70 text-red-800 dark:border-red-900/50 dark:bg-red-950/30 dark:text-red-200',
|
||||
warn: 'border-amber-200 bg-amber-50/70 text-amber-800 dark:border-amber-900/50 dark:bg-amber-950/20 dark:text-amber-200',
|
||||
info: 'border-gray-200 text-gray-600 dark:border-dark-600 dark:text-dark-300'
|
||||
}
|
||||
|
||||
const MODE_KEYS: Record<string, string> = {
|
||||
any: 'process.modeAny',
|
||||
all: 'process.modeAll',
|
||||
join: 'process.modeAll',
|
||||
serial: 'process.modeSerial',
|
||||
ratio: 'process.modeRatio'
|
||||
}
|
||||
|
||||
const errorCount = computed(() => (result.value?.findings ?? []).filter((item) => item.level === 'error').length)
|
||||
|
||||
const verdictHint = computed(() => {
|
||||
const summary = result.value?.summary
|
||||
if (!summary) return ''
|
||||
if (summary.form_errors) {
|
||||
return t('process.simulateFormHint', { count: summary.form_errors })
|
||||
}
|
||||
// 表单都填全了还挡着,那一定是画布自己的问题:话要说准,别让人去翻表单
|
||||
if (summary.design_errors) {
|
||||
return t('process.simulateDesignHint', { count: summary.design_errors })
|
||||
}
|
||||
return t(VERDICT_HINTS[result.value?.verdict ?? 'ok'])
|
||||
})
|
||||
|
||||
/** FlowTrajectory 吃的是画布那套 from/to,这里换一下字段名。 */
|
||||
const trajectoryRoutes = computed(() =>
|
||||
props.routes.map((route) => ({
|
||||
id: route.id,
|
||||
name: route.name,
|
||||
alias: route.alias,
|
||||
from: route.from_activity,
|
||||
to: route.to_activity,
|
||||
decision: route.decision
|
||||
}))
|
||||
)
|
||||
|
||||
const starterIdentity = computed(() => starter.value[0] ?? '')
|
||||
|
||||
/** 送去预测的、用来判断过没过时的,必须是同一份东西,否则「结论过时」会一直亮着。 */
|
||||
const payload = computed(() => ({
|
||||
starterIdentity: starterIdentity.value,
|
||||
data: data.value,
|
||||
activities: props.activities,
|
||||
routes: props.routes,
|
||||
approval: props.approval
|
||||
}))
|
||||
const inputsKey = computed(() => JSON.stringify(payload.value))
|
||||
const stale = computed(() => !!result.value && !running.value && inputsKey.value !== sentKey.value)
|
||||
|
||||
/** 这些系统带出的值是「发起人」带出来的,换人就得重新带。 */
|
||||
const STARTER_SOURCES = ['creator', 'creatorAccount', 'creatorUnit', 'creatorUnitPath']
|
||||
|
||||
/**
|
||||
* 换发起人:把上一位带出来的那几格清空,表单会按新的发起人重新带一遍。
|
||||
*
|
||||
* 只清「值正好就是上一位」的格子——手工填过的、别人的值一律不动。不清的话,
|
||||
* 申请人还留着上一位,而按表单找人的环节读的就是这一格,预测出来的人会跟着错。
|
||||
*/
|
||||
function dropStarterPresets(previousDn: string) {
|
||||
if (!previousDn) return
|
||||
const prev = dnParts(previousDn)
|
||||
const texts: Record<string, string> = {
|
||||
creator: prev.name,
|
||||
creatorAccount: prev.account,
|
||||
creatorUnit: prev.unitName,
|
||||
creatorUnitPath: prev.unitPath
|
||||
}
|
||||
const next: Record<string, unknown> = { ...data.value }
|
||||
let touched = false
|
||||
toSheet(props.schema).cells.forEach(({ field }) => {
|
||||
const source = String(field.auto ?? '')
|
||||
if (!isAutoPreset(field) || !STARTER_SOURCES.includes(source)) return
|
||||
const value = next[field.key]
|
||||
const shape = autoPresetShape(field)
|
||||
if (shape === 'person') {
|
||||
// 混了别人的一律不动,只处理「这一格就是发起人自己」
|
||||
if (!(Array.isArray(value) && value.length === 1 && value[0] === previousDn)) return
|
||||
} else if (shape === 'unit') {
|
||||
if (value !== prev.unitPath && value !== prev.unitName) return
|
||||
} else if (value !== texts[source]) {
|
||||
return
|
||||
}
|
||||
delete next[field.key]
|
||||
touched = true
|
||||
})
|
||||
if (touched) data.value = next
|
||||
}
|
||||
|
||||
function onStarter(value: string[]) {
|
||||
const previous = starterIdentity.value
|
||||
const next = value.slice(-1)
|
||||
if (previous === (next[0] ?? '')) {
|
||||
starter.value = next
|
||||
return
|
||||
}
|
||||
starter.value = next
|
||||
dropStarterPresets(previous)
|
||||
}
|
||||
|
||||
function modeLabel(mode: string): string {
|
||||
const key = MODE_KEYS[mode]
|
||||
return key ? t(key) : mode
|
||||
}
|
||||
|
||||
async function run(force = false) {
|
||||
if (!props.processId) return
|
||||
const key = JSON.stringify(payload.value)
|
||||
// 输入一个字都没变(比如刚带出完又触发了一次)就别再打后端一枪
|
||||
if (!force && result.value && key === sentKey.value) return
|
||||
running.value = true
|
||||
try {
|
||||
const simulated = await designAPI.simulateProcess(props.processId, payload.value)
|
||||
result.value = simulated
|
||||
sentKey.value = key
|
||||
failed.value = false
|
||||
if (errorCount.value) view.value = 'issues'
|
||||
} catch {
|
||||
failed.value = true
|
||||
} finally {
|
||||
running.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/** 表单与画布的改动:等手停下来一会儿再算,不必每敲一个字打后端一枪。 */
|
||||
const schedule = useDebounceFn(() => {
|
||||
if (props.show) void run()
|
||||
}, 900)
|
||||
|
||||
/** 换发起人 / 刚打开:先让表单把「发起人」那几格重新带一遍,再拿齐整的数据去算。 */
|
||||
const scheduleSoon = useDebounceFn(() => {
|
||||
if (props.show) void run()
|
||||
}, 300)
|
||||
|
||||
watch(inputsKey, () => {
|
||||
if (props.show) schedule()
|
||||
})
|
||||
|
||||
// 打开弹窗:拿当前登录人先跑一遍,让人一进来就看见一条走法,而不是一个空框
|
||||
watch(
|
||||
() => props.show,
|
||||
(open) => {
|
||||
if (!open) return
|
||||
if (!starter.value.length && props.defaultIdentity) starter.value = [props.defaultIdentity]
|
||||
view.value = 'flow'
|
||||
running.value = true
|
||||
scheduleSoon()
|
||||
}
|
||||
)
|
||||
|
||||
// 换发起人这一趟就整个变了:只等表单重新带出那一小会儿,不跟着打字那档防抖
|
||||
watch(starterIdentity, () => {
|
||||
if (!props.show) return
|
||||
running.value = true
|
||||
scheduleSoon()
|
||||
})
|
||||
|
||||
/** 给上层留个口子:切到别的流程时把上一份结论丢掉。 */
|
||||
function reset() {
|
||||
result.value = null
|
||||
sentKey.value = ''
|
||||
failed.value = false
|
||||
}
|
||||
|
||||
defineExpose({ reset })
|
||||
</script>
|
||||
|
|
@ -0,0 +1,343 @@
|
|||
<template>
|
||||
<div class="space-y-3">
|
||||
<p class="input-hint">{{ t('ds.processChannelHint') }}</p>
|
||||
|
||||
<div>
|
||||
<ProcessPicker
|
||||
:model-value="srcProcess"
|
||||
:label="t('ds.processPick')"
|
||||
:placeholder="t('ds.processPickPlaceholder')"
|
||||
:loading="loadingProcesses"
|
||||
@update:model-value="setProcess(String($event))"
|
||||
/>
|
||||
<p class="input-hint">{{ t('ds.processPickHint') }}</p>
|
||||
<p v-if="srcProcess && processRow && !processRow.published" class="input-hint text-amber-600 dark:text-amber-400">
|
||||
{{ t('ds.processNotPublished') }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div v-if="srcProcess" class="grid grid-cols-3 gap-3">
|
||||
<div>
|
||||
<span class="input-label">{{ t('ds.processStatus') }}</span>
|
||||
<Select :model-value="match.status ?? 'completed'" :options="statusOptions" @update:model-value="setStatus($event)" />
|
||||
<p class="input-hint">{{ t('ds.processStatusHint') }}</p>
|
||||
</div>
|
||||
<div>
|
||||
<span class="input-label">{{ t('ds.processOrder') }}</span>
|
||||
<Select :model-value="match.order ?? 'latest'" :options="orderOptions" @update:model-value="setOrder($event)" />
|
||||
<p class="input-hint">{{ t('ds.processOrderHint') }}</p>
|
||||
</div>
|
||||
<div>
|
||||
<span class="input-label">{{ t('ds.processScope') }}</span>
|
||||
<Select :model-value="match.scope ?? 'own'" :options="scopeOptions" @update:model-value="setScope($event)" />
|
||||
<p class="input-hint">{{ scopeHint }}</p>
|
||||
</div>
|
||||
<Input
|
||||
type="number"
|
||||
compact
|
||||
:model-value="String(match.days ?? 0)"
|
||||
:label="t('ds.processDays')"
|
||||
@update:model-value="patch({ days: Number($event) || 0 })"
|
||||
/>
|
||||
<Input
|
||||
v-if="kind === 'search'"
|
||||
type="number"
|
||||
compact
|
||||
:model-value="String(match.limit ?? 20)"
|
||||
:label="t('ds.processLimit')"
|
||||
@update:model-value="patch({ limit: Number($event) || 20 })"
|
||||
/>
|
||||
<Input
|
||||
v-else
|
||||
compact
|
||||
:model-value="String(match.person ?? '')"
|
||||
:label="t('ds.processPerson')"
|
||||
:placeholder="t('ds.processPersonPlaceholder')"
|
||||
@update:model-value="patch({ person: String($event) })"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div v-if="srcProcess && isCross" class="rounded-xl border border-amber-200 p-2.5 text-xs dark:border-amber-500/40">
|
||||
<p class="font-medium text-amber-700 dark:text-amber-400">{{ t('ds.processCrossTitle') }}</p>
|
||||
<p class="mt-1 text-amber-700/90 dark:text-amber-400/90">{{ t('ds.processCrossHint') }}</p>
|
||||
<p v-if="!minPermission" class="mt-1 font-medium text-amber-700 dark:text-amber-400">{{ t('ds.processCrossNeedPerm') }}</p>
|
||||
</div>
|
||||
|
||||
<!-- 匹配条件:值用的还是外部取数那一份写法,这里不另教一套语法 -->
|
||||
<div v-if="srcProcess" class="border-t border-gray-100 pt-2 dark:border-dark-700">
|
||||
<p class="input-label">{{ t('ds.processFilters') }}</p>
|
||||
<p class="input-hint">{{ t('ds.processFiltersHint') }}</p>
|
||||
<div
|
||||
v-for="(item, index) in filters"
|
||||
:key="index"
|
||||
class="mb-1.5 grid grid-cols-[minmax(0,1.1fr)_minmax(0,.8fr)_minmax(0,1.1fr)_2rem] items-end gap-1.5"
|
||||
>
|
||||
<Select
|
||||
:model-value="item.field"
|
||||
:options="fieldOptions"
|
||||
:placeholder="t('ds.processFieldCol')"
|
||||
compact
|
||||
searchable
|
||||
@update:model-value="setFilter(index, { field: String($event) })"
|
||||
/>
|
||||
<Select
|
||||
:model-value="item.op || 'eq'"
|
||||
:options="opOptions"
|
||||
compact
|
||||
@update:model-value="setFilter(index, { op: String($event) })"
|
||||
/>
|
||||
<Input
|
||||
v-if="needsValue(item.op)"
|
||||
compact
|
||||
:model-value="String(item.value ?? '')"
|
||||
:placeholder="t('ds.processValuePlaceholder')"
|
||||
@update:model-value="setFilter(index, { value: String($event) })"
|
||||
/>
|
||||
<span v-else class="pb-2 text-xs text-gray-400">{{ t('ds.processValueNone') }}</span>
|
||||
<button
|
||||
type="button"
|
||||
class="btn btn-ghost btn-icon mb-0.5 h-8 w-8 shrink-0 text-gray-400 hover:text-red-600"
|
||||
:title="t('ds.processFilterRemove')"
|
||||
:aria-label="t('ds.processFilterRemove')"
|
||||
@click="removeFilter(index)"
|
||||
>
|
||||
<Icon name="x" class="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
<p v-if="!filters.length" class="input-hint">{{ t('ds.processFiltersEmpty') }}</p>
|
||||
<button type="button" class="btn btn-secondary btn-sm w-full" :disabled="filters.length >= MAX_FILTERS" @click="addFilter">
|
||||
<Icon name="plus" class="mr-1 h-3.5 w-3.5" />{{ t('ds.processFiltersAdd') }}
|
||||
</button>
|
||||
<p v-if="droppedFields.length" class="mt-1 input-hint text-amber-600 dark:text-amber-400">
|
||||
{{ t('ds.processMissingFields', { fields: droppedFields.join('、') }) }}
|
||||
</p>
|
||||
<p v-if="filters.length" class="input-hint">{{ t('ds.processScanNote') }}</p>
|
||||
</div>
|
||||
|
||||
<!-- 带出哪些字段:勾一下就把 pick / mapExtra 那两条路径写好,解析那一栏不再让人手打 -->
|
||||
<div v-if="srcProcess" class="border-t border-gray-100 pt-2 dark:border-dark-700">
|
||||
<div class="flex items-center justify-between">
|
||||
<p class="input-label mb-0">{{ t('ds.processFields') }}</p>
|
||||
<span v-if="ticked.length" class="badge badge-primary">{{ t('ds.processFieldsOn', { count: ticked.length }) }}</span>
|
||||
</div>
|
||||
<p class="input-hint">{{ kind === 'search' ? t('ds.processFieldsHintSearch') : t('ds.processFieldsHintFetch') }}</p>
|
||||
<p v-if="loadingFields" class="input-hint">{{ t('ds.processFieldsLoading') }}</p>
|
||||
<p v-else-if="!fields.length" class="input-hint text-amber-600 dark:text-amber-400">{{ t('ds.processFieldsEmpty') }}</p>
|
||||
<div v-else class="max-h-[300px] space-y-1 overflow-y-auto rounded-lg border border-gray-200 p-2 dark:border-dark-600">
|
||||
<div v-for="item in fields" :key="item.key" class="flex items-center gap-2 text-xs">
|
||||
<input
|
||||
type="checkbox"
|
||||
class="rounded border-gray-300"
|
||||
:checked="ticked.includes(item.key)"
|
||||
:aria-label="item.label"
|
||||
@change="toggleField(item.key, ($event.target as HTMLInputElement).checked)"
|
||||
/>
|
||||
<span class="min-w-0 flex-1 truncate">
|
||||
{{ item.label }}
|
||||
<span class="font-mono text-[11px] text-gray-400">{{ item.key }}</span>
|
||||
</span>
|
||||
<span v-if="item.formName && !item.default" class="flex-shrink-0 text-[11px] text-gray-400">{{ item.formName }}</span>
|
||||
<button
|
||||
v-if="kind === 'fetch' && ticked.includes(item.key)"
|
||||
type="button"
|
||||
class="btn btn-ghost btn-sm flex-shrink-0"
|
||||
:class="{ 'btn-primary': mainKey === item.key }"
|
||||
:title="t('ds.processMainHint')"
|
||||
@click="setMain(item.key)"
|
||||
>
|
||||
{{ mainKey === item.key ? t('ds.processMainOn') : t('ds.processMain') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<p v-if="kind === 'fetch' && ticked.length && !mainKey" class="mt-1 input-hint text-amber-600 dark:text-amber-400">
|
||||
{{ t('ds.processMainMissing') }}
|
||||
</p>
|
||||
<p v-if="kind === 'fetch'" class="input-hint">{{ t('ds.processParseLocked') }}</p>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 数据源的「流程数据」通道:从本平台另一个流程的单据里带数据。
|
||||
*
|
||||
* 这个面板只写四样东西:``srcProcess``、``srcMatch``、``pick``、``mapExtra``。
|
||||
* 后两样由「勾选要带出哪些字段」翻译出来(翻译只在 utils/processSource 那一处),
|
||||
* 所以「解析」那一栏对这条通道不再摆输入框——同一份配置两个地方能改,早晚对不上。
|
||||
*/
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import Icon from '@/components/icons/Icon.vue'
|
||||
import ProcessPicker from '@/components/oa/design/ProcessPicker.vue'
|
||||
import Input from '@/components/common/Input.vue'
|
||||
import Select from '@/components/common/Select.vue'
|
||||
import { processFields as fetchProcessFields } from '@/api/dataSources'
|
||||
import { processCatalog } from '@/utils/processCatalog'
|
||||
import {
|
||||
MAX_FILTERS,
|
||||
PROCESS_OPS,
|
||||
mainFieldOfPick,
|
||||
missingFilterFields,
|
||||
tickedFields,
|
||||
usableFilters,
|
||||
writePicked
|
||||
} from '@/utils/processSource'
|
||||
import type { ProcessDataFilter, ProcessDataMatch, ProcessDef, ProcessFieldOption } from '@/types'
|
||||
|
||||
const props = defineProps<{
|
||||
srcProcess: string
|
||||
match: ProcessDataMatch
|
||||
kind: 'fetch' | 'search'
|
||||
pick: string
|
||||
mapExtra: Record<string, string>
|
||||
/** 跨人带数据必须有调用权限挡着,这里只负责把这句话讲到,配置本体在「可靠性与兜底」那一栏 */
|
||||
minPermission: string
|
||||
}>()
|
||||
const emit = defineEmits<{ (e: 'patch', values: Record<string, unknown>): void }>()
|
||||
const { t } = useI18n()
|
||||
|
||||
const processes = ref<ProcessDef[]>([])
|
||||
const loadingProcesses = ref(false)
|
||||
const fields = ref<ProcessFieldOption[]>([])
|
||||
const loadingFields = ref(false)
|
||||
/** 面板自己摊开的条件行:与后端认的那份之间只隔一次 usableFilters。 */
|
||||
const filters = ref<ProcessDataFilter[]>([])
|
||||
const ticked = ref<string[]>([])
|
||||
const mainKey = ref('')
|
||||
|
||||
const processRow = computed(() => processes.value.find((item) => item.id === props.srcProcess) ?? null)
|
||||
const isCross = computed(() => (props.match.scope ?? 'own') === 'all')
|
||||
|
||||
const statusOptions = computed(() =>
|
||||
(['completed', 'running', 'any'] as const).map((item) => ({ value: item, label: t(`ds.processStatus_${item}`) }))
|
||||
)
|
||||
const orderOptions = computed(() =>
|
||||
(['latest', 'earliest'] as const).map((item) => ({ value: item, label: t(`ds.processOrder_${item}`) }))
|
||||
)
|
||||
const scopeOptions = computed(() =>
|
||||
(['own', 'all'] as const).map((item) => ({ value: item, label: t(`ds.processScope_${item}`) }))
|
||||
)
|
||||
const opOptions = computed(() => PROCESS_OPS.map((item) => ({ value: item, label: t(`ds.processOp_${item}`) })))
|
||||
const fieldOptions = computed(() => fields.value.map((item) => ({ value: item.key, label: `${item.label} · ${item.key}` })))
|
||||
const scopeHint = computed(() => t(isCross.value ? 'ds.processScopeHintAll' : 'ds.processScopeHintOwn'))
|
||||
const droppedFields = computed(() => missingFilterFields({ ...props.match, filters: filters.value }, fields.value))
|
||||
|
||||
function needsValue(op: string): boolean {
|
||||
return !['empty', 'notEmpty'].includes(String(op || 'eq'))
|
||||
}
|
||||
|
||||
/** 把当前勾选与条件写回父级;条件里没填完整的行不进请求,免得存一堆半拉子。 */
|
||||
function commit(next: Partial<ProcessDataMatch> = {}, picked: { keys: string[]; main: string } | null = null) {
|
||||
const merged: ProcessDataMatch = { ...props.match, ...next }
|
||||
const values: Record<string, unknown> = { srcMatch: merged }
|
||||
const list = picked ?? { keys: ticked.value, main: mainKey.value }
|
||||
if (picked) {
|
||||
ticked.value = picked.keys
|
||||
mainKey.value = picked.main
|
||||
}
|
||||
Object.assign(values, props.kind === 'search'
|
||||
? { mapExtra: writePicked(list.keys, '').mapExtra }
|
||||
: writePicked(list.keys, list.main))
|
||||
emit('patch', values)
|
||||
}
|
||||
|
||||
function patch(next: Partial<ProcessDataMatch>) {
|
||||
commit(next)
|
||||
}
|
||||
|
||||
// 三档下拉的候选都是常量表,值域由这里替 Select 收一次,不在模板里写 cast
|
||||
function setStatus(value: unknown) {
|
||||
commit({ status: value as ProcessDataMatch['status'] })
|
||||
}
|
||||
|
||||
function setOrder(value: unknown) {
|
||||
commit({ order: value as ProcessDataMatch['order'] })
|
||||
}
|
||||
|
||||
function setScope(value: unknown) {
|
||||
commit({ scope: value as ProcessDataMatch['scope'] })
|
||||
}
|
||||
|
||||
function setProcess(id: string) {
|
||||
// 换流程等于换一套表单:上一套勾出来的字段路径已经指不到东西了,一次清干净
|
||||
ticked.value = []
|
||||
mainKey.value = ''
|
||||
filters.value = []
|
||||
emit('patch', {
|
||||
srcProcess: id,
|
||||
srcMatch: { ...props.match, filters: [] },
|
||||
pick: '',
|
||||
mapExtra: {}
|
||||
})
|
||||
}
|
||||
|
||||
function addFilter() {
|
||||
filters.value = [...filters.value, { field: '', op: 'eq', value: '' }]
|
||||
}
|
||||
|
||||
function removeFilter(index: number) {
|
||||
filters.value = filters.value.filter((_, at) => at !== index)
|
||||
commit({ filters: usableFilters(filters.value) })
|
||||
}
|
||||
|
||||
function setFilter(index: number, next: Partial<ProcessDataFilter>) {
|
||||
filters.value = filters.value.map((item, at) => (at === index ? { ...item, ...next } : item))
|
||||
commit({ filters: usableFilters(filters.value) })
|
||||
}
|
||||
|
||||
function toggleField(key: string, on: boolean) {
|
||||
const keys = on ? [...ticked.value, key] : ticked.value.filter((item) => item !== key)
|
||||
const main = keys.includes(mainKey.value) ? mainKey.value : keys[0] ?? ''
|
||||
commit({}, { keys, main })
|
||||
}
|
||||
|
||||
function setMain(key: string) {
|
||||
commit({}, { keys: ticked.value, main: key })
|
||||
}
|
||||
|
||||
async function loadFields() {
|
||||
if (!props.srcProcess) {
|
||||
fields.value = []
|
||||
return
|
||||
}
|
||||
loadingFields.value = true
|
||||
try {
|
||||
fields.value = (await fetchProcessFields(props.srcProcess)).fields
|
||||
} catch {
|
||||
fields.value = []
|
||||
} finally {
|
||||
loadingFields.value = false
|
||||
}
|
||||
}
|
||||
|
||||
watch(() => props.srcProcess, loadFields)
|
||||
watch(
|
||||
() => [props.srcProcess, props.pick, JSON.stringify(props.mapExtra ?? {})],
|
||||
() => {
|
||||
ticked.value = tickedFields(
|
||||
{ code: '', name: '', kind: props.kind, url: '', provider: 'process', pick: props.pick, mapExtra: props.mapExtra },
|
||||
fields.value
|
||||
)
|
||||
mainKey.value = mainFieldOfPick(props.pick)
|
||||
},
|
||||
{ immediate: true }
|
||||
)
|
||||
|
||||
onMounted(async () => {
|
||||
loadingProcesses.value = true
|
||||
// 清单本身交给选择器去拉,这边只要拿它判一下选中的流程发没发布
|
||||
processes.value = (await processCatalog()).processes
|
||||
loadingProcesses.value = false
|
||||
loadFields()
|
||||
})
|
||||
|
||||
/** 条件行跟着存下来的配置走:新建时后端那份是空的,编辑时按存过的摊开。 */
|
||||
watch(
|
||||
() => props.match.filters,
|
||||
(raw) => {
|
||||
const stored = usableFilters(Array.isArray(raw) ? raw : [])
|
||||
if (JSON.stringify(stored) !== JSON.stringify(filters.value)) filters.value = stored
|
||||
},
|
||||
{ immediate: true }
|
||||
)
|
||||
</script>
|
||||
|
|
@ -0,0 +1,86 @@
|
|||
/**
|
||||
* 设计期「重复审批人」体检的状态机。
|
||||
*
|
||||
* 放在 composable 而不是面板里,是因为体检结论有三处要用:右栏那块面板、工具栏上的
|
||||
* 角标、发布前那一句「还有三个人会签两次」。面板切走时结论得留着,否则角标会跟着消失,
|
||||
* 人刚修完就看不出好没好。
|
||||
*
|
||||
* 只有一件事是这里定的:**什么时候自己再算一遍**。画布每动一下就打后端一枪太吵,
|
||||
* 所以只在面板开着的时候按防抖补算;结论对不上当下这份设计时标成「待重算」,
|
||||
* 让人自己决定要不要点那一下。
|
||||
*/
|
||||
import { computed, ref, watch, type Ref } from 'vue'
|
||||
import { useDebounceFn } from '@vueuse/core'
|
||||
import { designAPI } from '@/api'
|
||||
import type { Activity, DedupAuditResult, ProcessApproval, RouteDef } from '@/types'
|
||||
|
||||
export interface DedupAuditDraft {
|
||||
activities: Activity[]
|
||||
routes: RouteDef[]
|
||||
approval: ProcessApproval
|
||||
}
|
||||
|
||||
export interface UseDedupAuditOptions {
|
||||
processId: Ref<string>
|
||||
/** 取画布上当前这份设计(含还没保存的改动) */
|
||||
draft: () => DedupAuditDraft
|
||||
/** 面板开着时,画布改动后隔多久自己补算一次 */
|
||||
delay?: number
|
||||
}
|
||||
|
||||
export function useDedupAudit(options: UseDedupAuditOptions) {
|
||||
const result = ref<DedupAuditResult | null>(null)
|
||||
const running = ref(false)
|
||||
const failed = ref(false)
|
||||
const ranAt = ref<Date | null>(null)
|
||||
/** 体检面板开着才自动补算:不开面板就没必要为每次拖拽打一次后端。 */
|
||||
const watching = ref(false)
|
||||
|
||||
let seq = 0
|
||||
const sentKey = ref('')
|
||||
|
||||
/** 这一份设计算不算得出同一个结论:拿它当「改过了」的凭据。 */
|
||||
const draftKey = computed(() => JSON.stringify(options.draft()))
|
||||
|
||||
/** 结论是不是还对着当下这份画布(改过就没重算)。 */
|
||||
const stale = computed(() => result.value !== null && draftKey.value !== sentKey.value)
|
||||
|
||||
async function run() {
|
||||
const id = options.processId.value
|
||||
if (!id) return
|
||||
const request = ++seq
|
||||
const payload = options.draft()
|
||||
running.value = true
|
||||
try {
|
||||
const data = await designAPI.auditDuplicateApprovers(id, payload)
|
||||
if (request !== seq) return
|
||||
result.value = data
|
||||
sentKey.value = JSON.stringify(payload)
|
||||
failed.value = false
|
||||
ranAt.value = new Date()
|
||||
} catch {
|
||||
if (request !== seq) return
|
||||
failed.value = true
|
||||
} finally {
|
||||
if (request === seq) running.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const schedule = useDebounceFn(() => {
|
||||
if (watching.value) void run()
|
||||
}, options.delay ?? 800)
|
||||
|
||||
watch(draftKey, () => schedule())
|
||||
|
||||
/** 打开面板 / 点「重新体检」:从这一拍起跟着画布自己补算。 */
|
||||
function refresh() {
|
||||
watching.value = true
|
||||
if (!running.value) void run()
|
||||
}
|
||||
|
||||
function stop() {
|
||||
watching.value = false
|
||||
}
|
||||
|
||||
return { result, running, failed, ranAt, stale, watching, run, refresh, stop }
|
||||
}
|
||||
|
|
@ -0,0 +1,131 @@
|
|||
/**
|
||||
* 「同一张单上同一个人重复出现」的统一口径。
|
||||
*
|
||||
* 引擎里存的一直是两个方向相反的开关(``skipApproved`` 往回看:这个人前面已经签过;
|
||||
* ``skipAhead`` 往前看:他后面还要再签)。两个开关各开各的,界面就成了两个几乎同名
|
||||
* 的下拉,看不出组合是什么意思——所以界面上收成**一档策略**:这单他签几次、签在哪一次。
|
||||
*
|
||||
* 四档都是真实存在的组合,存储不动(还是那两个老键 + ``dedup`` / ``dedupAhead``):
|
||||
* - ``each`` 每次都签
|
||||
* - ``first`` 只签第一次:后面再遇到自动过(老 ``dedup=all``)
|
||||
* - ``last`` 只签最后一次:前面再遇到自动过(老 ``dedupAhead=all/any``)
|
||||
* - ``once`` 只签一次:能提前跳的都跳掉,一旦真签了后面也不再打扰他
|
||||
*
|
||||
* 两条规则不会互相抵消:往回看那档以「已办」为凭,而前瞻跳过不产生已办,
|
||||
* 所以同一个人这一单一定至少真签一次。口径与后端 ``engine.repeat_policy`` 一致。
|
||||
*/
|
||||
import type { ActivityConfig, ProcessApproval } from '@/types'
|
||||
|
||||
export type DedupPolicy = 'each' | 'first' | 'last' | 'once'
|
||||
|
||||
/** 环节级多一档「跟随流程设置」(存储上就是把两个键都删掉)。 */
|
||||
export type NodeDedupPolicy = '' | DedupPolicy
|
||||
|
||||
/** 「后面还要他批」的判定口径:每条后续路径都必经(保守)/ 有一条可能就算(激进)。 */
|
||||
export type AheadScope = 'all' | 'any'
|
||||
|
||||
type StoredFlags = Pick<ProcessApproval, 'dedup' | 'dedupAhead'>
|
||||
|
||||
/** 环节上那两个键;没写过就是 ``undefined``=这个方向跟随流程设置。 */
|
||||
type NodeFlags = Pick<ActivityConfig, 'skipApproved' | 'skipAhead'>
|
||||
|
||||
/** 存储的两个开关折算成一档策略(两个都开=只签一次)。 */
|
||||
export function dedupPolicyOf(cfg: StoredFlags | null | undefined): DedupPolicy {
|
||||
const ahead = String(cfg?.dedupAhead ?? 'none') !== 'none'
|
||||
const approved = String(cfg?.dedup ?? 'none') === 'all'
|
||||
if (ahead && approved) return 'once'
|
||||
if (ahead) return 'last'
|
||||
if (approved) return 'first'
|
||||
return 'each'
|
||||
}
|
||||
|
||||
/** 用不用得上前瞻:只有「只签最后一次 / 只签一次」需要往后看。 */
|
||||
export function usesLookahead(policy: DedupPolicy): boolean {
|
||||
return policy === 'last' || policy === 'once'
|
||||
}
|
||||
|
||||
export function aheadScopeOf(cfg: StoredFlags | null | undefined): AheadScope {
|
||||
return String(cfg?.dedupAhead ?? '') === 'any' ? 'any' : 'all'
|
||||
}
|
||||
|
||||
/** 一档策略写回存储:不往后看时把 ``dedupAhead`` 收回去,免得留一份没用的激进口径。 */
|
||||
export function dedupPolicyWrite(policy: DedupPolicy, scope: AheadScope): Required<StoredFlags> {
|
||||
return {
|
||||
dedup: policy === 'first' || policy === 'once' ? 'all' : 'none',
|
||||
dedupAhead: usesLookahead(policy) ? scope : 'none'
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 这一环真正生效的两个开关:环节写过的算,没写的退回流程默认。
|
||||
* 口径与后端 ``engine.approval_flags`` 一致——继承是**按方向一个个**来的,不是整档继承,
|
||||
* 所以环节上只配了一个方向时,另一个方向仍跟着流程设置走。
|
||||
*/
|
||||
export function effectiveDedupFlags(
|
||||
node: NodeFlags | null | undefined,
|
||||
cfg: StoredFlags | null | undefined
|
||||
): { skipApproved: boolean; skipAhead: boolean } {
|
||||
return {
|
||||
skipApproved: node?.skipApproved ?? String(cfg?.dedup ?? 'none') === 'all',
|
||||
skipAhead: node?.skipAhead ?? String(cfg?.dedupAhead ?? 'none') !== 'none'
|
||||
}
|
||||
}
|
||||
|
||||
/** 这一环真正生效的那档策略(先把没写的方向按流程默认补齐,再折算成策略)。 */
|
||||
export function effectiveDedupPolicy(
|
||||
node: NodeFlags | null | undefined,
|
||||
cfg: StoredFlags | null | undefined
|
||||
): DedupPolicy {
|
||||
const flags = effectiveDedupFlags(node, cfg)
|
||||
if (flags.skipAhead) return flags.skipApproved ? 'once' : 'last'
|
||||
return flags.skipApproved ? 'first' : 'each'
|
||||
}
|
||||
|
||||
/** 这一环有没有钉住过任何一个方向:一个都没钉=跟随流程设置。 */
|
||||
export function dedupPinned(node: NodeFlags | null | undefined): boolean {
|
||||
return node?.skipApproved != null || node?.skipAhead != null
|
||||
}
|
||||
|
||||
/** 只显式配了一个方向(老界面上的两个开关各拨各的留下的):另一个方向在跟流程默认走。 */
|
||||
export function dedupHalfPinned(node: NodeFlags | null | undefined): boolean {
|
||||
return (node?.skipApproved == null) !== (node?.skipAhead == null)
|
||||
}
|
||||
|
||||
/** 环节上那份配置折算成一档策略;两个键都没写过就是「跟随流程设置」。
|
||||
* 这里只看环节自己写了什么,不含流程默认——要看真正生效的那档用 ``effectiveDedupPolicy``。 */
|
||||
export function nodeDedupPolicyOf(
|
||||
cfg: NodeFlags | null | undefined
|
||||
): NodeDedupPolicy {
|
||||
if (cfg?.skipApproved == null && cfg?.skipAhead == null) return ''
|
||||
return dedupPolicyOf({
|
||||
dedup: cfg?.skipApproved ? 'all' : 'none',
|
||||
dedupAhead: cfg?.skipAhead ? 'all' : 'none'
|
||||
})
|
||||
}
|
||||
|
||||
/** 环节选一档策略就是一次写清两个键(undefined 表示删键=跟随流程设置)。 */
|
||||
export function nodeDedupPolicyWrite(policy: NodeDedupPolicy): Record<string, boolean | undefined> {
|
||||
if (!policy) return { skipApproved: undefined, skipAhead: undefined }
|
||||
return {
|
||||
skipApproved: policy === 'first' || policy === 'once',
|
||||
skipAhead: policy === 'last' || policy === 'once'
|
||||
}
|
||||
}
|
||||
|
||||
/** 策略四档 + 跟随那一档的文案键。 */
|
||||
export const DEDUP_POLICY_KEYS: Record<DedupPolicy, string> = {
|
||||
each: 'dedupPolicyEach',
|
||||
first: 'dedupPolicyFirst',
|
||||
last: 'dedupPolicyLast',
|
||||
once: 'dedupPolicyOnce'
|
||||
}
|
||||
|
||||
/** 短一档的说法:环节右栏那一窄列放不下长句,长句留给提示文案。 */
|
||||
export const DEDUP_POLICY_SHORT_KEYS: Record<DedupPolicy, string> = {
|
||||
each: 'dedupPolicyShortEach',
|
||||
first: 'dedupPolicyShortFirst',
|
||||
last: 'dedupPolicyShortLast',
|
||||
once: 'dedupPolicyShortOnce'
|
||||
}
|
||||
|
||||
export const DEDUP_POLICIES: DedupPolicy[] = ['each', 'first', 'last', 'once']
|
||||
|
|
@ -0,0 +1,118 @@
|
|||
/**
|
||||
* 「重复审批人」体检结果的算法侧收口:结论怎么折成一句建议、画布上该挂哪几个角标。
|
||||
*
|
||||
* 判定本身在后端 ``service/dedupaudit.py``(与运行时同一套口径),这里只做两件事:
|
||||
* 一是把「还有的人会签两次」折算成一个能一键按下去的修法,二是把环节角色摊到画布上。
|
||||
* 两边都不重算规则,所以不会出现「界面上说会跳、运行时照样派待办」。
|
||||
*/
|
||||
import type { DedupAuditGroup, DedupAuditPair, DedupPairCause, DedupAuditResult, DedupRole } from '@/types'
|
||||
import type { DedupPolicy } from './approvalDedup'
|
||||
|
||||
/** 体检之后能一键落地的修法:改流程默认那一档,或让挡路的环节回到跟随流程。 */
|
||||
export type DedupFix = { kind: 'flow'; policy: DedupPolicy } | { kind: 'follow'; nodeIds: string[] }
|
||||
|
||||
export interface DedupFindings {
|
||||
/** 还会在同一张单上签两次的人头数(按组算,一组就是一个人) */
|
||||
open: number
|
||||
/** 静态判不准、需要人看一眼的组数 */
|
||||
watch: number
|
||||
/** 会在这张单上出现两次以上的人数 */
|
||||
people: number
|
||||
}
|
||||
|
||||
export interface DedupNodeMarks {
|
||||
skip: string[]
|
||||
double: string[]
|
||||
watch: string[]
|
||||
}
|
||||
|
||||
/** 生效那档里带「往回看」的两档:这一档的环节本来就会跳,不是挡路的那一环。 */
|
||||
const LOOKS_BACK = ['first', 'once']
|
||||
|
||||
/**
|
||||
* 「开一档往回看就管得住」的那几种原因:压根没配、往前看不敢断定、前面那环躲不掉。
|
||||
* 另外两种(并行同展、必批规则)不是策略没配的问题,别拿一键修法去糊。
|
||||
*/
|
||||
const BACKSTOPPABLE: DedupPairCause[] = ['policy_off', 'ahead_unproven', 'first_node']
|
||||
|
||||
/** 结论汇总:工具栏那个红色角标、发布前那句提醒都问这里。 */
|
||||
export function dedupFindings(result: DedupAuditResult | null | undefined): DedupFindings {
|
||||
const stats = result?.stats
|
||||
return {
|
||||
open: stats?.open ?? 0,
|
||||
watch: stats?.watch ?? 0,
|
||||
people: stats?.groups ?? 0
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 给「还会签两次」的那几组挑一个最小改动的修法。
|
||||
*
|
||||
* 挑修法看的不是红色角标那一档,而是「开一档往回看就管得住」的那些对:判成「要人确认」
|
||||
* 的组里同样有这种对——往后看开着、但后面有条分支不经过他,于是这一对没被管住,只是
|
||||
* 名单要等运行时才定得下来而已。这些人不该只能干看着橙灯。
|
||||
*
|
||||
* 顺序是按「先动流程、再动环节」:流程默认还是「每次都签」时,改成「只签第一次」
|
||||
* 一刀就能把往回看那条路全管住(比直接上「只签一次」保守——后者还会往后看,
|
||||
* 把前面该签的那环也跳掉,不该由体检替人做主)。已经开了往回看还漏,说明是某几环
|
||||
* 在环节上自己钉死了「不许跳」,那就只把挡路的环节退回跟随流程设置。
|
||||
*/
|
||||
export function dedupRecommendation(result: DedupAuditResult | null | undefined): DedupFix | null {
|
||||
const groups = backstopGroups(result)
|
||||
if (!groups.length) return null
|
||||
// 后端按这份画布算出来的流程默认那档,比界面上没保存的草稿更可信
|
||||
const policy = String(result?.policy ?? 'each')
|
||||
if (policy === 'each') return { kind: 'flow', policy: 'first' }
|
||||
if (policy === 'last') return { kind: 'flow', policy: 'once' }
|
||||
// 开了往回看还漏,一定是后面那一环自己把「前面批过也照签」钉死了:只退回这几环
|
||||
const nodes = new Map(groups.flatMap((group) => group.nodes).map((node) => [node.id, node]))
|
||||
const blocking = [
|
||||
...new Set(
|
||||
doubles(groups)
|
||||
.map((pair) => pair.to)
|
||||
.filter((id) => {
|
||||
const node = nodes.get(id)
|
||||
return !!node && !node.inherited && !LOOKS_BACK.includes(node.policy)
|
||||
})
|
||||
)
|
||||
]
|
||||
return blocking.length ? { kind: 'follow', nodeIds: blocking } : null
|
||||
}
|
||||
|
||||
/** 摊到画布环节上的角标:谁在这环会被自动跳过、谁在这环要签两次。 */
|
||||
export function dedupNodeMarks(result: DedupAuditResult | null | undefined): Record<string, DedupNodeMarks> {
|
||||
const marks: Record<string, DedupNodeMarks> = {}
|
||||
const bucket = (id: string): DedupNodeMarks => (marks[id] ??= { skip: [], double: [], watch: [] })
|
||||
;(result?.groups ?? []).forEach((group) => {
|
||||
group.nodes.forEach((node) => {
|
||||
const role: DedupRole = node.role
|
||||
if (role === 'sign') return
|
||||
bucket(node.id)[role === 'skip' ? 'skip' : role === 'double' ? 'double' : 'watch'].push(group.name)
|
||||
})
|
||||
})
|
||||
return marks
|
||||
}
|
||||
|
||||
/** 环节上那几条说明去重合并:同一环被多个人提到时只留一句。 */
|
||||
export function dedupNodeNotes(result: DedupAuditResult | null | undefined): string[] {
|
||||
const seen = new Set<string>()
|
||||
;(result?.nodes ?? []).forEach((node) => node.notes.forEach((note) => seen.add(note)))
|
||||
return [...seen]
|
||||
}
|
||||
|
||||
/** 还没被任何一档管住的那些对:并行同展与必批规则这两种不算「配置没配好」。 */
|
||||
function doubles(groups: DedupAuditGroup[]): DedupAuditPair[] {
|
||||
return groups
|
||||
.flatMap((group) => group.pairs)
|
||||
.filter((pair) => pair.outcome === 'double' && BACKSTOPPABLE.includes(pair.cause))
|
||||
}
|
||||
|
||||
/**
|
||||
* 开一档「往回看」就能管住的组:红色的「会签两次」全算,橙色的「要人确认」里
|
||||
* 只挑那种「没被策略管住、只是名单要等运行时才定」的——它们缺的是同一档开关。
|
||||
*/
|
||||
function backstopGroups(result: DedupAuditResult | null | undefined): DedupAuditGroup[] {
|
||||
return (result?.groups ?? []).filter(
|
||||
(group) => group.verdict === 'open' || (group.verdict === 'watch' && doubles([group]).length > 0)
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,137 @@
|
|||
/**
|
||||
* 「这一格能挂什么」的唯一一处口径:自动带出、提交时阈值判断、额度控制。
|
||||
*
|
||||
* 以前这三样各自在界面上写死一份类型白名单(能带出的 7 种、能判阈值的 7 种、能控额度的 7 种),
|
||||
* 三张名单还互不相干:日期格能判阈值却不能带出,人员格能选却不能问一句"有没有填",
|
||||
* 34 种字段类型里二十多种三个面板都看不见——不是功能没有,是界面没给入口。
|
||||
* 这里把它们收成一份,按**这一格装得下什么**来分:
|
||||
*
|
||||
* - 装得下一个数或一句话的:三样全能挂
|
||||
* - 装得下一串/一个对象的(多选、附件、部门、日期区间):能问"有没有填",不能比大小
|
||||
* - 纯排版(标题、分隔线、说明文字):没有值,什么都挂不上
|
||||
*
|
||||
* 判定仍然只在服务端做一次:这里决定的是"设计器摆不摆这一栏、摆哪几个比较符",
|
||||
* 提交时后端照旧按同一份配置再判一遍(``service/threshold.py``、``service/quota.py``)。
|
||||
*/
|
||||
import type { FormFieldDef, LinkageOp, ThresholdConfig } from '@/types'
|
||||
|
||||
export type FieldCapability = 'fetch' | 'threshold' | 'quota'
|
||||
|
||||
/** 今天摆在面板里的全部比较符(比"属于/包含"那几个已经不给了)。 */
|
||||
const OFFERED_OPS: LinkageOp[] = ['gt', 'ge', 'lt', 'le', 'eq', 'ne', 'empty', 'notEmpty']
|
||||
|
||||
/** 装得下一个数:既能比大小,也能直接当额度里那笔钱。 */
|
||||
export const NUMBER_TYPES: string[] = ['money', 'number', 'formula', 'rate']
|
||||
/** 比的是先后,比较符和数值同一档。 */
|
||||
export const DATE_TYPES: string[] = ['date', 'datetime', 'time']
|
||||
/** 装得下一句文本或一个选项值。 */
|
||||
export const TEXT_TYPES: string[] = [
|
||||
'text', 'textarea', 'mobile', 'email', 'idcard', 'url', 'select', 'radio', 'auto', 'hidden'
|
||||
]
|
||||
/** 只有是与不是。 */
|
||||
export const FLAG_TYPES: string[] = ['switch']
|
||||
/** 装的是一串值或一个对象:能问"填了没有",比大小说不清。 */
|
||||
export const BAG_TYPES: string[] = [
|
||||
'daterange', 'checkbox', 'dept', 'cascader', 'user', 'relation', 'address',
|
||||
'attachment', 'image', 'signature', 'sign', 'file'
|
||||
]
|
||||
/** 明细表:一叠行,额度逐行控,阈值只能问"有没有填过行"。 */
|
||||
export const TABLE_TYPES: string[] = ['table']
|
||||
/** 纯排版:没有值。 */
|
||||
export const LAYOUT_TYPES: string[] = ['title', 'divider', 'description']
|
||||
|
||||
const SCALAR_TYPES = [...NUMBER_TYPES, ...DATE_TYPES, ...TEXT_TYPES]
|
||||
|
||||
/** 附件那几类连一笔额度都挂不住,口径与后端 ``quota.UNCONTROLABLE_TYPES`` 一致。 */
|
||||
const UNQUOTABLE_TYPES = ['attachment', 'image', 'signature', 'sign', 'file']
|
||||
|
||||
/** 这一格能不能挂某一样。名单之外的一律当"装不下"处理,新加类型时先归组再用。 */
|
||||
export function canCarry(type: string, cap: FieldCapability): boolean {
|
||||
if (!type || LAYOUT_TYPES.includes(type)) return false
|
||||
if (cap === 'fetch') return SCALAR_TYPES.includes(type)
|
||||
if (cap === 'quota') return !UNQUOTABLE_TYPES.includes(type)
|
||||
return true
|
||||
}
|
||||
|
||||
/** 这一格能挂哪些面板:设计器与字段卡都读这一份,不再各自数名单。 */
|
||||
export function capabilitiesOf(type: string): FieldCapability[] {
|
||||
return (['fetch', 'threshold', 'quota'] as FieldCapability[]).filter((cap) => canCarry(type, cap))
|
||||
}
|
||||
|
||||
/** 阈值能用的比较符:装不下一句数的格子只给"有没有填"这一档。 */
|
||||
export function thresholdOps(type: string): LinkageOp[] {
|
||||
if (NUMBER_TYPES.includes(type) || DATE_TYPES.includes(type) || TEXT_TYPES.includes(type)) {
|
||||
return OFFERED_OPS
|
||||
}
|
||||
if (FLAG_TYPES.includes(type)) return ['eq', 'ne', 'empty', 'notEmpty']
|
||||
return ['empty', 'notEmpty']
|
||||
}
|
||||
|
||||
/** 新配一条阈值时默认给哪个比较符:数值/日期比大小,其余先问有没有填。 */
|
||||
export function defaultThresholdOp(type: string): LinkageOp {
|
||||
return NUMBER_TYPES.includes(type) || DATE_TYPES.includes(type) || TEXT_TYPES.includes(type) ? 'gt' : 'notEmpty'
|
||||
}
|
||||
|
||||
/** 明细表点了列却找不到那一列:类型说不清,比较符也就无从评判(缺哪一列由面板点名)。 */
|
||||
const MISSING_TYPE = '__missing__'
|
||||
|
||||
/**
|
||||
* 这条阈值**实际要比的东西**是什么类型。
|
||||
*
|
||||
* 明细表不再等于"一整串行":点了 `column` 之后,比的是那一列的值,
|
||||
* 列是金额就能比大小、能挑字段当右值,比较符跟着列走。
|
||||
*/
|
||||
export function thresholdSubjectType(field: FormFieldDef, cfg?: ThresholdConfig): string {
|
||||
if (field.type !== 'table') return String(field.type ?? '')
|
||||
const column = String(cfg?.column ?? '').trim()
|
||||
if (!column) return 'table'
|
||||
const hit = ((field.columns ?? []) as FormFieldDef[]).find((item) => String(item.key ?? '') === column)
|
||||
return hit ? String(hit.type ?? '') : MISSING_TYPE
|
||||
}
|
||||
|
||||
/** 这一条阈值能用哪些比较符:口径同后端 ``threshold.ops_for_field``。 */
|
||||
export function thresholdOpsFor(field: FormFieldDef, cfg?: ThresholdConfig): LinkageOp[] {
|
||||
const kind = thresholdSubjectType(field, cfg)
|
||||
return kind === MISSING_TYPE ? [] : thresholdOps(kind)
|
||||
}
|
||||
|
||||
/** 新配一条阈值默认给哪个比较符(明细表点了金额列就默认比大小)。 */
|
||||
export function defaultThresholdOpFor(field: FormFieldDef, cfg?: ThresholdConfig): LinkageOp {
|
||||
const kind = thresholdSubjectType(field, cfg)
|
||||
return kind === MISSING_TYPE ? 'notEmpty' : defaultThresholdOp(kind)
|
||||
}
|
||||
|
||||
/** 这条阈值比的是不是一句数(面板上的措辞与「比什么」那一栏跟着它走)。 */
|
||||
export function holdsNumberFor(field: FormFieldDef, cfg?: ThresholdConfig): boolean {
|
||||
const kind = thresholdSubjectType(field, cfg)
|
||||
return kind !== MISSING_TYPE && holdsNumber(kind)
|
||||
}
|
||||
|
||||
/** 这条阈值的比较符与要比的东西搭不搭(口径同后端 ``problems``)。 */
|
||||
export function thresholdTypeProblemFor(field: FormFieldDef, cfg?: ThresholdConfig): string {
|
||||
const op = String(cfg?.op ?? '')
|
||||
if (!op) return ''
|
||||
const kind = thresholdSubjectType(field, cfg)
|
||||
if (kind === MISSING_TYPE) return ''
|
||||
if (thresholdOps(kind).includes(op as LinkageOp)) return ''
|
||||
return thresholdTypeProblem(kind, op)
|
||||
}
|
||||
|
||||
/** 这一格能不能自己装下阈值要比的那个数(面板上的措辞跟着变)。 */
|
||||
export function holdsNumber(type: string): boolean {
|
||||
return NUMBER_TYPES.includes(type) || DATE_TYPES.includes(type) || TEXT_TYPES.includes(type)
|
||||
}
|
||||
|
||||
/**
|
||||
* 阈值配置与字段类型搭不搭。回空串表示没问题。
|
||||
*
|
||||
* 只对新放开的那些类型说话(多选、附件、开关、明细表……以前根本挂不上阈值),
|
||||
* 老配置能配出来的组合一概不报,免得一夜之间满地都是历史毛病。
|
||||
*/
|
||||
export function thresholdTypeProblem(type: string, op: string): string {
|
||||
if (!op) return ''
|
||||
if (thresholdOps(type).includes(op as LinkageOp)) return ''
|
||||
return BAG_TYPES.includes(type) || TABLE_TYPES.includes(type)
|
||||
? '这一格装的是一串值,阈值只能问它填了没有(为空 / 不为空)'
|
||||
: '这一格比不了大小,换一个比较符'
|
||||
}
|
||||
|
|
@ -0,0 +1,45 @@
|
|||
/**
|
||||
* 设计器用的流程清单 + 分类清单:挑流程的地方都从这一份拿。
|
||||
*
|
||||
* 「只允许关联某个流程」「带出另一个流程的数据」这些面板一次挂好几个,每个自己发一次请求
|
||||
* 既慢又容易各看各的。这里缓存一小会儿(60 秒):够盖住一次设计过程里的反复点开,
|
||||
* 又不至于新建了流程还要刷新页面才看得见。
|
||||
*/
|
||||
import { designAPI } from '@/api'
|
||||
import type { Category, ProcessDef } from '@/types'
|
||||
|
||||
export interface ProcessCatalog {
|
||||
categories: Category[]
|
||||
processes: ProcessDef[]
|
||||
}
|
||||
|
||||
/** 没归到任何分类的流程单独占一档,不然它们永远选不到。 */
|
||||
export const UNCATEGORISED = '__none__'
|
||||
|
||||
const TTL_MS = 60_000
|
||||
|
||||
let cache: { at: number; value: ProcessCatalog } | null = null
|
||||
let inflight: Promise<ProcessCatalog> | null = null
|
||||
|
||||
const EMPTY: ProcessCatalog = { categories: [], processes: [] }
|
||||
|
||||
export function processCatalog(force = false): Promise<ProcessCatalog> {
|
||||
if (!force && cache && Date.now() - cache.at < TTL_MS) return Promise.resolve(cache.value)
|
||||
if (inflight) return inflight
|
||||
inflight = Promise.all([designAPI.listCategories(), designAPI.listProcesses()])
|
||||
.then(([categories, processes]) => {
|
||||
const value = { categories, processes }
|
||||
cache = { at: Date.now(), value }
|
||||
return value
|
||||
})
|
||||
.catch(() => EMPTY)
|
||||
.finally(() => {
|
||||
inflight = null
|
||||
})
|
||||
return inflight
|
||||
}
|
||||
|
||||
/** 这条流程属于哪一档(没分类的落到未分类那一档)。 */
|
||||
export function categoryOf(item: ProcessDef): string {
|
||||
return item.category || UNCATEGORISED
|
||||
}
|
||||
|
|
@ -0,0 +1,116 @@
|
|||
import type { DataSource, ProcessDataFilter, ProcessDataMatch, ProcessFieldOption } from '@/types'
|
||||
|
||||
/**
|
||||
* 「从另一个流程带数据」这条通道的界面口径。
|
||||
*
|
||||
* 它不是一个新功能,而是数据源的一种 provider:字段上挂的还是那份 ``fetch`` 配置,
|
||||
* 所以带出、多源合集、写入哪几格、留痕、提交时服务端覆盖全部复用外部取数那一条链路
|
||||
* (后端 service/processdata.py + service/fetch.py)。
|
||||
*
|
||||
* 这个文件只干两件脏活:把「勾选要带出哪些字段」翻译成 ``pick`` / ``mapExtra`` 里
|
||||
* 那两条点路径,以及把翻译结果翻回来给界面回显。翻译只在这一处,界面不再自己拼字符串。
|
||||
*/
|
||||
|
||||
/** 数据源是不是流程数据通道。 */
|
||||
export function isProcessSource(source: DataSource | null | undefined): boolean {
|
||||
return String(source?.provider ?? '') === 'process'
|
||||
}
|
||||
|
||||
/** 能带的比较符。和后端 service/processdata.OPS 一一对应,多一个就是一次口径漂移。 */
|
||||
export const PROCESS_OPS = ['eq', 'ne', 'contains', 'in', 'gt', 'gte', 'lt', 'lte', 'empty', 'notEmpty'] as const
|
||||
|
||||
/** 这几档不需要取值,界面上把输入框收起来。 */
|
||||
export const PROCESS_VALUE_OPS = ['eq', 'ne', 'contains', 'in', 'gt', 'gte', 'lt', 'lte']
|
||||
|
||||
/** 一条源最多几个匹配条件;与后端 service/processdata.MAX_FILTERS 同一档。 */
|
||||
export const MAX_FILTERS = 8
|
||||
|
||||
/** 候选扫描上限:条件是在最近这么多单里筛的,界面上要说这一句。 */
|
||||
export const SCAN_LIMIT = 300
|
||||
|
||||
/** 带出范围:默认只查自己的单,跨人必须显式选并配调用权限。 */
|
||||
export const PROCESS_SCOPES = ['own', 'all']
|
||||
export const PROCESS_STATUSES = ['completed', 'running', 'any']
|
||||
export const PROCESS_ORDERS = ['latest', 'earliest']
|
||||
|
||||
/** 新建一条流程数据源时的匹配配置;每一档都取安全侧。 */
|
||||
export function defaultMatch(): ProcessDataMatch {
|
||||
return { scope: 'own', person: '', status: 'completed', order: 'latest', days: 0, limit: 20, filters: [] }
|
||||
}
|
||||
|
||||
/** 表单字段在「那份响应」里的路径;与后端 processdata.payload_of 的形状对齐。 */
|
||||
export function fieldPath(key: string): string {
|
||||
return `data.${String(key || '').trim()}`
|
||||
}
|
||||
|
||||
/** 主值取自哪个字段(``pick`` 写回 data.<key>);不是字段路径就回空串。 */
|
||||
export function mainFieldOfPick(pick: string | undefined): string {
|
||||
const text = String(pick || '').trim()
|
||||
return text.startsWith('data.') ? text.slice('data.'.length) : ''
|
||||
}
|
||||
|
||||
/** 已经勾上的字段(含当作主值那一格),按字段清单的顺序回。 */
|
||||
export function tickedFields(source: DataSource | null | undefined, fields: ProcessFieldOption[]): string[] {
|
||||
if (!source) return []
|
||||
const picked = new Set(Object.values(source.mapExtra || {}).map((path) => String(path || '')))
|
||||
const main = String(source.pick || '').trim()
|
||||
if (main) picked.add(main)
|
||||
const wanted = new Set([...picked].map((path) => path.replace(/^data\./, '')))
|
||||
return fields.map((item) => item.key).filter((key) => wanted.has(key))
|
||||
}
|
||||
|
||||
/** 按勾选结果写回 pick 与 mapExtra:主值是第一个勾的字段。 */
|
||||
export function writePicked(
|
||||
keys: string[],
|
||||
mainKey: string
|
||||
): { pick: string; mapExtra: Record<string, string> } {
|
||||
const mapExtra: Record<string, string> = {}
|
||||
keys.forEach((key) => {
|
||||
mapExtra[key] = fieldPath(key)
|
||||
})
|
||||
return { pick: mainKey ? fieldPath(mainKey) : '', mapExtra }
|
||||
}
|
||||
|
||||
/** 主值候选:勾在 mapExtra 里的字段也能当主值,所以直接用勾选清单。 */
|
||||
export function labelOf(fields: ProcessFieldOption[], key: string): string {
|
||||
return fields.find((item) => item.key === key)?.label || key
|
||||
}
|
||||
|
||||
/** 匹配配置里有没有已经认不出的字段(目标流程改了表单),界面据此提醒一句。 */
|
||||
export function missingFilterFields(
|
||||
match: ProcessDataMatch | undefined,
|
||||
fields: ProcessFieldOption[]
|
||||
): string[] {
|
||||
if (!fields.length) return []
|
||||
const known = new Set(fields.map((item) => item.key))
|
||||
return (match?.filters ?? [])
|
||||
.map((item) => String(item.field || '').trim())
|
||||
.filter((key) => key && !known.has(key))
|
||||
}
|
||||
|
||||
/** 这条源在字段上那一栏要显示的一句话。 */
|
||||
export function processSourceSummary(
|
||||
source: DataSource,
|
||||
processName: string,
|
||||
labels: { status: Record<string, string>; scope: Record<string, string> }
|
||||
): string {
|
||||
const match = source.srcMatch || {}
|
||||
const status = labels.status[match.status ?? 'completed'] ?? ''
|
||||
const scope = labels.scope[match.scope ?? 'own'] ?? ''
|
||||
const filters = (match.filters ?? []).filter((item) => String(item.field || '').trim()).length
|
||||
const bits = [processName ? `${processName}` : '', status, scope]
|
||||
if (filters) bits.push(`${filters} 个匹配条件`)
|
||||
return bits.filter(Boolean).join(' · ')
|
||||
}
|
||||
|
||||
/** 一条匹配条件是不是配完整了(没填值 / 没选字段的那些不进请求)。 */
|
||||
export function usableFilters(filters: ProcessDataFilter[] | undefined): ProcessDataFilter[] {
|
||||
return (filters ?? [])
|
||||
.map((item) => ({
|
||||
field: String(item.field || '').trim(),
|
||||
op: String(item.op || 'eq').trim(),
|
||||
value: String(item.value ?? '').trim()
|
||||
}))
|
||||
.filter((item) => item.field && PROCESS_OPS.includes(item.op as (typeof PROCESS_OPS)[number]))
|
||||
.filter((item) => PROCESS_VALUE_OPS.includes(item.op) ? Boolean(item.value) : true)
|
||||
}
|
||||
|
|
@ -0,0 +1,406 @@
|
|||
/**
|
||||
* 「额度控制」配置面板的公共逻辑:替人把映射猜出来、把配置讲成人话、顺手挑毛病。
|
||||
*
|
||||
* 这里只碰**配置的形状**,不碰台账与提交判断——可用额度怎么算、超支怎么挡,
|
||||
* 口径仍然只在后端一处(``backend/app/service/quota.py``)。面板上做的一切
|
||||
* 最后都落回同一份 ``field.quota``,与历史配置完全兼容。
|
||||
*/
|
||||
import type { FormFieldDef, QuotaDef, QuotaFieldConfig } from '@/types'
|
||||
|
||||
/** 后端写回的那三个数。顺序就是面板上勾选的顺序:最常看的排最前。 */
|
||||
export type QuotaSlot = 'avail' | 'used' | 'total'
|
||||
|
||||
export const QUOTA_SLOTS: QuotaSlot[] = ['avail', 'used', 'total']
|
||||
|
||||
/** 装得下一笔钱的列/格类型。公式格不算:它每次联动都会重算,会把带出来的数盖掉。 */
|
||||
export const MONEY_TYPES: string[] = ['money', 'number']
|
||||
/** 能当「本次金额」的列:再多认公式列,因为它算得出来就是准的。 */
|
||||
export const AMOUNT_TYPES: string[] = ['money', 'number', 'formula']
|
||||
|
||||
/** 维度键里的英文词 → 中文叫法。猜映射时靠它把 `advanceNo` 对上「备用金单号」那一列。 */
|
||||
const WORD_HINTS: Record<string, string[]> = {
|
||||
advance: ['备用金', '借款', '垫款'],
|
||||
loan: ['借款', '借支'],
|
||||
borrow: ['借款', '借支'],
|
||||
budget: ['预算', '科目'],
|
||||
cost: ['成本'],
|
||||
center: ['中心'],
|
||||
account: ['科目', '账户'],
|
||||
subject: ['科目'],
|
||||
project: ['项目'],
|
||||
contract: ['合同'],
|
||||
year: ['年度', '年份'],
|
||||
month: ['月份', '月度'],
|
||||
dept: ['部门', '组织'],
|
||||
department: ['部门'],
|
||||
org: ['组织', '部门'],
|
||||
person: ['人员', '员工', '申请人'],
|
||||
staff: ['员工', '人员'],
|
||||
owner: ['归属人', '负责人'],
|
||||
amount: ['金额', '额度'],
|
||||
money: ['金额'],
|
||||
total: ['合计', '总额'],
|
||||
no: ['单号', '编号', '号码'],
|
||||
code: ['编码', '编号', '代码'],
|
||||
name: ['名称'],
|
||||
type: ['类型', '种类'],
|
||||
category: ['类别', '科目'],
|
||||
settle: ['冲销', '核销'],
|
||||
offset: ['冲销', '核销'],
|
||||
expense: ['费用', '报销'],
|
||||
reimburse: ['报销'],
|
||||
travel: ['差旅'],
|
||||
apply: ['申请'],
|
||||
date: ['日期'],
|
||||
supplier: ['供应商'],
|
||||
vendor: ['供应商']
|
||||
}
|
||||
|
||||
/** 三个数各自在表单里通常叫什么。越靠前越具体,匹配时按这个顺序找。 */
|
||||
const SLOT_HINTS: Record<QuotaSlot, string[]> = {
|
||||
avail: ['还可冲', '还可用', '剩余', '可用额度', '可用', '余额', 'available', 'remain', 'balance'],
|
||||
used: ['已冲销', '已核销', '已冲', '已用', '已报', '已还', 'used', 'settled', 'offset'],
|
||||
total: ['借款金额', '借款额', '预算总额', '预算金额', '总额度', '总额', 'total', 'quota']
|
||||
}
|
||||
|
||||
/** 「本次金额」那一列/那一格的常见叫法。 */
|
||||
const AMOUNT_HINTS = [
|
||||
'本次冲销金额', '本次冲销', '本次申请金额', '本次金额', '本次报销', '本次',
|
||||
'冲销金额', '报销金额', '申请金额', '金额合计', '合计', 'amount', 'money', 'total'
|
||||
]
|
||||
|
||||
/** 面板上「新建一格」时给的中文名。 */
|
||||
export const SLOT_LABELS: Record<QuotaSlot, string> = {
|
||||
avail: '可用额度',
|
||||
used: '已核销',
|
||||
total: '总额'
|
||||
}
|
||||
|
||||
function norm(text: unknown): string {
|
||||
return String(text ?? '').toLowerCase().replace(/[\s_\-·、()()::]/g, '')
|
||||
}
|
||||
|
||||
/** `advanceNo` → `['advance', 'no']`;中文名原样回来。 */
|
||||
export function dimWords(dim: string): string[] {
|
||||
const text = String(dim ?? '').trim()
|
||||
if (!text) return []
|
||||
if (/[一-龥]/.test(text)) return [text]
|
||||
return (text.replace(/([a-z0-9])([A-Z])/g, '$1 $2').match(/[a-z0-9]+/gi) ?? []).map((word) =>
|
||||
word.toLowerCase()
|
||||
)
|
||||
}
|
||||
|
||||
/** 把维度键翻成人话:`advanceNo` → 备用金单号;翻不动就原样回。 */
|
||||
export function dimLabel(dim: string): string {
|
||||
const words = dimWords(dim)
|
||||
if (!words.length) return String(dim ?? '')
|
||||
if (words.length === 1 && /[一-龥]/.test(words[0])) return words[0]
|
||||
const parts = words.map((word) => WORD_HINTS[word]?.[0] ?? '')
|
||||
return parts.every(Boolean) ? parts.join('') : String(dim)
|
||||
}
|
||||
|
||||
/** 一个维度键能接受的所有线索词(中文叫法 + 英文词本身)。 */
|
||||
function dimHints(dim: string): string[] {
|
||||
const words = dimWords(dim)
|
||||
const out: string[] = [...words]
|
||||
words.forEach((word) => (WORD_HINTS[word] ?? []).forEach((hint) => out.push(hint)))
|
||||
const label = dimLabel(dim)
|
||||
if (label !== dim) out.unshift(label)
|
||||
return out.filter(Boolean)
|
||||
}
|
||||
|
||||
interface Candidate {
|
||||
key: string
|
||||
label: string
|
||||
type: string
|
||||
readonly?: boolean
|
||||
dictCode?: string
|
||||
options?: unknown[]
|
||||
}
|
||||
|
||||
function toCandidate(item: FormFieldDef): Candidate {
|
||||
return {
|
||||
key: String(item.key ?? ''),
|
||||
label: String(item.label ?? item.key ?? ''),
|
||||
type: String(item.type ?? ''),
|
||||
readonly: Boolean(item.readonly),
|
||||
dictCode: String(item.dictCode ?? ''),
|
||||
options: item.options
|
||||
}
|
||||
}
|
||||
|
||||
function hits(text: string, keywords: string[]): boolean {
|
||||
const hay = norm(text)
|
||||
return keywords.some((word) => hay.includes(norm(word)))
|
||||
}
|
||||
|
||||
/**
|
||||
* 按线索词挑一格:外层按线索词的优先级走,内层看候选。
|
||||
*
|
||||
* 为什么要这个顺序——「可用额度」「借款金额」「本次冲销金额」三列都带「金额」,
|
||||
* 反过来按列扫会把「总额」认成本次金额。线索词写在前面的才是专属叫法。
|
||||
*/
|
||||
function pick(
|
||||
candidates: Candidate[],
|
||||
keywords: string[],
|
||||
accept: (item: Candidate) => boolean
|
||||
): Candidate | null {
|
||||
for (const word of keywords) {
|
||||
const hit = candidates.find((item) => accept(item) && hits(item.label, [word]))
|
||||
if (hit) return hit
|
||||
}
|
||||
for (const word of keywords) {
|
||||
const hit = candidates.find((item) => accept(item) && hits(item.key, [word]))
|
||||
if (hit) return hit
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** 维度那一格:先认列名/键名对得上的,再认中文叫法对得上的,最后退到选择列。 */
|
||||
function pickDim(candidates: Candidate[], dim: string): Candidate | null {
|
||||
const key = norm(dim)
|
||||
const exact = candidates.find((item) => norm(item.key) === key)
|
||||
if (exact) return exact
|
||||
const sameKey = candidates.find((item) => norm(item.key).includes(key) || key.includes(norm(item.key)))
|
||||
if (sameKey) return sameKey
|
||||
const hints = dimHints(dim)
|
||||
return pick(candidates, hints, () => true)
|
||||
}
|
||||
|
||||
/** 一张明细表 / 一组表单字段里,能被额度当配置目标用的候选。 */
|
||||
function pool(items: FormFieldDef[], selfKey = ''): Candidate[] {
|
||||
return items.filter((item) => item.key && item.key !== selfKey).map(toCandidate)
|
||||
}
|
||||
|
||||
/** 猜出来的一份映射,以及「哪些是从猜的、哪些还缺」。 */
|
||||
export interface QuotaGuess {
|
||||
/** 只填了能确定的那几项,其余留空,交给面板提示去催 */
|
||||
cfg: Pick<QuotaFieldConfig, 'amount' | 'dims' | 'show'> & { rows?: QuotaFieldConfig['rows'] }
|
||||
/** 摘要行:维度与本次金额各认到了哪一列 */
|
||||
matched: Array<{ name: string; from: string }>
|
||||
/** 摘要行下面的「还可显示」:三个数各认到了哪一格 */
|
||||
shown: Array<{ slot: QuotaSlot; from: string }>
|
||||
/** 缺什么(面板上直接念出来,并给一个「去补」的入口) */
|
||||
missing: string[]
|
||||
/** 什么都没认出来:多半是明细表还没建列 */
|
||||
empty: boolean
|
||||
}
|
||||
|
||||
type ShowTargets = { total?: string; used?: string; avail?: string }
|
||||
|
||||
function slotTargets(items: Array<{ slot: QuotaSlot; key: string }>): ShowTargets {
|
||||
const out: ShowTargets = {}
|
||||
items.forEach((item) => {
|
||||
if (item.key) out[item.slot] = item.key
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
||||
/** 带出位的候选:只读金额格优先,因为它天生就是给后端写数的。 */
|
||||
function pickShown(candidates: Candidate[], slot: QuotaSlot, exclude: string): Candidate | null {
|
||||
const list = candidates.filter((item) => MONEY_TYPES.includes(item.type) && item.key !== exclude)
|
||||
return (
|
||||
pick(list.filter((item) => item.readonly), SLOT_HINTS[slot], () => true) ??
|
||||
pick(list, SLOT_HINTS[slot], () => true)
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 选完额度定义之后的「已自动识别」:按维度名、列名、列叫法猜一遍映射。
|
||||
*
|
||||
* 猜错了不要紧——面板上原样列出认到的每一对,高级里都能改;不猜就得让人
|
||||
* 一上来面对八个下拉框,那是这个面板以前最劝退的地方。
|
||||
*/
|
||||
export function guessQuotaMapping(
|
||||
def: QuotaDef | null,
|
||||
field: FormFieldDef,
|
||||
siblings: FormFieldDef[] = []
|
||||
): QuotaGuess {
|
||||
const dims = (def?.dims ?? []).map(String)
|
||||
const matched: QuotaGuess['matched'] = []
|
||||
const shown: QuotaGuess['shown'] = []
|
||||
const missing: string[] = []
|
||||
const isTable = field.type === 'table'
|
||||
const columns = pool((field.columns ?? []) as FormFieldDef[])
|
||||
const fields = pool(siblings, String(field.key ?? ''))
|
||||
|
||||
if (isTable) {
|
||||
const rowDims: Record<string, string> = {}
|
||||
const taken: string[] = []
|
||||
dims.forEach((dim) => {
|
||||
const hit = pickDim(columns, dim)
|
||||
if (hit) {
|
||||
rowDims[dim] = hit.key
|
||||
taken.push(hit.key)
|
||||
matched.push({ name: dimLabel(dim), from: hit.label })
|
||||
} else {
|
||||
missing.push(dimLabel(dim))
|
||||
}
|
||||
})
|
||||
const amount = pick(
|
||||
columns.filter((item) => !taken.includes(item.key)),
|
||||
AMOUNT_HINTS,
|
||||
(item) => AMOUNT_TYPES.includes(item.type)
|
||||
)
|
||||
if (amount) matched.push({ name: '本次金额', from: amount.label })
|
||||
else missing.push('本次金额')
|
||||
QUOTA_SLOTS.forEach((slot) => {
|
||||
const hit = pickShown(columns, slot, amount?.key ?? '')
|
||||
if (hit) shown.push({ slot, from: hit.label })
|
||||
})
|
||||
const rowShow = slotTargets(shown.map((item) => ({ slot: item.slot, key: columnKeyOf(columns, item.from) })))
|
||||
return {
|
||||
cfg: {
|
||||
amount: '',
|
||||
dims: {},
|
||||
show: {},
|
||||
rows: { dims: rowDims, amount: amount?.key ?? '', show: rowShow }
|
||||
},
|
||||
matched,
|
||||
shown,
|
||||
missing,
|
||||
empty: !matched.length && !shown.length
|
||||
}
|
||||
}
|
||||
|
||||
const self = toCandidate(field)
|
||||
const dimCfg: Record<string, string> = {}
|
||||
dims.forEach((dim) => {
|
||||
const hit = pickDim(fields, dim)
|
||||
if (hit) {
|
||||
dimCfg[dim] = `{form:${hit.key}}`
|
||||
matched.push({ name: dimLabel(dim), from: hit.label })
|
||||
}
|
||||
// 认不到也先不催:后端本来就把没写的维度退到 `{form:<同名>}`,同名格子真不存在时自检会说
|
||||
})
|
||||
const amount =
|
||||
MONEY_TYPES.includes(self.type) || self.type === 'formula'
|
||||
? self
|
||||
: pick(fields, AMOUNT_HINTS, (item) => AMOUNT_TYPES.includes(item.type))
|
||||
if (amount) {
|
||||
matched.push({ name: '本次金额', from: amount === self ? `${amount.label}(本格)` : amount.label })
|
||||
} else {
|
||||
missing.push('本次金额')
|
||||
}
|
||||
QUOTA_SLOTS.forEach((slot) => {
|
||||
const hit = pickShown(fields, slot, amount?.key ?? '')
|
||||
if (hit) shown.push({ slot, from: hit.label })
|
||||
})
|
||||
return {
|
||||
cfg: {
|
||||
amount: amount ? `{form:${amount.key}}` : '',
|
||||
dims: dimCfg,
|
||||
show: slotTargets(shown.map((item) => ({ slot: item.slot, key: fieldKeyOf(fields, item.from) })))
|
||||
},
|
||||
matched,
|
||||
shown,
|
||||
missing,
|
||||
empty: !matched.length && !shown.length
|
||||
}
|
||||
}
|
||||
|
||||
function columnKeyOf(columns: Candidate[], label: string): string {
|
||||
return columns.find((item) => item.label === label)?.key ?? ''
|
||||
}
|
||||
|
||||
function fieldKeyOf(fields: Candidate[], label: string): string {
|
||||
return fields.find((item) => item.label === label)?.key ?? ''
|
||||
}
|
||||
|
||||
/** 自动补格子的键名:跟着当前字段走,重了就加后缀。 */
|
||||
export function quotaSlotKey(fieldKey: string, slot: QuotaSlot, taken: Iterable<string>): string {
|
||||
const used = new Set(Array.from(taken))
|
||||
const base = `${String(fieldKey || 'quota')}_${slot}`
|
||||
if (!used.has(base)) return base
|
||||
let suffix = 2
|
||||
while (used.has(`${base}_${suffix}`)) suffix += 1
|
||||
return `${base}_${suffix}`
|
||||
}
|
||||
|
||||
/** 新建那一格:只读金额,精度两位——勾了显示,它就该是后端写、人改不了的。 */
|
||||
export function quotaHolderField(key: string, label: string): FormFieldDef {
|
||||
return {
|
||||
key,
|
||||
label,
|
||||
type: 'money',
|
||||
required: false,
|
||||
readonly: true,
|
||||
precision: 2
|
||||
} as FormFieldDef
|
||||
}
|
||||
|
||||
/** 明细表里补一列只读金额:列名跟着额度字段走,免得几张明细表撞名。 */
|
||||
export function quotaSlotColumn(fieldKey: string, slot: QuotaSlot, taken: Iterable<string>): FormFieldDef {
|
||||
return {
|
||||
key: quotaSlotKey(fieldKey || 'quota', slot, taken),
|
||||
label: SLOT_LABELS[slot],
|
||||
type: 'money',
|
||||
readonly: true,
|
||||
precision: 2
|
||||
} as FormFieldDef
|
||||
}
|
||||
|
||||
/**
|
||||
* 面板上的自检:拿这份配置当场念一遍毛病,不用等保存。
|
||||
*
|
||||
* 规则与后端 ``quota.problems`` 同一把尺子,只是这里能拿到额度定义与列清单,
|
||||
* 说的是「还差哪一列」这种具体话;真正挡住保存的还是后端那一道。
|
||||
*/
|
||||
export function lintQuota(
|
||||
def: QuotaDef | null,
|
||||
field: FormFieldDef,
|
||||
cfg: QuotaFieldConfig,
|
||||
siblings: FormFieldDef[] = []
|
||||
): string[] {
|
||||
const out: string[] = []
|
||||
if (!String(cfg.def ?? '').trim()) return out
|
||||
const dims = (def?.dims ?? []).map(String)
|
||||
const isTable = field.type === 'table'
|
||||
const columns = ((field.columns ?? []) as FormFieldDef[]).map((item) => String(item.key ?? ''))
|
||||
const keys = new Set(siblings.map((item) => String(item.key ?? '')))
|
||||
|
||||
if (isTable) {
|
||||
const rows = cfg.rows ?? {}
|
||||
const amountCol = String(rows.amount ?? '').trim()
|
||||
if (amountCol && !columns.includes(amountCol)) out.push(`本次金额那一列「${amountCol}」在明细表里不存在`)
|
||||
dims.forEach((dim) => {
|
||||
// 没点名的维度由后端退到同名列,缺没缺那一列交给面板上的「还差」说,这里只抓写歪了的
|
||||
const column = String(rows.dims?.[dim] ?? '').trim()
|
||||
if (column && !columns.includes(column)) out.push(`维度「${dimLabel(dim)}」指向的列「${column}」在明细表里不存在`)
|
||||
})
|
||||
const used: string[] = []
|
||||
QUOTA_SLOTS.forEach((slot) => {
|
||||
const target = String((rows.show as Record<string, string> | undefined)?.[slot] ?? '').trim()
|
||||
if (!target) return
|
||||
if (!columns.includes(target)) out.push(`${SLOT_LABELS[slot]}要写进的列「${target}」不存在`)
|
||||
else if (target === amountCol) out.push(`${SLOT_LABELS[slot]}不能写在本次金额那一列,会被盖掉`)
|
||||
else if (used.includes(target)) out.push(`有两格都写进了列「${target}」,会互相盖掉`)
|
||||
used.push(target)
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
||||
const amountRef = fieldRef(cfg.amount)
|
||||
if (amountRef && !keys.has(amountRef)) out.push(`本次金额引用的字段「${amountRef}」不存在`)
|
||||
// 没点名的维度由后端退到同名字段,缺不缺那一格让「还差」去说,这里不重复报
|
||||
Object.entries(cfg.dims ?? {}).forEach(([dim, expr]) => {
|
||||
const ref = fieldRef(expr)
|
||||
if (ref && !keys.has(ref)) out.push(`维度「${dimLabel(dim)}」引用的字段「${ref}」不存在`)
|
||||
})
|
||||
const used: string[] = []
|
||||
QUOTA_SLOTS.forEach((slot) => {
|
||||
const target = String((cfg.show as Record<string, string> | undefined)?.[slot] ?? '').trim()
|
||||
if (!target) return
|
||||
if (!keys.has(target)) out.push(`${SLOT_LABELS[slot]}要写进的字段「${target}」不存在`)
|
||||
else if (target === String(field.key ?? '')) out.push(`${SLOT_LABELS[slot]}不能写回本格,会把本次金额盖掉`)
|
||||
else if (used.includes(target)) out.push(`有两格都写进了字段「${target}」,会互相盖掉`)
|
||||
used.push(target)
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
||||
/** `{form.x}` / `{form:x}` 里的字段名;不是这种写法回空串(与后端同口径)。 */
|
||||
export function fieldRef(expr: unknown): string {
|
||||
const match = /^\{form[.:]([^}]+)\}$/.exec(String(expr ?? '').trim())
|
||||
return match ? match[1] : ''
|
||||
}
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
/**
|
||||
* 额度下拉那一行怎么念。
|
||||
*
|
||||
* 后端按额度定义的「下拉显示」渲染好 `label`(写法见
|
||||
* `backend/app/service/quota.py:quota_label`),这里原样念出来:
|
||||
* 填报时的下拉、额度定义页的预览、配置面板的台账预览都从这里出,
|
||||
* 免得三处各改一遍、改一处漏两处。
|
||||
*
|
||||
* 配成什么样就念成什么样,界面不自己添内容——想看「还可冲多少」就在
|
||||
* 模板里写 `{avail}`,不写就不出现。
|
||||
*/
|
||||
import type { QuotaOption } from '@/types'
|
||||
|
||||
/** 后端渲染不出东西时会自己退回来源单据标题,所以这里只剩「取不到就退回取值」。 */
|
||||
export function quotaPickLabel(item: QuotaOption): string {
|
||||
const label = String(item.label ?? '').trim()
|
||||
return label || String(item.value ?? '').trim()
|
||||
}
|
||||
Loading…
Reference in New Issue