1573 lines
88 KiB
Python
1573 lines
88 KiB
Python
"""写回报文的映射渲染器 -- L2 模板里那份 JSON 怎么变成真正发出去的报文。
|
||
|
||
配置化写回的底气全在这一层:**取值语法刻意做小**(见
|
||
``docs/outbound-integration-design.md`` §4),只做五种写法 + 一小组转换函数,
|
||
余下一律当字面量。三样东西直接复用现成实现,一个新语言都不造:
|
||
|
||
- 条件发送复用 ``dicts.condition_ok``(和设计器里的条件显隐/条件必填同一份数据结构);
|
||
- 派生值复用 ``expressions`` 沙箱(``__builtins__`` 已清空,**沙箱里不许有 IO**);
|
||
- 枚举翻译复用数据字典(OA 的「差旅费」→ ERP 的「660001」,运营改字典就行,不用发版)。
|
||
|
||
渲染的输入是 ``{data, work, actor}`` —— 和引擎现成的表达式上下文同一份,
|
||
配置页照着 ``work.`` 下面那几个键名列即可。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import re
|
||
from datetime import datetime
|
||
from typing import Any, Iterable
|
||
|
||
from sqlalchemy import select
|
||
from sqlalchemy.orm import Session
|
||
|
||
from .. import models
|
||
from . import autofill, binding, dicts, org, quota
|
||
from .quota import DATE_FORMATS, to_cents
|
||
|
||
#: 整段就是一个 ``{...}`` 时按原类型给(金额不该变成字符串),拼串写法才转字符串
|
||
TOKEN_ALL = re.compile(r"^\{([^{}]+)\}$")
|
||
#: 串里的每一个 ``{...}``
|
||
TOKEN_ANY = re.compile(r"\{([^{}]+)\}")
|
||
#: 八种取值写法的前缀:认不出的前缀一律当固定文本发出去(设计期由 ``_ref_problems`` 点名)
|
||
REF_KINDS = ("form", "item", "work", "activity", "action", "auto", "const", "attach")
|
||
#: 前缀 + 分隔符:``form.x`` / ``form:x`` / ``cents:form.x`` / ``auto:today:YYYY`` 都从这里起手
|
||
KIND_HEAD = re.compile(r"^([A-Za-z_]+)\s*[:.]\s*(.*)$", re.S)
|
||
#: 转换函数就这九个:缺了先不加,加一个是长期复用的开发(§11)。
|
||
#: ``account`` 是最后一个,因为它补的是一个**翻译**而不是一个格式:选人字段那一格现在
|
||
#: 存的本来就是登录账号,但值也可能是集成方写进来的老身份 DN、脚本拼出来的姓名,而 SQL
|
||
#: 与上游报文要的是账号——这一层换算不能交给配置的人在语句里拆字符串(拆还拆不对:
|
||
#: DN 末段未必是账号,部门改过一次名之后末段是姓名)。见 :func:`org.person_account`。
|
||
TRANSFORMS = ("cents", "yuan", "date", "trim", "upper", "default", "join", "bool", "account")
|
||
#: 幂等键能用的变量(``phase`` 是触发时刻、``target`` 是退回落到的那一环、``via`` 是这一退
|
||
#: 谁按的,见 :func:`idem_key`)
|
||
IDEM_VARS = ("source", "code", "job", "serial", "work", "event", "event_key",
|
||
"phase", "target", "via", "revision", "today")
|
||
#: L3 挂载的四种触发时机(常量放在这一层:设计期校验与运行期入队共用一把尺子,
|
||
#: ``outbox`` 直接拿这几个值,不再各写一份)。
|
||
#: ``arrive`` / ``leave`` 由引擎在 ``_advance`` 里表达;``goBack`` / ``recall`` 是「退回」与
|
||
#: 「撤回已办」这两颗按钮——它们**不经过** ``_advance``(``go_back`` / ``reset_task`` 自己派
|
||
#: 待办),所以钩子另有两处,口径见 ``docs/node-writeback-config.md`` §1 §1.5 §13。
|
||
TRIGGER_ARRIVE = "arrive"
|
||
TRIGGER_LEAVE = "leave"
|
||
TRIGGER_GOBACK = "goBack"
|
||
TRIGGER_RECALL = "recall"
|
||
TRIGGERS = (TRIGGER_ARRIVE, TRIGGER_LEAVE, TRIGGER_GOBACK, TRIGGER_RECALL)
|
||
#: 触发时刻的中文说法:体检文案、``{action.phase_name}``、发件箱那一列共用一份
|
||
TRIGGER_LABELS = {
|
||
TRIGGER_ARRIVE: "到达本环节时",
|
||
TRIGGER_LEAVE: "本环节审批通过后",
|
||
TRIGGER_GOBACK: "本环节被退回时",
|
||
TRIGGER_RECALL: "本环节被撤回时",
|
||
}
|
||
#: 退回 / 撤回这两个时刻要在幂等键里补一段,才和「通过后」那条分得开。``arrive`` /
|
||
#: ``leave`` 那一段**留空**:存量报文的幂等键一个字节都不变,升级之后旧单第二次命中仍旧
|
||
#: 并回原来那条,不会有人平白多收到一张凭证。
|
||
PHASE_KEY_TRIGGERS = (TRIGGER_GOBACK, TRIGGER_RECALL)
|
||
#: 时刻的写法归一:设计器存驼峰(与路由上 ``decision=goBack`` 同词),手改的 JSON 与导出件
|
||
#: 习惯下划线小写,别处导来的流程件还可能带 ``retract`` 这类同义词。读法只有
|
||
#: :func:`trigger_of` 一处,别出现"界面存 goBack、运行期只认 goback"。
|
||
TRIGGER_ALIASES = {
|
||
"arrive": TRIGGER_ARRIVE,
|
||
"leave": TRIGGER_LEAVE,
|
||
"goback": TRIGGER_GOBACK, "go_back": TRIGGER_GOBACK, "back": TRIGGER_GOBACK,
|
||
"recall": TRIGGER_RECALL, "retract": TRIGGER_RECALL, "reset": TRIGGER_RECALL,
|
||
}
|
||
#: 每个时刻能被哪些环节类型触发。配在这个环节根本没有的时刻 = 一条都不发的死配置,
|
||
#: 界面上不给选、保存流程时挡(与 :data:`ONE_WAY_TRIGGER` 同一条原则)。
|
||
#: ``None`` = 不限环节类型:引擎那两个触发点写在 ``_advance`` 的类型分发之前。
|
||
TRIGGER_ACTIVITY_TYPES = {
|
||
TRIGGER_ARRIVE: None,
|
||
TRIGGER_LEAVE: None,
|
||
# 「退回」只在有人工待办的环节上;开始环节没有上游可退,画到开始环节那条线是「退回修改」
|
||
# **到达**开始环节,不是从开始环节退回,所以它只有 recall、没有 goBack。
|
||
TRIGGER_GOBACK: ("manual",),
|
||
# 撤回收的是「本人那条已办」,发起环节提交出去的那一条同样撤得动(发起人撤回自己的提交)。
|
||
TRIGGER_RECALL: ("manual", "begin"),
|
||
}
|
||
#: 这两个时刻还要求环节上真有那颗按钮:开关关掉之后配在这里,就又是一条"配得挺对、永不发作"
|
||
TRIGGER_ACTIVITY_FLAGS = {
|
||
TRIGGER_GOBACK: ("allowGoBack", "退回"),
|
||
TRIGGER_RECALL: ("allowRecall", "撤回"),
|
||
}
|
||
#: 「本环节被退回时」再按**退回到哪一环**筛一次(规则块上的 ``goBackTo``)。没写这一格 =
|
||
#: 任何退回都发,存量配置零迁移。三种令牌混着勾:两个语义档 + 指定环节 id,任一命中即发。
|
||
#: 口径见 ``docs/goback-target-writeback-design.md`` §3——判定只认引擎算出来的那个落点
|
||
#: (``go_back`` 里 ``_resolve_goback_target`` 的结果),既不看画布上那条线的终点,
|
||
#: 也不看待办下拉里人挑的那一项。
|
||
MOUNT_GOBACK_KEYS = ("goBackTo", "go_back_to")
|
||
GOBACK_STARTER = "@starter"
|
||
GOBACK_PREV = "@prev"
|
||
#: 语义档之外的取值都是环节 id
|
||
GOBACK_TOKENS = (GOBACK_STARTER, GOBACK_PREV)
|
||
#: 两个语义档的中文说法(面板与体检文案共用;指定环节那一项念环节自己的名字)
|
||
GOBACK_TOKEN_LABELS = {GOBACK_STARTER: "退回给发起人", GOBACK_PREV: "退回到上一环节"}
|
||
#: 「退回到哪一环才发」之外还要问一句**这一退是谁按的**:第三方调接口退回来那一单,
|
||
#: 与审批人在待办页点退回那一单,对面要的处理常常不一样(前者多半根本不该再回发一遍)。
|
||
#: 取值就是引擎与外部审批那四个 ``VIA_*``(``service/node_approve.py`` 同一份),不另立词表:
|
||
#: ``oa`` 待办页那颗按钮、``oa_confirm`` 外部表了态人在 OA 横幅上点头、
|
||
#: ``open`` 第三方直接调 ``/open/*``、``embed`` 嵌入页 decide 与引擎替父单点的子流程。
|
||
#: 没写这一格 = 谁按的都发,存量配置零迁移。
|
||
MOUNT_GOBACK_VIA_KEYS = ("goBackVia", "go_back_via")
|
||
GOBACK_VIA_OA = "oa"
|
||
GOBACK_VIA_OA_CONFIRM = "oa_confirm"
|
||
GOBACK_VIA_OPEN = "open"
|
||
GOBACK_VIA_EMBED = "embed"
|
||
GOBACK_VIAS = (GOBACK_VIA_OA, GOBACK_VIA_OA_CONFIRM, GOBACK_VIA_OPEN, GOBACK_VIA_EMBED)
|
||
#: 外部那两条通道:面板上「只发外部按的」那一键用它,判定本身不看这一档
|
||
GOBACK_VIA_EXTERNAL = (GOBACK_VIA_OPEN, GOBACK_VIA_EMBED)
|
||
#: 面板与体检文案(带着动作,退回那一念得通)
|
||
GOBACK_VIA_LABELS = {
|
||
GOBACK_VIA_OA: "OA 里点的退回",
|
||
GOBACK_VIA_OA_CONFIRM: "外部表态、OA 里确认",
|
||
GOBACK_VIA_OPEN: "第三方调开放接口退回",
|
||
GOBACK_VIA_EMBED: "嵌入页 / 子流程退回",
|
||
}
|
||
#: 报文里 ``{action.via_name}`` 用这一份中性说法:通过后与到达那一刻也用它,那里没有
|
||
#: "退回"这个动作,念成「OA 界面 / 第三方开放接口」才对。
|
||
GOBACK_VIA_SHORT_LABELS = {
|
||
GOBACK_VIA_OA: "OA 界面",
|
||
GOBACK_VIA_OA_CONFIRM: "外部表态、OA 里确认",
|
||
GOBACK_VIA_OPEN: "第三方开放接口",
|
||
GOBACK_VIA_EMBED: "嵌入页 / 子流程",
|
||
}
|
||
#: 手写配置与导出件里的别名叫到正式值上(键一律小写)。外部那一路的叫法最多,认下来比
|
||
#: 让人重勾一次便宜;认不下来的原样留着,由 :func:`mount_problems` 点名。
|
||
GOBACK_VIA_ALIASES = {
|
||
"oa": GOBACK_VIA_OA,
|
||
"oa_confirm": GOBACK_VIA_OA_CONFIRM, "confirm": GOBACK_VIA_OA_CONFIRM,
|
||
"open": GOBACK_VIA_OPEN, "openapi": GOBACK_VIA_OPEN, "api": GOBACK_VIA_OPEN,
|
||
"third": GOBACK_VIA_OPEN, "thirdparty": GOBACK_VIA_OPEN, "external": GOBACK_VIA_OPEN,
|
||
"embed": GOBACK_VIA_EMBED, "embedded": GOBACK_VIA_EMBED, "subprocess": GOBACK_VIA_EMBED,
|
||
}
|
||
#: 没填幂等键模板时用的这一份
|
||
DEFAULT_IDEM_RULE = "{source}:{code}:{job}:{event}:{event_key}:{revision}"
|
||
#: ``{auto:x}`` 认识的自动变量:与表单"自动带出"共用一份,配置期就挡住写错的名字
|
||
AUTO_KINDS = autofill.ALL_KEYS
|
||
#: ``{work.x}`` 允许取的单据字段。**白名单**:报文是出域数据,``work.data``、``work.tokens``
|
||
#: 这类内部状态和 ``creator_identity`` 这串登录账号不该被顺手发出去;对接方要的工号
|
||
#: 显式写 ``{auto:creatorAccount}``,别拿白名单里的展示字段凑。
|
||
WORK_FIELDS = (
|
||
"id", "job", "serial", "title", "status", "process_name", "process_alias",
|
||
"category_name", "creator_person", "creator_identity_name", "creator_unit_name",
|
||
"activity_name", "current_activity_names", "start_time", "finish_time", "duration",
|
||
)
|
||
#: ``{activity.x}`` 允许取的环节字段:**触发这条报文的那一环**——环节挂载点名的那一环,
|
||
#: 或老写法里模板自己声明「到达某环节」指着的那一环。它就是 ``oa_outbound_message.event_key``
|
||
#: 里那个值,也是幂等键里的 ``{event_key}``:报文里告诉对方"该按哪一环的钮"与幂等键认的环节
|
||
#: 必须是同一个,两处各取一份迟早会漂。三条终态(办结 / 终止 / 作废)不挂环节,那一刻取到空串。
|
||
#: 环节 id 只在所属流程内有意义,复制流程、导到别的环境都会换掉它——所以它只能由系统在这一刻
|
||
#: 填给对方,谁都不该抄下来长期存着(``docs/node-writeback-config.md`` §9)。
|
||
ACTIVITY_FIELDS = ("id", "name", "alias", "type")
|
||
#: ``{action.x}`` 取的是**触发这条报文的那一颗按钮**:哪个时刻、按钮叫什么、这条线的决定语义、
|
||
#: 以及人按下去时填的意见。有了它,「同意 / 退回 / 撤回共用一份映射、只有状态值不同」这一类
|
||
#: 写回就是一条挂载勾三个时刻 + 一行 ``dictMap``,不必复制三份模板;「同意才发、拒绝不发」
|
||
#: 也不用另立编码。三条终态不挂环节、也没有按钮,那一刻整组渲染成空串(与 ``{activity.x}``
|
||
#: 同一条口径)。
|
||
#: 「被退回时」还多给三个落点取值:退到了哪一环(id / 名字 / 别名)。「退到发起人才发那条、
|
||
#: 退到上一环发另一条」的分流靠规则上的 ``goBackTo`` 筛,不必为了区分落点复制模板;
|
||
#: 要在报文里写明退到哪儿了,就取这三格。别的时刻没有落点,渲染空串。
|
||
#: 四个时刻都还多给一格**来源**:``{action.via}`` / ``{action.via_name}`` 说的是把单子送到
|
||
#: 这一刻的那一下是谁按的(OA 界面 / 外部表态后在 OA 确认 / 第三方开放接口 / 嵌入页与子流程)。
|
||
#: 第三方自己退回来的那一单不想再回发一条回声,用规则上的 ``goBackVia`` 筛掉;要在报文里按来源
|
||
#: 给不同的值(OA 退的叫 R、第三方退的叫 X),直接取这两格,不必复制模板。
|
||
ACTION_FIELDS = ("phase", "phase_name", "route", "route_alias", "decision", "opinion",
|
||
"target", "target_name", "target_alias", "via", "via_name")
|
||
#: 目标路径允许的字符:点分路径,数组下标写 ``lines[0].x`` 也认
|
||
TO_PATH = re.compile(r"^[A-Za-z0-9_\u4e00-\u9fa5]+(?:[.\[][A-Za-z0-9_\u4e00-\u9fa5\]]+)*$")
|
||
#: ``{auto:...}`` 里的日期格式沿用额度那一份,别在这里另立一套
|
||
|
||
|
||
def _field_key(raw: str) -> str:
|
||
"""把 ``form.x`` / ``x`` / ``x:urls`` 统一收成字段名 ``x``。
|
||
|
||
配置里前缀写法不统一(``{form.x}`` 与 ``{form:x}`` 都收,与 ``quota.FORM_REF`` 一致),
|
||
而 ``attach`` 与 ``default`` 这类写法后面还跟着参数,用冒号隔开——取字段名时都要切掉。
|
||
"""
|
||
text = str(raw or "").strip()
|
||
head = KIND_HEAD.match(text)
|
||
if head and head.group(1) == "form":
|
||
text = head.group(2).strip()
|
||
return text.partition(":")[0].strip()
|
||
|
||
|
||
class RenderError(ValueError):
|
||
"""渲染不下去了。入队阶段宁可抛出来也别发半份报文出去。"""
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 单个取值
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
def _attach_value(value: object, mode: str) -> list[str]:
|
||
"""附件格子 -> 上游能用的形式。
|
||
|
||
表单里那一格存的可能是 id 列表,也可能是带名字的对象列表(前端上传后回显用),
|
||
两种都见过,这里都认。``urls`` 给的是**站内相对路径**:出域报文里塞一个内网绝对地址
|
||
既没用也不安全,上游要下载应该由它自己的账号来取。
|
||
"""
|
||
rows = value if isinstance(value, list) else ([value] if value else [])
|
||
out: list[str] = []
|
||
for item in rows:
|
||
if isinstance(item, dict):
|
||
ident = str(item.get("id") or item.get("attachmentId") or "")
|
||
name = str(item.get("name") or item.get("fileName") or "")
|
||
else:
|
||
ident, name = str(item or ""), ""
|
||
if mode == "names":
|
||
out.append(name or ident)
|
||
elif mode == "urls":
|
||
out.append(f"/api/v1/attachment/{ident}/download" if ident else "")
|
||
else:
|
||
out.append(ident)
|
||
return [item for item in out if item]
|
||
|
||
|
||
def _transform(name: str, rest: str, ctx: "Ctx") -> Any:
|
||
"""``{cents:form.amount}`` 这类转换写法:函数名后面先是一段取值写法,再往后可带参数。"""
|
||
head, _, tail = rest.partition(":")
|
||
value = ctx.value_of(head) if head else ""
|
||
if name == "cents":
|
||
return to_cents(value)
|
||
if name == "yuan":
|
||
cents = to_cents(value)
|
||
return None if cents is None else round(cents / 100, 2)
|
||
if name == "date":
|
||
fmt = tail or "YYYY-MM-DD"
|
||
if fmt not in DATE_FORMATS:
|
||
raise RenderError(f"不支持的日期格式:{fmt}(可选 {'/'.join(DATE_FORMATS)})")
|
||
pattern = DATE_FORMATS[fmt]
|
||
if isinstance(value, datetime):
|
||
return value.strftime(pattern)
|
||
text = str(value or "").strip()
|
||
if not text:
|
||
return datetime.now().strftime(pattern)
|
||
# 上游常给 "2026-10-14 09:30:00" 这种带时间的串:先按常见形状切一下再说
|
||
for shape in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%dT%H:%M:%S", "%Y-%m-%d", "%Y/%m/%d"):
|
||
try:
|
||
return datetime.strptime(text[: len(shape) + 2].strip(), shape).strftime(pattern)
|
||
except ValueError:
|
||
continue
|
||
return text
|
||
if name == "trim":
|
||
return str(value or "").strip()
|
||
if name == "upper":
|
||
return str(value or "").upper()
|
||
if name == "default":
|
||
return tail if value in (None, "", [], {}) else value
|
||
if name == "join":
|
||
sep = tail or ","
|
||
items = value if isinstance(value, list) else ([] if value in (None, "") else [value])
|
||
return sep.join(str(item) for item in items)
|
||
if name == "account":
|
||
# 选人控件给的是身份 DN(多选还是个数组),SQL 与上游要的是登录账号:
|
||
# 翻译放在平台这一层,配表单的人只管点那一格,不用知道 DN 长什么样
|
||
return org.person_account(ctx.db, value)
|
||
if name == "bool":
|
||
truthy = tail or "true"
|
||
on = value not in (None, "", False, 0, "0", "false", "否")
|
||
return truthy if on else ("" if not tail else None)
|
||
raise RenderError(f"不认识的转换函数:{name}(一期只有 {'/'.join(TRANSFORMS)})")
|
||
|
||
|
||
class Ctx:
|
||
"""一次渲染的上下文:单据数据 + 单据行 + 当前明细行(在 ``each`` 里面时才有)。"""
|
||
|
||
def __init__(self, db: Session, *, data: dict | None, work=None, actor=None,
|
||
activity=None, row: dict | None = None, action: dict | None = None,
|
||
cache: dicts.DictCache | None = None) -> None:
|
||
self.db = db
|
||
self.data = dict(data or {})
|
||
self.work = work
|
||
self.actor = actor
|
||
#: 触发这条报文的环节行;终态那一刻与手工填数据的预览都没有,``{activity.x}`` 取空串
|
||
self.activity = activity
|
||
#: 触发这条报文的那一颗按钮(时刻 / 按钮名 / 决定语义 / 意见);终态与预览同样没有,
|
||
#: ``{action.x}`` 取空串。入队那一刻存进报文行,重渲染与人工重推都照这一份回放。
|
||
self.action = dict(action or {})
|
||
self.row = row
|
||
self.cache = cache or dicts.DictCache(db)
|
||
|
||
def child(self, row: dict) -> "Ctx":
|
||
return Ctx(self.db, data=self.data, work=self.work, actor=self.actor,
|
||
activity=self.activity, row=row, action=self.action, cache=self.cache)
|
||
|
||
def value_of(self, token: str) -> Any:
|
||
"""解析一个 ``{...}`` 里面的内容(不含花括号)。
|
||
|
||
``{form.x}`` 与 ``{form:x}`` 两种写法都认——额度、外部取数、条件联动那边都是
|
||
两种一起收的(``quota.FORM_REF`` 就是这么写的),这里只认一种会让人反复踩。
|
||
"""
|
||
text = str(token or "").strip()
|
||
head = KIND_HEAD.match(text)
|
||
if not head:
|
||
return text # 没认出前缀:整串当字面量,少一种报错少一种坑
|
||
kind, rest = head.group(1), head.group(2)
|
||
if kind in TRANSFORMS:
|
||
return _transform(kind, rest, self)
|
||
if kind == "form":
|
||
return self.data.get(_field_key(rest))
|
||
if kind == "item":
|
||
key, _, mode = rest.partition(":")
|
||
value = (self.row or {}).get(key.strip())
|
||
return _attach_value(value, mode.strip()) if mode.strip() in ("ids", "names", "urls") else value
|
||
if kind == "work":
|
||
attr = rest.strip()
|
||
if attr not in WORK_FIELDS:
|
||
raise RenderError(f"单据上没有 {{work.{attr}}} 这个值,可取的字段:{'/'.join(WORK_FIELDS)}")
|
||
value = getattr(self.work, attr, "") if self.work is not None else ""
|
||
return value.strftime("%Y-%m-%d %H:%M:%S") if isinstance(value, datetime) else value
|
||
if kind == "activity":
|
||
attr = rest.strip()
|
||
if attr not in ACTIVITY_FIELDS:
|
||
raise RenderError(f"环节上没有 {{activity.{attr}}} 这个值,可取的字段:{'/'.join(ACTIVITY_FIELDS)}")
|
||
return str(getattr(self.activity, attr, "") or "") if self.activity is not None else ""
|
||
if kind == "action":
|
||
attr = rest.strip()
|
||
if attr not in ACTION_FIELDS:
|
||
raise RenderError(f"按钮上没有 {{action.{attr}}} 这个值,可取的字段:{'/'.join(ACTION_FIELDS)}")
|
||
return str(self.action.get(attr, "") or "")
|
||
if kind == "const":
|
||
# 与取数那一路同一个口径(:func:`binding.const_literal`):``{const:1}`` 给数字 1。
|
||
# 这一层原来给的是字符串 ``"1"``,于是同一条写法在数据源测试里是 1、在写回报文里是
|
||
# "1"——上游那个 Go 服务对 ``*bool`` 字段只接 0/1/true/false,实测直接 400。
|
||
# 混着文字写("共 {const:1} 项")照旧拼成字符串,那条路本来就是拼话。
|
||
return binding.const_literal(rest)
|
||
if kind == "attach":
|
||
key, _, mode = rest.partition(":")
|
||
return _attach_value(self.data.get(_field_key(key)), (mode or "ids").strip())
|
||
if kind == "auto":
|
||
name, _, fmt = rest.partition(":")
|
||
if name.strip() in ("today", "now") and fmt.strip() in DATE_FORMATS:
|
||
return datetime.now().strftime(DATE_FORMATS[fmt.strip()])
|
||
return quota.resolve_text(self.db, "{auto:%s}" % rest, self.data, work=self.work, actor=self.actor)
|
||
return text
|
||
|
||
def render(self, expr: object) -> Any:
|
||
"""渲染一个配置值:整段是一个引用时给原类型,混着文字时给拼好的字符串。"""
|
||
text = "" if expr is None else str(expr)
|
||
whole = TOKEN_ALL.match(text.strip())
|
||
if whole:
|
||
return self.value_of(whole.group(1))
|
||
if "{" not in text:
|
||
return text
|
||
return TOKEN_ANY.sub(lambda match: "" if self.value_of(match.group(1)) is None
|
||
else str(self.value_of(match.group(1))), text)
|
||
|
||
def dict_map(self, code: str, pick: str, value: Any) -> Any:
|
||
"""枚举翻译:字典项的附加值里取 ``pick`` 那个键。运营改字典即生效,不用发版。"""
|
||
# 表单里那一格存的不一定是编码(它可以配成存名称或附加值),先认编码再扫一遍
|
||
item = dicts.find_item(self.cache.index(code), str(value))
|
||
if item is None:
|
||
raise RenderError(f"字典 {code} 里没有值「{value}」这一项,翻译不出来")
|
||
extra = item.get("extra") or {}
|
||
if pick:
|
||
if pick not in extra:
|
||
raise RenderError(f"字典 {code} 的「{value}」项没有附加值 {pick}")
|
||
return extra[pick]
|
||
return item.get("label") or value
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 报文渲染
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
def _assign(body: dict, path: str, value: Any) -> None:
|
||
"""按点路径往 body 里写值:``header.companyCode`` 写出的是嵌套对象。"""
|
||
parts = [part for part in re.split(r"\.", str(path).strip()) if part]
|
||
if not parts:
|
||
raise RenderError("映射行没写目标字段(to)")
|
||
node: Any = body
|
||
for index, part in enumerate(parts):
|
||
last = index == len(parts) - 1
|
||
key: Any = part[:-1] if part.endswith("]") and "[" in part else part
|
||
bracket = re.search(r"\[(\d+)\]$", part)
|
||
if bracket:
|
||
index_no = int(bracket.group(1))
|
||
holder = node.setdefault(key, []) if isinstance(node, dict) else None
|
||
if holder is None:
|
||
raise RenderError(f"目标路径 {path} 上 {key} 不是数组,写不进去")
|
||
while len(holder) <= index_no:
|
||
holder.append({})
|
||
if last:
|
||
holder[index_no] = value
|
||
node = holder[index_no]
|
||
continue
|
||
if not isinstance(node, dict):
|
||
raise RenderError(f"目标路径 {path} 走到 {part} 时前面不是对象")
|
||
if last:
|
||
node[key] = value
|
||
else:
|
||
node = node.setdefault(key, {})
|
||
|
||
|
||
def render_template(db: Session, template: dict, *, data: dict, work=None, actor=None,
|
||
activity=None, only_fields: Iterable[str] | None = None,
|
||
action: dict | None = None) -> dict:
|
||
"""按模板渲染出发送的 JSON body。
|
||
|
||
模板形状(``Integration.payload``)::
|
||
|
||
{ "method": "POST", "path": "/api/voucher/create",
|
||
"fields": [
|
||
{ "to": "header.sourceNo", "from": "{work.serial}" },
|
||
{ "to": "header.amount", "from": "{cents:form.applyAmount}" },
|
||
{ "to": "header.dept", "from": "{form.costCenter}",
|
||
"when": { "rules": [{ "field": "applyAmount", "op": "gt", "value": 1000 }] } },
|
||
{ "to": "lines", "each": "{form.expenses}", "map": {
|
||
"subject": { "from": "{item.expenseType}", "dictMap": "erp_subject_map", "pick": "subject" },
|
||
"amount": { "from": "{cents:item.amount}" } } } ] }
|
||
|
||
``only_fields`` 是环节挂载上勾的「要发的字段」(映射行的 ``to`` 清单):名单外的行直接
|
||
跳过;空 = 整份模板(没勾就是整份发,见 ``docs/node-writeback-config.md`` §2)。
|
||
|
||
``activity`` 是触发这条报文的那一环(环节挂载点名的那一环),只用来喂 ``{activity.x}``;
|
||
终态那一刻没有环节,不传就是取空串。``action`` 同理,是触发它的那颗按钮,喂 ``{action.x}``。
|
||
"""
|
||
if not isinstance(template, dict):
|
||
raise RenderError("映射配置不是一段对象")
|
||
ctx = Ctx(db, data=data, work=work, actor=actor, activity=activity, action=action)
|
||
only = {str(name or "").strip() for name in (only_fields or [])}
|
||
body: dict[str, Any] = {}
|
||
for item in template.get("fields") or []:
|
||
if not isinstance(item, dict):
|
||
raise RenderError(f"映射行格式不对:{item!r}")
|
||
to = str(item.get("to") or "").strip()
|
||
if not to:
|
||
raise RenderError("映射行没写目标字段(to)")
|
||
if only and to not in only:
|
||
continue # 环节上勾了「只发这几个」,这一行不在名单里
|
||
if item.get("when") and not dicts.condition_ok(item["when"], ctx.data):
|
||
continue
|
||
if item.get("each"):
|
||
rows = ctx.render(item["each"])
|
||
if not isinstance(rows, list):
|
||
raise RenderError(f"{to} 配了逐行映射,但 {item['each']} 取回来的不是明细表")
|
||
lines = []
|
||
for row in rows:
|
||
if not isinstance(row, dict):
|
||
continue
|
||
one: dict[str, Any] = {}
|
||
for name, cell in (item.get("map") or {}).items():
|
||
one[name] = _render_cell(ctx.child(row), cell, at=f"{to}.{name}")
|
||
lines.append(one)
|
||
_assign(body, to, lines)
|
||
continue
|
||
_assign(body, to, _render_cell(ctx, item, at=to))
|
||
transform = str(template.get("transform") or "").strip()
|
||
if transform:
|
||
return _run_transform(transform, body)
|
||
return body
|
||
|
||
|
||
def _render_cell(ctx: Ctx, cell: object, *, at: str) -> Any:
|
||
"""渲染一行映射(或 ``each.map`` 里的一格)。"""
|
||
if not isinstance(cell, dict):
|
||
return ctx.render(cell)
|
||
if cell.get("when") and not dicts.condition_ok(cell["when"], ctx.row if ctx.row is not None else ctx.data):
|
||
return None
|
||
value = ctx.render(cell.get("from"))
|
||
code = str(cell.get("dictMap") or "").strip()
|
||
if code:
|
||
value = ctx.dict_map(code, str(cell.get("pick") or "").strip(), value)
|
||
script = str(cell.get("transform") or "").strip()
|
||
if script:
|
||
value = _run_cell_script(script, value, ctx)
|
||
fallback = cell.get("default", None)
|
||
if value is None and fallback is not None:
|
||
value = ctx.render(fallback)
|
||
return value
|
||
|
||
|
||
def _run_cell_script(script: str, value: Any, ctx: Ctx) -> Any:
|
||
"""单格上的派生值脚本:沙箱里没有 ``__builtins__``,**取不到 IO**,只算值。
|
||
|
||
``expressions`` 的命名空间是把 ``data`` 的顶层键摊成裸名字给的(``amount > 5000`` 这种写法),
|
||
所以当前值与当前明细行走 ``data`` 里的 ``value`` / ``row`` 两个键进来,
|
||
脚本里直接写 ``round(value * 1.13, 2)`` 就行。表单里若真有一格叫 ``value``,
|
||
它在脚本里会被当前值盖住——这个取舍写在这里,配置页上也提示同一句话。
|
||
"""
|
||
from ..engine import expressions
|
||
|
||
scope = dict(ctx.data)
|
||
scope["value"] = value
|
||
scope["row"] = ctx.row or {}
|
||
try:
|
||
return expressions.evaluate(script, {"data": scope, "work": _work_view(ctx.work)})
|
||
except Exception as exc: # 沙箱里的错都是配置错,直接说清是哪一格
|
||
raise RenderError(f"派生值脚本没算出来:{exc}") from exc
|
||
|
||
|
||
def _run_transform(script: str, body: dict) -> dict:
|
||
"""整份报文级别的收尾脚本(补校验位、拼签名串这类)。同样只算值,不发请求。"""
|
||
from ..engine import expressions
|
||
|
||
try:
|
||
result = expressions.evaluate(script, {"data": {"body": body}, "work": {}})
|
||
except Exception as exc:
|
||
raise RenderError(f"报文级脚本没算出来:{exc}") from exc
|
||
return result if isinstance(result, dict) else body
|
||
|
||
|
||
def _work_view(work: Any) -> dict:
|
||
"""``work.`` 在脚本里是普通字典:沙箱拿不到 ORM 对象,也不该拿得到整行记录。"""
|
||
if work is None:
|
||
return {}
|
||
return {key: getattr(work, key, "") for key in ("id", "job", "serial", "title", "process",
|
||
"process_name", "creator", "creator_identity",
|
||
"creator_identity_name", "creator_unit",
|
||
"creator_unit_name")}
|
||
|
||
|
||
def url_for(row: models.DataSource, path: str) -> str:
|
||
"""L1 的地址 + L2 的路径 = 真正打出去的 URL。
|
||
|
||
L1 只到「这个系统的入口」,具体调哪个接口归 L2:同一个 ERP 建凭证、查凭证共用一份
|
||
密钥与超时,不该为了换接口去改 L1。
|
||
"""
|
||
base = str(row.url or "").strip()
|
||
tail = str(path or "").strip()
|
||
if not tail:
|
||
return base
|
||
if tail.startswith("http://") or tail.startswith("https://"):
|
||
return tail
|
||
if not base:
|
||
raise RenderError("数据源没配接口地址,拼不出要发往哪里")
|
||
return f"{base.rstrip('/')}/{tail.lstrip('/')}"
|
||
|
||
|
||
def render_for(db: Session, row: models.DataSource, integration: models.Integration,
|
||
*, data: dict, work=None, actor=None, activity=None,
|
||
only_fields: list[str] | None = None,
|
||
action: dict | None = None) -> tuple[str, str, dict]:
|
||
"""渲染一条待发消息:回 ``(method, url, body)``。``only_fields`` 见 :func:`render_template`。"""
|
||
template = dict(integration.payload or {})
|
||
return (
|
||
str(template.get("method") or row.method or "POST").upper(),
|
||
url_for(row, str(template.get("path") or "")),
|
||
render_template(db, template, data=data, work=work, actor=actor,
|
||
activity=activity, only_fields=only_fields, action=action),
|
||
)
|
||
|
||
|
||
def idem_key(integration: models.Integration, *, source: str, job: str, serial: str,
|
||
work_id: str, event: str, event_key: str, revision: int,
|
||
phase: str = "", target: str = "", via: str = "") -> str:
|
||
"""幂等键:默认 ``{source}:{code}:{job}:{event}:{event_key}:{revision}``,随 ``X-Idempotency-Key`` 发出。
|
||
|
||
上游支持幂等时它是"重发也不会多一张凭证"的凭据;上游不支持时,至少本地
|
||
``uk_ob_idem`` 唯一键挡得住重复入队。键里必须有 ``{code}``:一张单挂两个模板时,
|
||
少了它就只剩第一条。
|
||
|
||
``phase`` 是环节那一刻的触发时刻。默认规则里**只有**「退回」与「撤回」会往 ``{event}``
|
||
那一段后面补一小截 ``:goBack`` / ``:recall``,于是同一份模板挂在「通过后」+「退回」
|
||
两个时刻各是一条报文;``arrive`` / ``leave`` 那一段留空,存量报文的键与升级前的形状
|
||
完全一致(否则老单子在升级后重走一次就会平白多一发)。自定义幂等键要自己分时刻,
|
||
显式写 ``{phase}``(``IDEM_VARS`` 里已给出)。
|
||
|
||
``target`` 是「被退回时」那一刻退落到的那一环。默认规则里**不用**它:一张单被退两次
|
||
(哪怕退到不同环节)仍旧只发一条,对面按单号幂等更新的写回不会被同一个状态打两遍。
|
||
要"退到 A 一条、退到 B 再一条",就在这条模板的自定义幂等键里写 ``{target}``;
|
||
和任何取值一样,加进键里就是换了键,历史报文不再算重复(``docs/goback-target-writeback-design.md`` §6)。
|
||
|
||
``via`` 是这一次表态走的哪条通道(``oa`` / ``oa_confirm`` / ``open`` / ``embed``)。默认规则里
|
||
同样**不用**它:第三方自己退回来的那一单,默认仍旧照规则发一条出去;要按来源各发一条,
|
||
就在这条模板的自定义幂等键里写 ``{via}``。只有"同一份模板既给 OA 用又给外部用、对面认的
|
||
是两个状态"的流程才需要它,别默认就带上——那等于让一张单被同一件事打两遍。
|
||
"""
|
||
values = {
|
||
"source": source, "code": integration.code, "job": job, "serial": serial,
|
||
"work": work_id, "event": event, "event_key": event_key, "revision": str(revision),
|
||
"phase": phase, "target": target, "via": via,
|
||
"today": datetime.now().strftime("%Y-%m-%d"),
|
||
}
|
||
if phase in PHASE_KEY_TRIGGERS:
|
||
values["event"] = f"{event}:{phase}"
|
||
rule = str(integration.idem_rule or "").strip() or DEFAULT_IDEM_RULE
|
||
out = TOKEN_ANY.sub(lambda match: str(values.get(match.group(1), "")), rule)
|
||
return out[:191]
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 设计期校验:配错别让它存进来
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
def form_refs_of(template: object) -> list[str]:
|
||
"""模板里引用了哪些表单字段(``{form.x}`` 与 ``{attach:form.x}``)。"""
|
||
found: list[str] = []
|
||
stack: list[object] = [template]
|
||
while stack:
|
||
node = stack.pop()
|
||
if isinstance(node, dict):
|
||
stack.extend(node.values())
|
||
elif isinstance(node, list):
|
||
stack.extend(node)
|
||
elif isinstance(node, str):
|
||
for match in TOKEN_ANY.finditer(node):
|
||
head = KIND_HEAD.match(match.group(1).strip())
|
||
if not head:
|
||
continue
|
||
kind, rest = head.group(1), head.group(2)
|
||
if kind in TRANSFORMS:
|
||
# 转换函数里面还套着一段取值写法:拆出来再走一遍同一把尺子
|
||
stack.append("{%s}" % rest)
|
||
continue
|
||
if kind in ("form", "attach"):
|
||
key = _field_key(rest)
|
||
if key and key not in found:
|
||
found.append(key)
|
||
return found
|
||
|
||
|
||
#: 只在渲染这一刻存在的那几个键的前缀。送审那一路要带批次号、修订号、附件清单与
|
||
#: 一次性清单入口(``service/external_check.CHECK_KEYS`` 那六个 ``_check*``),它们既不是
|
||
#: 表单字段也不该进 ``work.data``——落进单据等于给集成配几个没人看的隐藏格,还会跟着
|
||
#: 导出、打印、条件分支一起跑。所以设计期校验不能拿"字段在表单上不存在"量它们:
|
||
#: 模板一绑表单就存不进去,方案里写明的写法反倒成了错的。
|
||
#: 这个前缀约定由 ``scripts/check_invoice_check.py`` 对着 ``CHECK_KEYS`` 钉住。
|
||
SYNTHETIC_PREFIX = "_"
|
||
|
||
|
||
def real_form_refs(refs: Iterable[str]) -> list[str]:
|
||
"""去掉合成键,只剩"真的该在表单上"的那几个字段名。"""
|
||
return [key for key in refs if not str(key).startswith(SYNTHETIC_PREFIX)]
|
||
|
||
|
||
#: 环节挂载里「失败策略」与「补救路线」两格的两种拼写。设计器写进 ``config.writeback``
|
||
#: 的是驼峰(和环节配置里 ``taskValues`` / ``ccRules`` / ``routeDecisions`` 一个习惯),
|
||
#: 手工拼的 JSON 与导出件习惯用下划线。两种都认:三边各自都写对、合起来什么都不发生,
|
||
#: 是这一层最难查的一种错法(``on_failure`` 曾经就是这么静默失效的)。
|
||
MOUNT_FAILURE_KEYS = ("onFailure", "on_failure")
|
||
MOUNT_ROUTE_KEYS = ("failRoute", "fail_route")
|
||
|
||
|
||
def clean_condition(value: object) -> dict:
|
||
"""把界面上那份结构化条件收成能落库的形状:没写出有效规则就落空 dict(= 每张单都发)。
|
||
|
||
留一条没有 field 的规则在下面跑,等于配了一条永远为真的条件还自称"只发一部分",
|
||
所以这一格在落库前就把这种空壳清掉,让它老老实实回到"没配"这一档。
|
||
"""
|
||
if isinstance(value, list):
|
||
value = {"rules": value}
|
||
if not isinstance(value, dict):
|
||
return {}
|
||
rules = [item for item in (value.get("rules") or [])
|
||
if isinstance(item, dict) and str(item.get("field") or "").strip()]
|
||
if not rules:
|
||
return {}
|
||
out = dict(value)
|
||
out["rules"] = rules
|
||
return out
|
||
|
||
|
||
def mount_entries(mount: dict) -> list[tuple[str, dict]]:
|
||
"""挂载点名的模板:``(模板编码, 这一格自己的条件)``,顺序就是这一环节里的发送顺序。
|
||
|
||
两种写法都认,老配置一行都不用改:
|
||
|
||
- ``["erp_x", "fund_y"]``:只点名,不单独加条件;
|
||
- ``[{"code": "erp_x", "when": {...}}, "fund_y"]``:要在**这个环节**按字段值分流时用
|
||
——同一张报销单挂两个模板,各带一条互斥的条件,对公进 ERP、现金进资金系统。
|
||
|
||
这一格的条件只管"这个环节的这个模板";模板自己那份「哪些单才发」跟着模板走、
|
||
挂载上那条 ``when`` 管整批,三道各自独立,都过才发(``docs/node-writeback-config.md`` §4)。
|
||
"""
|
||
out: list[tuple[str, dict]] = []
|
||
seen: set[str] = set()
|
||
for item in (mount.get("integrations") or []):
|
||
if isinstance(item, dict):
|
||
code = str(item.get("code") or "").strip()
|
||
condition = clean_condition(item.get("when") or item.get("condition"))
|
||
else:
|
||
code = str(item or "").strip()
|
||
condition = {}
|
||
if not code or code in seen:
|
||
continue
|
||
seen.add(code)
|
||
out.append((code, condition))
|
||
return out
|
||
|
||
|
||
def mount_blocks(mount: dict) -> list[dict]:
|
||
"""把一个环节的挂载读成**一组规则**,每块各有自己的时机、模板与条件。
|
||
|
||
一个环节可以有多条写回规则,例如「到达本环节时通知 A 系统」+「本环节审批通过后按
|
||
结算方式分流给 B / C 系统」,两条互不干扰。只有一条规则时还是老的单块写法(整段就是
|
||
一块),所以存量配置一行都不用改,导出的流程 JSON 也不会因为这次改动整体换形状。
|
||
|
||
``{"blocks": [...]}`` 是新写法;``blocks`` 缺省或为空 = 整段就是一块(老写法)。
|
||
"""
|
||
blocks = mount.get("blocks")
|
||
if isinstance(blocks, list):
|
||
picked = [block for block in blocks if isinstance(block, dict)]
|
||
if picked:
|
||
return picked
|
||
return [mount]
|
||
|
||
|
||
def mount_all_entries(mount: dict) -> list[tuple[str, dict]]:
|
||
"""跨块的全部 ``(编码, 条件)``:编码按首次出现去重,条件取它第一次出现那份。
|
||
|
||
给"这个模板被谁挂着"这类跨块查询用;真正决定发不发的是各块自己的那份
|
||
(见 :func:`mount_entries`)。
|
||
"""
|
||
out: list[tuple[str, dict]] = []
|
||
seen: set[str] = set()
|
||
for block in mount_blocks(mount):
|
||
for code, condition in mount_entries(block):
|
||
if code in seen:
|
||
continue
|
||
seen.add(code)
|
||
out.append((code, condition))
|
||
return out
|
||
|
||
|
||
def mount_codes(mount: dict) -> list[str]:
|
||
"""挂载点名的模板编码(跨块去重),顺序与首次出现顺序一致。"""
|
||
return [code for code, _ in mount_all_entries(mount)]
|
||
|
||
|
||
def mount_entry_conditions(mount: dict) -> dict[str, dict]:
|
||
"""``编码 -> 这一格的条件``;没配条件的编码不在里面。"""
|
||
return {code: condition for code, condition in mount_entries(mount) if condition}
|
||
|
||
|
||
def mount_entry_fields(block: dict) -> dict[str, list[str]]:
|
||
"""挂载里每个模板在这一格勾的「要发的字段」:``编码 -> [目标字段...]``。
|
||
|
||
只在对象写法(``{"code": ..., "fields": [...]}``)上有;没勾、勾成空、老写法纯编码
|
||
都不进这张表——没勾就是整份发。勾了全部目标字段和没勾等价,界面会写回成没勾那份。
|
||
"""
|
||
out: dict[str, list[str]] = {}
|
||
for item in (block.get("integrations") or []):
|
||
if not isinstance(item, dict):
|
||
continue
|
||
code = str(item.get("code") or "").strip()
|
||
raw = item.get("fields")
|
||
if not code or not isinstance(raw, list):
|
||
continue
|
||
wanted: list[str] = []
|
||
for name in raw:
|
||
text = str(name or "").strip()
|
||
if text and text not in wanted:
|
||
wanted.append(text)
|
||
if wanted:
|
||
out[code] = wanted
|
||
return out
|
||
|
||
|
||
def template_field_targets(template: object) -> list[str]:
|
||
"""一个模板能勾的「要发的字段」清单(映射行的 ``to``,按配置顺序去重)。
|
||
|
||
``template`` 收 ORM 行或导出件里的 dict——payload 两边同一份形状。
|
||
"""
|
||
payload = template.get("payload") if isinstance(template, dict) else getattr(template, "payload", None)
|
||
if not isinstance(payload, dict):
|
||
return []
|
||
out: list[str] = []
|
||
for row in payload.get("fields") or []:
|
||
to = str((row or {}).get("to") or "").strip() if isinstance(row, dict) else ""
|
||
if to and to not in out:
|
||
out.append(to)
|
||
return out
|
||
|
||
|
||
def mount_of(activity) -> dict:
|
||
"""环节配置里那一段写回挂载(L3)。没配就是空 dict,调用方都按"没挂"处理。"""
|
||
config = getattr(activity, "config", None)
|
||
mount = config.get("writeback") if isinstance(config, dict) else None
|
||
return mount if isinstance(mount, dict) else {}
|
||
|
||
|
||
def mount_value(mount: dict, keys: tuple[str, ...]) -> str:
|
||
"""按 keys 的顺序取第一个非空值:两种拼写共用一条读取口径。"""
|
||
for key in keys:
|
||
text = str(mount.get(key) or "").strip()
|
||
if text:
|
||
return text
|
||
return ""
|
||
|
||
|
||
#: 只有「到达」这一个时刻的环节、以及只有「往外走」这一个时刻的环节。
|
||
#: 提交单据等于「离开开始环节」,而结束/作废环节到了就地收尾,不会再往外走:
|
||
#: 触发时机配反的那条写回永远不发,而且不报错——必须在保存时就说破。
|
||
ONE_WAY_TRIGGER = {
|
||
"begin": ("arrive", "开始环节不会被「走到」,单据提交那一刻算「本环节审批通过后」(界面上写「提交单据时」)"),
|
||
"end": ("leave", "结束环节到了就收尾,不会再往外走"),
|
||
"cancel": ("leave", "作废环节到了就收尾,不会再往外走"),
|
||
}
|
||
#: 环节类型的中文说法,只喂提示文案。引擎那份 ``definition.ACTIVITY_TYPES`` 是判据,
|
||
#: 为了一句话去 import 它会把 service → engine → service 绕成环。
|
||
ACTIVITY_TYPE_LABELS = {
|
||
"begin": "发起", "manual": "审批", "choice": "条件分支", "parallel": "并发",
|
||
"merge": "聚合", "split": "拆分明细", "script": "脚本", "invoke": "接口调用",
|
||
"embed": "子流程", "delay": "定时", "end": "结束", "cancel": "作废",
|
||
}
|
||
#: 三条终态的中文名:提示里要说「办结那一刻」,写 completed 没人看得懂
|
||
TERMINAL_LABELS = {
|
||
models.Integration.EVENT_COMPLETED: "办结",
|
||
models.Integration.EVENT_TERMINATED: "终止",
|
||
models.Integration.EVENT_CANCELED: "作废",
|
||
}
|
||
#: 「什么时候发」这一格的两种拼写:接口与前端用驼峰,库里与导出件用下划线(与挂载那几种
|
||
#: 拼写同一个毛病,只留一处读法,别出现"界面存 triggerEvents、运行期读 trigger_event")
|
||
TRIGGER_LIST_KEYS = ("triggerEvents", "trigger_events")
|
||
|
||
|
||
def _event_field(integration: object, keys: tuple[str, ...]) -> object:
|
||
"""模板上的一格:dict(没保存的草稿)与 ORM 行都从这儿读,两种拼写都认。"""
|
||
for key in keys:
|
||
if isinstance(integration, dict):
|
||
value = integration.get(key)
|
||
else:
|
||
value = getattr(integration, key, None)
|
||
if value not in (None, "", []):
|
||
return value
|
||
return None
|
||
|
||
|
||
def terminal_events_of(integration: object) -> tuple[str, ...]:
|
||
"""这条模板会在哪几条终态那一刻自动发。这份读法是全项目唯一的一处。
|
||
|
||
新形状是 ``trigger_events`` 那份清单——办结 / 终止 / 作废可以多选,也可以一条都不勾;
|
||
清单为空就回落到老的那一格标量 ``trigger_event``,分寸与 :func:`mount_blocks`
|
||
「一条规则时平铺、多条才换形状」一致,存量配置与导出件一行都不用改。
|
||
|
||
``activity``(旧写法:模板自己点名一个环节)与 ``manual``(不自动发)都不是终态,
|
||
不进这份清单:前者归 L3 环节挂载,后者根本就是一个触发点都没有。
|
||
"""
|
||
raw = _event_field(integration, TRIGGER_LIST_KEYS)
|
||
out: list[str] = []
|
||
for item in (raw if isinstance(raw, list) else []):
|
||
event = str(item or "").strip()
|
||
if event in models.Integration.TERMINAL_EVENTS and event not in out:
|
||
out.append(event)
|
||
if out:
|
||
return tuple(out)
|
||
legacy = str(_event_field(integration, ("trigger_event", "triggerEvent")) or "").strip()
|
||
return (legacy,) if legacy in models.Integration.TERMINAL_EVENTS else ()
|
||
|
||
|
||
def normalize_terminal_events(value: object) -> list[str]:
|
||
"""界面传来的「什么时候发」清单:去掉重复与不认识的取值,按办结 / 终止 / 作废排。
|
||
|
||
不认识的取值不在这里报错(``problems`` 会点名),这里只保证落库的东西是干净的。
|
||
"""
|
||
if isinstance(value, str):
|
||
value = [value]
|
||
picked = {str(item or "").strip() for item in (value or []) if str(item or "").strip()}
|
||
return [event for event in models.Integration.TERMINAL_EVENTS if event in picked]
|
||
|
||
|
||
def declared_activity_of(integration: object) -> str:
|
||
"""旧写法点名的那个环节 id(``trigger_event=activity``)。新配置不再往这儿写。"""
|
||
event = str(_event_field(integration, ("trigger_event", "triggerEvent")) or "").strip()
|
||
if event != models.Integration.EVENT_ACTIVITY:
|
||
return ""
|
||
return str(_event_field(integration, ("event_key", "eventKey")) or "").strip()
|
||
|
||
|
||
def trigger_of(raw: object) -> str:
|
||
"""一个触发时刻的写法归一。认不得的**原样返回**,交给 :func:`mount_problems` 点名。"""
|
||
text = str(raw or "").strip()
|
||
if not text:
|
||
return TRIGGER_ARRIVE
|
||
return TRIGGER_ALIASES.get(text.lower().replace("-", "_"), text)
|
||
|
||
|
||
def mount_triggers(mount: dict) -> list[str]:
|
||
"""这一条挂载在**哪几个时刻**发。没写 ``trigger`` 的存量配置一律按「到达时」,口径不变。
|
||
|
||
一个时刻存字符串、几个时刻才存数组——与 :func:`mount_blocks`「一条规则平铺、多条才换
|
||
``blocks``」同一个习惯,存量配置与导出件零迁移。读法只有这一处:设计期校验、运行期入队、
|
||
接口回显三边都从这儿拿,不会再出现"界面存了 goBack、运行期只认 goback"。
|
||
"""
|
||
raw = mount.get("trigger")
|
||
items = list(raw) if isinstance(raw, (list, tuple, set)) else [raw]
|
||
out: list[str] = []
|
||
for item in items:
|
||
phase = trigger_of(item)
|
||
if phase not in out:
|
||
out.append(phase)
|
||
return out or [TRIGGER_ARRIVE]
|
||
|
||
|
||
def mount_trigger(mount: dict) -> str:
|
||
"""这一条挂载的第一个时刻。老调用方与接口那一格仍按一个时刻说话,从这里拿。"""
|
||
return mount_triggers(mount)[0]
|
||
|
||
|
||
def trigger_text(phases: Iterable[str]) -> str:
|
||
"""一组时刻的中文说法,给提示与体检文案用:``到达本环节时 / 本环节被退回时``。"""
|
||
return " / ".join(TRIGGER_LABELS.get(str(phase or "").strip(), str(phase or ""))
|
||
for phase in phases)
|
||
|
||
|
||
def mount_goback_raw(mount: dict) -> tuple[list[str], bool]:
|
||
"""落点筛子的原始读法:``(去重后的令牌, 这一格有没有被写过)``。
|
||
|
||
写了 ``[]`` 与干脆没写不是一回事——前者是"勾了却一个都没勾中",界面上看着像"都不发",
|
||
运行期却等于任何退回都发,保存时要点名(与"挂了条件却一条都没写等于每张单都发"同一条口径)。
|
||
"""
|
||
raw: object = None
|
||
written = False
|
||
for key in MOUNT_GOBACK_KEYS:
|
||
if key in mount:
|
||
written = True
|
||
if raw is None:
|
||
raw = mount.get(key)
|
||
items = list(raw) if isinstance(raw, (list, tuple, set)) else ([] if raw in (None, "") else [raw])
|
||
out: list[str] = []
|
||
for item in items:
|
||
text = str(item or "").strip()
|
||
if text and text not in out:
|
||
out.append(text)
|
||
return out, written
|
||
|
||
|
||
def mount_goback_to(mount: dict) -> list[str]:
|
||
"""这一块勾了「退回到哪些环节才发」的哪几档。空 = 任何退回都发。
|
||
|
||
认不得的令牌**原样留着**(多半是那个环节被删了或改过 id),交给 :func:`mount_problems`
|
||
点名——在这儿洗掉就等于把"这条写回其实一条都不会发"藏起来了。两种拼写都认,
|
||
与 ``onFailure`` 那一份读法同一习惯。
|
||
"""
|
||
return mount_goback_raw(mount)[0]
|
||
|
||
|
||
def goback_via_of(value: object) -> str:
|
||
"""把"这一退是谁按的"归成那四个正式值之一。认不出来原样回(小写去空格),由体检点名。"""
|
||
raw = str(value or "").strip().lower()
|
||
return GOBACK_VIA_ALIASES.get(raw, raw)
|
||
|
||
|
||
def mount_goback_via_raw(mount: dict) -> tuple[list[str], bool]:
|
||
"""来源筛子的原始读法:``(归一后的通道, 这一格有没有被写过)``。
|
||
|
||
写了 ``[]`` 与干脆没写不是一回事——与 :func:`mount_goback_raw` 同一条口径,界面上看着像
|
||
"都不发",运行期却等于谁按的都发,保存时要点名。认不得的写法原样留着,别洗掉。
|
||
"""
|
||
raw: object = None
|
||
written = False
|
||
for key in MOUNT_GOBACK_VIA_KEYS:
|
||
if key in mount:
|
||
written = True
|
||
if raw is None:
|
||
raw = mount.get(key)
|
||
items = list(raw) if isinstance(raw, (list, tuple, set)) else ([] if raw in (None, "") else [raw])
|
||
out: list[str] = []
|
||
for item in items:
|
||
text = str(item or "").strip()
|
||
if not text:
|
||
continue
|
||
value = goback_via_of(text)
|
||
if value not in out:
|
||
out.append(value)
|
||
return out, written
|
||
|
||
|
||
def mount_goback_via(mount: dict) -> list[str]:
|
||
"""这一块勾了「谁按的退回才发」的哪几条通道。空 = 谁按的都发。"""
|
||
return mount_goback_via_raw(mount)[0]
|
||
|
||
|
||
def goback_via_text(values: Iterable[str]) -> str:
|
||
"""勾中的通道说成一句人话:``第三方调开放接口退回 / 嵌入页 / 子流程退回``。"""
|
||
return " / ".join(GOBACK_VIA_LABELS.get(str(value or "").strip().lower(),
|
||
str(value or ""))
|
||
for value in values)
|
||
|
||
|
||
def goback_via_name(value: object) -> str:
|
||
"""报文里 ``{action.via_name}`` 那一句:认不得的通道就把原值写出去,别编一个说法。"""
|
||
raw = goback_via_of(value)
|
||
return GOBACK_VIA_SHORT_LABELS.get(raw, raw)
|
||
|
||
|
||
|
||
def goback_hit(block: dict, facts: dict | None) -> bool:
|
||
"""这一次退回**是谁按的**、**落到了哪一环**,命中这一块的筛子吗。两格都没勾 = 全都算命中。
|
||
|
||
两格是 AND:先过来源、再过落点,任一没过这一刻这条规则就当没存在过——不入队、不留报文、
|
||
不算失败。``facts`` 是引擎交下来的那一份事实:``via`` 这一退走的哪条通道、``target`` 落点
|
||
环节 id、``is_starter`` / ``is_prev`` 两个布尔(后者指"落点正好是候选清单第一个",也就是
|
||
人不挑时引擎自己选的那一个)。判据只在这一处,前端 ``utils/formWriteback.ts`` 镜像同一份。
|
||
|
||
缺什么就当那一格没筛:升级前入队的老报文重推时 ``action_data`` 里没有 ``via``,这时把
|
||
"只发第三方退回"那条判成不命中,等于让人工重推凭空少一条——宁可发出去。
|
||
"""
|
||
data = facts if isinstance(facts, dict) else {}
|
||
wanted = mount_goback_via(block)
|
||
if wanted:
|
||
via = goback_via_of(data.get("via"))
|
||
if via and via not in wanted:
|
||
return False
|
||
tokens = mount_goback_to(block)
|
||
if not tokens:
|
||
return True
|
||
target = str(data.get("target") or "")
|
||
for token in tokens:
|
||
if token == GOBACK_STARTER:
|
||
if bool(data.get("is_starter")):
|
||
return True
|
||
elif token == GOBACK_PREV:
|
||
if bool(data.get("is_prev")):
|
||
return True
|
||
elif target and token == target:
|
||
return True
|
||
return False
|
||
|
||
|
||
def goback_overlap(left: list[str], right: list[str]) -> bool:
|
||
"""两组筛子(落点令牌 / 来源通道)会不会被同一次退回同时命中——两条规则撞不撞先看这一条。
|
||
|
||
有一边没筛就是"任何落点",必然重叠;两边都筛了就比令牌。两个不同的令牌算不重叠:
|
||
极端情况下 ``@prev`` 与 ``@starter`` 会同时为真(这一环没有可退的审批环节,候选第一个就是
|
||
发起人),那时后一条只是并回前一条(同编码同环节同键),不多发也不报错,不值得为它挡保存。
|
||
"""
|
||
if not left or not right:
|
||
return True
|
||
return bool(set(left) & set(right))
|
||
|
||
|
||
def goback_text(tokens: list[str], names: dict[str, str] | None = None) -> str:
|
||
"""勾中的落点说成一句人话:``退回给发起人 / 部门经理``。环节名由调用方手里那份清单给。"""
|
||
labels = names or {}
|
||
return " / ".join(GOBACK_TOKEN_LABELS.get(token, labels.get(token) or token) for token in tokens)
|
||
|
||
|
||
def mount_failure_policy(mount: dict) -> str:
|
||
"""这一条挂载的失败策略(没写就返回空串,由调用方回落到模板自己的默认)。"""
|
||
return mount_value(mount, MOUNT_FAILURE_KEYS)
|
||
|
||
|
||
def mount_fail_route(mount: dict) -> str:
|
||
"""这一条挂载指定的补救路线(``branch`` 那一期才会用到,先按两种拼写都认)。"""
|
||
return mount_value(mount, MOUNT_ROUTE_KEYS)
|
||
|
||
|
||
def condition_fields(condition: object) -> list[str]:
|
||
"""结构化条件里引用了哪些表单字段(与 ``dicts.condition_dependencies`` 同一口径)。
|
||
|
||
写回挂载上的 ``when`` 用的是同一份数据结构,所以也共用同一把校验尺子:
|
||
条件指向一个表单里不存在的字段,等于这条写回永远不发,且没人会被通知。
|
||
"""
|
||
if isinstance(condition, list):
|
||
condition = {"rules": condition}
|
||
if not isinstance(condition, dict):
|
||
return []
|
||
out: list[str] = []
|
||
for rule in condition.get("rules") or []:
|
||
if not isinstance(rule, dict):
|
||
continue
|
||
name = str(rule.get("field") or "").strip()
|
||
if name and name not in out:
|
||
out.append(name)
|
||
return out
|
||
|
||
|
||
def row_refs(row: dict) -> list[str]:
|
||
"""一行映射里所有要解析的取值写法:``from`` 加上逐行映射 ``map`` 里每格的 from。
|
||
|
||
逐行映射那几格最容易漏校验——界面上它们是明细里的小格子,配置却和顶层 from 同级。
|
||
"""
|
||
out: list[str] = []
|
||
for value in [row.get("from"), *(v.get("from") for v in (row.get("map") or {}).values()
|
||
if isinstance(v, dict))]:
|
||
text = "" if value is None else str(value)
|
||
if "{" not in text:
|
||
# 没有花括号的 from 是字面量,但少了 from 这一格上面已经报过
|
||
continue
|
||
out.append(text)
|
||
if row.get("each"):
|
||
out.append(str(row["each"]))
|
||
return out
|
||
|
||
|
||
def _ref_problems(mark: str, exprs: Iterable[str]) -> list[str]:
|
||
"""前缀写法校验。判据与 ``Ctx.value_of`` 保持一致:认不出的前缀会当字面量发出去。
|
||
|
||
``{form.x}`` 与 ``{form:x}`` 都能渲染(``KIND_HEAD`` 点和冒号都收),这里要是只认
|
||
冒号,就会把能正常工作的写法判成错的——越界报错比不报错更坑人。
|
||
"""
|
||
out: list[str] = []
|
||
for expr in exprs:
|
||
for token in TOKEN_ANY.findall(expr):
|
||
head = KIND_HEAD.match(token.strip())
|
||
if not head:
|
||
out.append(f"{mark}用了不认识的取值写法:{{{token}}},"
|
||
"要以 form/item/work/activity/auto/const/attach 开头")
|
||
continue
|
||
kind, rest = head.group(1), head.group(2)
|
||
if kind in TRANSFORMS:
|
||
# 转换函数里还套着一段取值写法,用同一把尺子再看一眼
|
||
out.extend(_ref_problems(mark, ["{%s}" % rest] if "{" not in rest else []))
|
||
elif kind not in REF_KINDS:
|
||
out.append(f"{mark}用了不认识的取值写法:{{{token}}},"
|
||
"要以 form/item/work/activity/auto/const/attach 开头")
|
||
elif kind == "auto":
|
||
name, _, fmt = rest.partition(":")
|
||
if name.strip() not in AUTO_KINDS:
|
||
out.append(f"{mark}的自动变量不认识:{name.strip() or '(空)'}(可选 {'/'.join(AUTO_KINDS)})")
|
||
elif name.strip() in ("today", "now") and fmt.strip() and fmt.strip() not in DATE_FORMATS:
|
||
out.append(f"{mark}的日期格式不支持:{fmt.strip()}(可选 {'/'.join(DATE_FORMATS)})")
|
||
elif kind == "work":
|
||
attr = rest.strip()
|
||
if attr not in WORK_FIELDS:
|
||
out.append(f"{mark}取不到单据上的这个值:{{{{work.{attr}}}}}(可选 {'/'.join(WORK_FIELDS)})")
|
||
elif kind == "activity":
|
||
attr = rest.strip()
|
||
if attr not in ACTIVITY_FIELDS:
|
||
out.append(f"{mark}取不到环节上的这个值:{{{{activity.{attr}}}}}"
|
||
f"(可选 {'/'.join(ACTIVITY_FIELDS)};它是触发这条报文的那一环)")
|
||
elif kind == "action":
|
||
attr = rest.strip()
|
||
if attr not in ACTION_FIELDS:
|
||
out.append(f"{mark}取不到按钮上的这个值:{{{{action.{attr}}}}}"
|
||
f"(可选 {'/'.join(ACTION_FIELDS)};它是触发这条报文的那颗按钮,"
|
||
"三条终态那一刻没有按钮,这几格渲染成空串)")
|
||
return out
|
||
|
||
|
||
def problems(db: Session, integration: dict, *, fields: Iterable[dict] | None = None,
|
||
source: models.DataSource | None = None) -> list[str]:
|
||
"""模板配置的毛病。与 ``form_problems`` 同一把尺子,界面上先说一遍再存。"""
|
||
out: list[str] = []
|
||
code = str(integration.get("code") or "").strip()
|
||
at = f"模板「{str(integration.get('name') or code) or '未命名'}」"
|
||
template = integration.get("payload")
|
||
if not isinstance(template, dict):
|
||
out.append(f"{at}的映射配置格式不对")
|
||
template = {}
|
||
event = str(integration.get("trigger_event") or "").strip()
|
||
if event not in models.Integration.EVENTS:
|
||
out.append(f"{at}的触发事件不支持:{event}")
|
||
# 「什么时候发」是一份清单(办结 / 终止 / 作废可以多选,也可以一条都不勾)。
|
||
# 认不得的取值必须点名:静默丢掉一格,就是"界面上勾了、终态那一刻却没发"。
|
||
raw_events = integration.get("triggerEvents")
|
||
if raw_events not in (None, "", []) and not isinstance(raw_events, list):
|
||
out.append(f"{at}的「什么时候发」得是一份清单")
|
||
else:
|
||
unknown = [str(item or "").strip() for item in (raw_events or [])
|
||
if str(item or "").strip() and str(item or "").strip() not in
|
||
models.Integration.TERMINAL_EVENTS]
|
||
if unknown:
|
||
out.append(f"{at}的「什么时候发」里有不支持的取值:{'、'.join(unknown)}"
|
||
"(这一格只有办结 / 终止 / 作废,环节那一刻发不在这儿配)")
|
||
# 一条都不勾不是毛病,是**还没定时机**:这条模板要么被挂在某个环节上,要么只在集成页重推。
|
||
# 界面上会把这件事写在明面上(见 IntegrationView 的「什么时候真的会发」),这里不拦保存。
|
||
event_key = str(integration.get("eventKey") or "").strip()
|
||
if event == models.Integration.EVENT_ACTIVITY and not event_key:
|
||
out.append(f"{at}选了「到达某环节」但没选是哪个环节")
|
||
elif event == models.Integration.EVENT_ACTIVITY and event_key and terminal_events_of(integration):
|
||
# 两头都点名 = 这个环节发一次、终态那一刻再发一次,两条报文幂等键不同(事件段不一样)。
|
||
# 与"终态模板被挂进环节"是同一件事的两个方向,所以同样在保存时挡下来。
|
||
labels = " / ".join(TERMINAL_LABELS.get(item, item) for item in terminal_events_of(integration))
|
||
out.append(f"{at}既写着「到达某环节」又勾了{labels},会在这两个时刻各发一次,"
|
||
"两条报文幂等键不同、上游会当成两笔;用界面上一键把它搬到环节上,"
|
||
"或把终态那一半另发一个编码")
|
||
if event == models.Integration.EVENT_ACTIVITY and event_key:
|
||
# 这一种触发以前**从来不发**(没有调用方),如今真会发了,环节 id 写错就等于
|
||
# 配了一条永远不响的写回——保存时挡下来,比上线后"怎么没动静"好查一万倍。
|
||
hit = db.execute(
|
||
select(models.Activity.name, models.Activity.process, models.Activity.form,
|
||
models.Activity.type)
|
||
.where(models.Activity.id == event_key)
|
||
).first()
|
||
if hit is None:
|
||
out.append(f"{at}选的环节在流程里不存在(环节 id:{event_key}),这个模板一条都不会发")
|
||
elif str(hit.type or "").strip() == "begin":
|
||
out.append(f"{at}的环节「{hit.name}」是发起环节,它不会被「走到」,这一条永远不会发;"
|
||
"要在提交那一刻发,就去流程设计器把这个模板挂到发起环节的「写回挂载」上(时机就是「提交单据时」)")
|
||
else:
|
||
# 环节 id 是真的,但它只属于一条流程;模板绑的表单和那张单对不上时,
|
||
# 运行期会按"不是这张单"跳过(outbox.enqueue_node),一条不发也不报错。
|
||
process = db.get(models.Process, str(hit.process or ""))
|
||
form_id = str(hit.form or "") or str(getattr(process, "latest_form", "") or "")
|
||
bound = str(integration.get("bizForm") or "").strip()
|
||
if bound and form_id and bound != form_id:
|
||
out.append(f"{at}绑的表单与环节「{hit.name}」用的那张单不是同一张,"
|
||
"走到那里会被跳过,一条都不会发")
|
||
condition = integration.get("condition")
|
||
if condition not in (None, "", {}, []):
|
||
wanted = {str((item or {}).get("key") or "").strip()
|
||
for item in (fields or []) if isinstance(item, dict)}
|
||
for name in condition_fields(condition):
|
||
# 没绑表单时不校验字段名(与"还没选表单就不校验映射里的字段引用"同一分寸)
|
||
if wanted and name not in wanted:
|
||
out.append(f"{at}「哪些单才发」里的字段在这张表单里不存在:{name}(条件不成立的单一条都不会发)")
|
||
if not dicts.has_rules(condition):
|
||
out.append(f"{at}配了「哪些单才发」却一条条件都没写,等于每张单都发")
|
||
failure = str(integration.get("onFailure") or "continue").strip()
|
||
if failure not in models.Integration.FAILURE_POLICIES:
|
||
out.append(f"{at}的失败策略不支持:{failure}")
|
||
if failure == models.Integration.FAILURE_BRANCH and not str(integration.get("failRoute") or "").strip():
|
||
out.append(f"{at}选了「走一条补救路线」但没选是哪条路线")
|
||
rule = str(integration.get("idemRule") or "").strip()
|
||
if rule:
|
||
names = {name.strip() for name in TOKEN_ANY.findall(rule)}
|
||
unknown = [name for name in TOKEN_ANY.findall(rule) if name.strip() not in IDEM_VARS]
|
||
if unknown:
|
||
out.append(f"{at}的幂等键用了不认识的变量:{'、'.join(unknown)}")
|
||
elif "code" not in names:
|
||
# 少了模板编码,同一张单上的另一个模板会被本地唯一键当成重复吃掉
|
||
out.append(f"{at}的幂等键没带模板编码 {{{{code}}}}:同一张单挂多个模板时,"
|
||
"后配的那条会被当成重复而悄悄丢掉")
|
||
elif bool(integration.get("refireOnRevisit")) and "revision" not in names:
|
||
# 勾了重发却换不出新键,就是"界面勾了、运行期什么也没发生"那一类,保存时点名
|
||
out.append(f"{at}勾了「重复到达时重发」,但幂等键没带 {{revision}}:再次走到这一环节时"
|
||
"算出来的键与上一条完全一样,会被本地唯一键挡回去,等于没勾")
|
||
|
||
if source is not None:
|
||
if source.direction == models.DataSource.DIRECTION_IN:
|
||
out.append(f"{at}引用的数据源 {source.code} 方向是「只取数」,写回要选「往外写」或「双向」")
|
||
elif str(integration.get("source") or "").strip():
|
||
out.append(f"{at}引用的数据源不存在:{integration.get('source')}")
|
||
|
||
keys = {str(item.get("key") or "").strip() for item in (fields or []) if isinstance(item, dict)}
|
||
types = {str(item.get("key") or "").strip(): str(item.get("type") or "") for item in (fields or [])
|
||
if isinstance(item, dict)}
|
||
cache = dicts.DictCache(db)
|
||
for index, item in enumerate(template.get("fields") or [], start=1):
|
||
mark = f"{at}第 {index} 行映射"
|
||
if not isinstance(item, dict):
|
||
out.append(f"{mark}格式不对")
|
||
continue
|
||
to = str(item.get("to") or "").strip()
|
||
if not to:
|
||
out.append(f"{mark}没写目标字段")
|
||
elif not TO_PATH.match(to):
|
||
out.append(f"{mark}的目标字段不合法:{to}")
|
||
if not item.get("each") and "from" not in item:
|
||
out.append(f"{mark}没写怎么取值(from)")
|
||
if item.get("each"):
|
||
rows = real_form_refs(form_refs_of(item.get("each")))
|
||
for key in rows:
|
||
if keys and key not in keys:
|
||
out.append(f"{mark}逐行映射的 {key} 在表单里不存在")
|
||
elif types.get(key) and types[key] != "table":
|
||
out.append(f"{mark}的 {key} 不是明细表,逐行映射配不上")
|
||
if not item.get("map"):
|
||
out.append(f"{mark}配了逐行映射但没写每行发哪些字段")
|
||
if str(item.get("dictMap") or "").strip() and not cache.items(str(item["dictMap"]).strip()):
|
||
out.append(f"{mark}要翻译的字典不存在或是空的:{item['dictMap']}")
|
||
out.extend(_ref_problems(mark, row_refs(item)))
|
||
for key in real_form_refs(form_refs_of(item)):
|
||
if keys and key not in keys:
|
||
out.append(f"{mark}取的表单字段不存在:{key}")
|
||
if item.get("transform"):
|
||
out.extend(_script_problem(item["transform"], f"{mark}的派生值脚本"))
|
||
if str(template.get("transform") or "").strip():
|
||
out.extend(_script_problem(template["transform"], f"{at}的报文级脚本"))
|
||
|
||
for index, item in enumerate(integration.get("resultWrite") or [], start=1):
|
||
target = str((item or {}).get("to") or "").strip() if isinstance(item, dict) else ""
|
||
if not target:
|
||
out.append(f"{at}第 {index} 行响应回写没写回哪个字段")
|
||
elif keys and target not in keys:
|
||
out.append(f"{at}响应要回写的字段在表单里不存在:{target}")
|
||
if isinstance(item, dict) and not str(item.get("pick") or "").strip():
|
||
out.append(f"{at}第 {index} 行响应回写没写从响应哪里取")
|
||
return out
|
||
|
||
|
||
def activity_form_id(db: Session, activity) -> str:
|
||
"""这个环节实际看的是哪张单:环节自己的 ``form`` 优先,否则流程的 ``latest_form``。"""
|
||
form_id = str(getattr(activity, "form", "") or "").strip()
|
||
if form_id:
|
||
return form_id
|
||
process_id = str(getattr(activity, "process", "") or "").strip()
|
||
process = db.get(models.Process, process_id) if process_id else None
|
||
return str(getattr(process, "latest_form", "") or "").strip()
|
||
|
||
|
||
def activity_form_fields(db: Session, activity, cache: dict[str, list[dict]]) -> list[dict]:
|
||
"""这个环节那张单的字段清单。校验 ``when`` 里的字段、模板绑的表单都从这儿拿。"""
|
||
form_id = activity_form_id(db, activity)
|
||
if not form_id:
|
||
return []
|
||
if form_id not in cache:
|
||
cache[form_id] = autofill.form_fields(db, form_id)
|
||
return cache[form_id]
|
||
|
||
|
||
def phase_sign(integration: object, phase: str) -> str:
|
||
"""这条模板在这个时刻上的幂等键"时刻段"是什么形状。
|
||
|
||
同一个环节上两段形状一样的两个时刻会撞成一条报文(后一条被 ``uk_ob_idem`` 吃掉),
|
||
形状不同的才各发一条:默认键下「通过后」与「退回」分得开、「到达」与「通过后」分不开
|
||
(:data:`PHASE_KEY_TRIGGERS` 那句说的就是这件事);自定义键里写了 ``{phase}`` 就按时刻分,
|
||
既没写 ``{event}`` 也没写 ``{phase}`` 则是**任何**时刻都只发一条。
|
||
"""
|
||
rule = str(getattr(integration, "idem_rule", "") or "").strip() or DEFAULT_IDEM_RULE
|
||
if "{phase}" in rule:
|
||
return phase
|
||
if "{event}" not in rule:
|
||
return ""
|
||
return phase if phase in PHASE_KEY_TRIGGERS else ""
|
||
|
||
|
||
def mount_problems(
|
||
db: Session,
|
||
activities: Iterable[object],
|
||
route_refs: Iterable[str],
|
||
goback: dict[str, Iterable[str]] | None = None,
|
||
) -> list[str]:
|
||
"""L3 挂载(环节配置里的 ``writeback``)的毛病。
|
||
|
||
这一层的错最阴:模板本身是好的、流程本身也能发布,只有走到那一环节才发现
|
||
"模板早被删了"或者"响应回写的字段审批人还能改"。所以要在**保存流程**的时候就挡下来。
|
||
|
||
``goback`` 是每一环**退得到哪些环节**(``环节 id -> 落点 id 集合``,由调用方从流程定义算:
|
||
:func:`app.engine.engine.goback_universe`)。给了它才能查出"勾了一个这一环永远退不到的
|
||
落点"这种死配置;没给(拿不到图的调用方)就跳过这一条,别拿缺信息当有病。
|
||
|
||
一个环节可以挂**多条规则**(``blocks``):各有各的时机、模板、条件和失败策略,
|
||
所以结构问题逐块判、提示里点名是第几条;模板自己那些毛病(不存在、停用、终态重复、
|
||
绑错表单、响应回写打架)跟哪条规则无关,跨块去重后只说一遍。
|
||
"""
|
||
out: list[str] = []
|
||
# 设计器按路由名挑路线、库里存的是路由 id,两种写法都算认得(见 §3.3)
|
||
known_routes = {str(rid or "").strip() for rid in (route_refs or [])}
|
||
# 落点筛子(goBackTo)指到这两份名单之外就是死配置:环节压根不存在,或这一环退不到那里
|
||
activity_rows = list(activities or [])
|
||
activity_names = {str(getattr(item, "id", "") or "").strip(): str(getattr(item, "name", "") or "")
|
||
for item in activity_rows}
|
||
reachable = {str(key or "").strip(): {str(value or "").strip() for value in (values or [])}
|
||
for key, values in (goback or {}).items()}
|
||
mounts: list[tuple[object, dict, list[dict]]] = []
|
||
wanted: list[str] = []
|
||
for activity in activity_rows:
|
||
mount = mount_of(activity)
|
||
if not mount:
|
||
continue
|
||
blocks = mount_blocks(mount)
|
||
mounts.append((activity, mount, blocks))
|
||
for block in blocks:
|
||
for code, _ in mount_entries(block):
|
||
if code not in wanted:
|
||
wanted.append(code)
|
||
if not mounts:
|
||
return out
|
||
|
||
rows = db.execute(select(models.Integration).where(
|
||
models.Integration.code.in_(wanted))).scalars().all() if wanted else []
|
||
by_code = {row.code: row for row in rows}
|
||
field_cache: dict[str, list[dict]] = {}
|
||
for activity, mount, blocks in mounts:
|
||
at = f"环节「{getattr(activity, 'name', '') or getattr(activity, 'id', '')}」的写回配置"
|
||
activity_id = str(getattr(activity, "id", "") or "").strip()
|
||
# 同一环节挂多条规则时,"触发时机不支持"这种话必须说清是哪一条,否则没人找得着
|
||
labels = [at] if len(blocks) == 1 else [f"{at}第 {index + 1} 条规则" for index in range(len(blocks))]
|
||
keys = {str(item.get("key") or "").strip() for item in activity_form_fields(db, activity, field_cache)
|
||
if isinstance(item, dict)}
|
||
# 编码 -> 各块里勾的「要发的字段」并集:勾错名字和条件指错字段一样阴,保存时就点名
|
||
scopes: dict[str, list[str]] = {}
|
||
for block in blocks:
|
||
for code, names in mount_entry_fields(block).items():
|
||
merged = scopes.setdefault(code, [])
|
||
merged.extend(name for name in names if name not in merged)
|
||
# blocks 与顶层 integrations 同时写:运行期只认 blocks(见 mount_blocks),
|
||
# 顶层那一串会被静静吃掉,所以保存时就说明白
|
||
if isinstance(mount.get("blocks"), list) and mount.get("blocks") and (mount.get("integrations") or []):
|
||
out.append(f"{at}同时写了顶层的模板清单和多条规则,实际只按多条规则那几组发送;把顶层那一串清掉")
|
||
# 重复提醒里只说"第几条",把整段环节名抄两遍没人看得下去
|
||
short_labels = [f"第 {index + 1} 条规则" for index in range(len(blocks))]
|
||
first_label: dict[str, int] = {}
|
||
# 编码 -> 已出现过的那些时刻的 (幂等键时刻段, 那块勾的退回落点, 那块勾的退回来源):
|
||
# 形状撞上、且落点与来源两组筛子都可能被同一次退回同时命中,才是真撞。两条规则各管各的
|
||
# 落点(或各管各的来源)时同一次退回只会命中一块,那叫分流不叫重复。
|
||
first_signs: dict[str, list[tuple[str, list[str], list[str]]]] = {}
|
||
for index, (label, block) in enumerate(zip(labels, blocks)):
|
||
entries = mount_entries(block)
|
||
block_codes = [code for code, _ in entries]
|
||
if not block_codes:
|
||
out.append(f"{label}还没选要发哪个写回模板")
|
||
phases = mount_triggers(block)
|
||
tokens, tokens_written = mount_goback_raw(block)
|
||
vias, vias_written = mount_goback_via_raw(block)
|
||
for code in block_codes:
|
||
name = by_code[code].name if by_code.get(code) else code
|
||
signs = first_signs.get(code)
|
||
if signs is None:
|
||
first_label[code] = index
|
||
first_signs[code] = [(phase_sign(by_code.get(code), phase), tokens, vias)
|
||
for phase in phases]
|
||
continue
|
||
# 撞不撞看四件事:报文编码、环节、幂等键的时刻段是不是全一样,再加上这两块勾的
|
||
# 退回落点与退回来源会不会被同一次退回同时命中。全撞上 = 后一条必被 uk_ob_idem
|
||
# 当成重复吃掉。
|
||
clash = [phase for phase in phases
|
||
if any(sign == phase_sign(by_code.get(code), phase)
|
||
and goback_overlap(owner_to, tokens)
|
||
and goback_overlap(owner_via, vias)
|
||
for sign, owner_to, owner_via in signs)]
|
||
if clash:
|
||
same_moment = [phase for phase in clash if phase in mount_triggers(blocks[first_label[code]])]
|
||
note = (f"两个时刻都是{trigger_text(same_moment or clash)},"
|
||
"两条报文的幂等键相同,后一条会被当成重复报文丢掉" if same_moment else
|
||
f"{trigger_text(clash)} 那几个时刻在这条模板的幂等键里分不开"
|
||
"(自定义键里既没有 {event} 也没有 {phase}),后一条会被当成重复报文丢掉;"
|
||
"要按时刻各发一条,就到集成页把这条模板的幂等键加上 {phase}")
|
||
if TRIGGER_GOBACK in (same_moment or clash):
|
||
note += (";只想按退落到哪一环分开,就把 {target} 加进这条模板的幂等键;"
|
||
"只想按这一退是谁按的分开,就加 {via}")
|
||
out.append(f"{label}又选了模板「{name}」,与{short_labels[first_label[code]]}重复:"
|
||
+ note + ";分流请各用各的编码")
|
||
first_signs[code] = [*signs, *((phase_sign(by_code.get(code), phase), tokens, vias)
|
||
for phase in phases
|
||
if phase not in mount_triggers(blocks[first_label[code]]))]
|
||
for phase in phases:
|
||
if phase in TRIGGERS:
|
||
continue
|
||
out.append(f"{label}的触发时机不支持:{block.get('trigger') if len(phases) == 1 else phase}"
|
||
f"(可选 {trigger_text(TRIGGERS)})")
|
||
# 开始环节只有「提交」这一个时刻、结束/作废只有「到达」这一个时刻:
|
||
# 配成另一个不会报错,只是这条写回一条都不会发(创建与归档就配在这两个环节上)
|
||
node_type = str(getattr(activity, "type", "") or "").strip()
|
||
one_way = ONE_WAY_TRIGGER.get(node_type)
|
||
if one_way and one_way[0] in phases:
|
||
out.append(f"{label}的触发时机选错了:{one_way[1]}。"
|
||
f"要在这里回写就把时机改成「{'本环节审批通过后' if one_way[0] == 'arrive' else '到达本环节时'}」,"
|
||
"否则这条写回永远不会发")
|
||
# 「退回」/「撤回」这两个时刻挂在没有那颗按钮的环节上,同样是死配置:
|
||
# 分支环节没人按按钮、把按钮关掉的那一环按不动,配在这里一条都不会发。
|
||
for phase in phases:
|
||
allowed = TRIGGER_ACTIVITY_TYPES.get(phase)
|
||
if allowed is not None and node_type not in allowed:
|
||
out.append(f"{label}的触发时机是「{TRIGGER_LABELS[phase]}」,"
|
||
f"而这一环是{ACTIVITY_TYPE_LABELS.get(node_type, node_type or '未知')}环节,"
|
||
"不会有这一刻;这条写回一条都不会发,换成「到达本环节时」或「本环节审批通过后」")
|
||
continue
|
||
flag = TRIGGER_ACTIVITY_FLAGS.get(phase)
|
||
if flag and not bool((getattr(activity, "config", None) or {}).get(flag[0], True)):
|
||
out.append(f"{label}的触发时机是「{TRIGGER_LABELS[phase]}」,但这一环把「{flag[1]}」按钮关了"
|
||
f"({flag[0]}=false);要么把按钮打开,要么把这条写回的时机改掉")
|
||
# 「退回到哪些环节才发」那一格:勾了「被退回时」才算数,勾中的落点还得是这一环
|
||
# 真退得到的地方。落点写错 = 又一条"界面上一切正常、运行期一声不响"的配置。
|
||
if tokens_written and not tokens:
|
||
out.append(f"{label}勾了「退回到哪些环节才发」却一个都没选,等于任何退回都发;"
|
||
"要任何退回都发就别写这一格")
|
||
elif tokens and TRIGGER_GOBACK not in phases:
|
||
out.append(f"{label}写了退回落点({goback_text(tokens, activity_names)})却没勾"
|
||
f"「{TRIGGER_LABELS[TRIGGER_GOBACK]}」,落点那一格是白配的")
|
||
elif tokens and node_type in (TRIGGER_ACTIVITY_TYPES.get(TRIGGER_GOBACK) or ()):
|
||
for token in tokens:
|
||
if token in GOBACK_TOKENS:
|
||
continue
|
||
name = activity_names.get(token) or token
|
||
if token not in activity_names:
|
||
out.append(f"{label}的退回落点指的环节在这条流程里不存在:{name}"
|
||
"(环节被删了,或是别处导来的流程件换了 id);这条写回一条都不会发,"
|
||
"重新勾一次落点,或改用「退回给发起人」这一档")
|
||
elif activity_id in reachable and token not in reachable[activity_id]:
|
||
out.append(f"{label}的退回落点勾了「{name}」,但这一环退不到它——退回只退得到"
|
||
"本环节的上游环节,还不能超出那颗按钮的可选范围;换一个退得到的落点")
|
||
# 「谁按的退回才发」那一格(goBackVia):第三方调接口把这一退送进来、与审批人在
|
||
# 待办页点那颗按钮,对面要的处理常常不一样,这一格把它们分开。通道名写错同样是
|
||
# "界面上一切正常、运行期一声不响",保存时一起点名。
|
||
if vias_written and not vias:
|
||
out.append(f"{label}勾了「谁按的退回才发」却一个都没选,等于谁按的都发;"
|
||
"要谁按的都发就别写这一格")
|
||
elif vias and TRIGGER_GOBACK not in phases:
|
||
out.append(f"{label}写了退回来源({goback_via_text(vias)})却没勾"
|
||
f"「{TRIGGER_LABELS[TRIGGER_GOBACK]}」,来源那一格是白配的")
|
||
else:
|
||
for value in vias:
|
||
if value not in GOBACK_VIAS:
|
||
out.append(f"{label}的退回来源不认识:{value}(可选 "
|
||
f"{goback_via_text(GOBACK_VIAS)};第三方调 /open/* 退回是 open,"
|
||
"嵌入页 decide 与引擎替父单点的子流程是 embed)")
|
||
failure = mount_failure_policy(block)
|
||
if failure and failure not in models.Integration.FAILURE_POLICIES:
|
||
out.append(f"{label}的失败策略不支持:{failure}")
|
||
if failure == models.Integration.FAILURE_BRANCH:
|
||
# 自动改道要在流转那一刻就知道写回结果,与发件箱异步投递的前提冲突;
|
||
# 这一期它按「挡住处理人」执行。宁可保存时说一句,也别让人以为改道已经生效。
|
||
out.append(f"{label}选的「走一条补救路线」这一期还不会自动改道,实际按「挡住处理人」执行;"
|
||
"要人工补救就选「挡住处理人」,再在集成页重推")
|
||
route = mount_fail_route(block)
|
||
if route and known_routes and route not in known_routes:
|
||
out.append(f"{label}指定的补救路线在这条流程里不存在:{route}")
|
||
# 「只有部分单要回写」那条条件:字段名打错等于这条写回永远不发,而且没人被通知——
|
||
# 比发错更难发现,所以必须在保存流程时就挡下来。
|
||
for name in condition_fields(block.get("when")):
|
||
if keys and name not in keys:
|
||
out.append(f"{label}「满足条件才发」里的字段在表单里不存在:{name}(条件不成立的单一条都不会发)")
|
||
# 挂了条件却一条都没写:condition_ok 会当成「无条件」放行,跟"只想发一部分"的本意正好相反
|
||
if isinstance(block.get("when"), dict) and not dicts.has_rules(block.get("when")):
|
||
out.append(f"{label}配了「满足条件才发」却一条条件都没写,等于每张单都发")
|
||
# 单个模板那一格的条件:同一把尺子,只是提示里要点名是哪个模板
|
||
for code, entry_when in entries:
|
||
if not entry_when:
|
||
continue
|
||
name_label = by_code[code].name if by_code.get(code) else code
|
||
for field in condition_fields(entry_when):
|
||
if keys and field not in keys:
|
||
out.append(f"{label}模板「{name_label}」那一格的条件里,字段在表单里不存在:{field}"
|
||
"(条件不成立的单这一条不会发)")
|
||
if not dicts.has_rules(entry_when):
|
||
out.append(f"{label}模板「{name_label}」那一格配了条件却一条都没写,"
|
||
"等于这一环节每张单都发这个模板")
|
||
perms = ((getattr(activity, "config", None) or {}).get("formPerms")
|
||
if isinstance(getattr(activity, "config", None), dict) else None) or {}
|
||
for code in [item for item, _ in mount_all_entries(mount)]:
|
||
template = by_code.get(code)
|
||
if template is None:
|
||
out.append(f"{at}点名的写回模板不存在:{code}")
|
||
continue
|
||
if not template.enabled:
|
||
out.append(f"{at}点名的写回模板「{template.name}」已经停用,走到这里什么都不会发")
|
||
# 模板绑了别的表单:映射里的 {form.x} 读的是这张单,取不到就是空值发出去
|
||
# (运行期 outbox 也按这一条跳过,两边口径一致)
|
||
if template.biz_form and activity_form_id(db, activity) and \
|
||
template.biz_form != activity_form_id(db, activity):
|
||
out.append(f"{at}要发的模板「{template.name}」绑的是另一张表单,"
|
||
"这一环节的单子取不到它要的那些字段")
|
||
scope = scopes.get(code)
|
||
if scope:
|
||
targets = template_field_targets(template.payload)
|
||
unknown = [name for name in scope if name not in targets]
|
||
if unknown:
|
||
out.append(f"{at}要发的模板「{template.name}」勾了模板映射里没有的发送字段:"
|
||
f"{' / '.join(unknown)};能勾的是 {' / '.join(targets) or '(这个模板还没有映射行)'}")
|
||
# 三条终态的模板又被挂在环节上 = 同一份报文发两次:这一环节一次、进终态那一刻一次。
|
||
# 两条报文的幂等键不同(事件段不一样),上游只会当成两笔业务——那正是"一张凭证变两张"的来路。
|
||
events = terminal_events_of(template)
|
||
if events:
|
||
label = " / ".join(TERMINAL_LABELS.get(item, item) for item in events)
|
||
out.append(f"{at}要发的模板「{template.name}」的「什么时候发」勾了{label},挂在环节上会让它"
|
||
f"在这一环节和{label}那一刻各发一次,两条报文幂等键不同、上游会当成两笔;"
|
||
"只想要一次就到集成页把这条模板的终态勾选去掉(时机就只听这个环节的),"
|
||
"确实两头都要发就为终态那一刻另发一个编码")
|
||
for item in template.result_write or []:
|
||
target = str((item or {}).get("to") or "").strip() if isinstance(item, dict) else ""
|
||
# 审批人还能改这一格,响应回来又把它覆盖掉:同一次提交里两个来源抢一个字段
|
||
if target and str(perms.get(target) or "") in ("editable", "required"):
|
||
out.append(f"{at}要发的模板「{template.name}」会把响应写回「{target}」,"
|
||
f"但这一环节这一格还能编辑,会被响应覆盖;把它设成只读或隐藏")
|
||
return out
|
||
|
||
|
||
def _script_problem(script: object, at: str) -> list[str]:
|
||
"""脚本只在设计期查一次语法(能不能编译):危险名字与 IO 由沙箱在运行期兜。"""
|
||
from ..engine import expressions
|
||
|
||
text = str(script or "").strip()
|
||
if not text:
|
||
return []
|
||
message = expressions.validate_script(text)
|
||
return [] if message is None else [f"{at}写错了:{message}"]
|
||
|
||
|
||
def out_fields_of(template: object) -> list[str]:
|
||
"""这份模板会把哪些表单字段送出 OA。
|
||
|
||
报文是**出域数据**(§13):模板页必须能把这份清单摊给人看,
|
||
身份证、银行卡这类字段一旦出现在映射里,配置的人应当当场看见自己发了什么。
|
||
"""
|
||
return form_refs_of(template)
|