648 lines
31 KiB
Python
648 lines
31 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, dicts, quota
|
||
from .quota import DATE_FORMATS, to_cents
|
||
|
||
#: 整段就是一个 ``{...}`` 时按原类型给(金额不该变成字符串),拼串写法才转字符串
|
||
TOKEN_ALL = re.compile(r"^\{([^{}]+)\}$")
|
||
#: 串里的每一个 ``{...}``
|
||
TOKEN_ANY = re.compile(r"\{([^{}]+)\}")
|
||
#: 五种取值写法
|
||
REF_KINDS = ("form", "item", "work", "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)
|
||
TRANSFORMS = ("cents", "yuan", "date", "trim", "upper", "default", "join", "bool")
|
||
#: 幂等键能用的变量
|
||
IDEM_VARS = ("source", "code", "job", "serial", "work", "event", "event_key", "revision", "today")
|
||
#: 没填幂等键模板时用的这一份
|
||
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`` 这种统一身份 DN 不该被顺手发出去。
|
||
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",
|
||
)
|
||
#: 目标路径允许的字符:点分路径,数组下标写 ``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 == "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,
|
||
row: dict | None = None, cache: dicts.DictCache | None = None) -> None:
|
||
self.db = db
|
||
self.data = dict(data or {})
|
||
self.work = work
|
||
self.actor = actor
|
||
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,
|
||
row=row, 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 == "const":
|
||
return 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 = self.cache.index(code).get(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) -> 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}" } } } ] }
|
||
"""
|
||
if not isinstance(template, dict):
|
||
raise RenderError("映射配置不是一段对象")
|
||
ctx = Ctx(db, data=data, work=work, actor=actor)
|
||
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 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) -> tuple[str, str, dict]:
|
||
"""渲染一条待发消息:回 ``(method, url, body)``。"""
|
||
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),
|
||
)
|
||
|
||
|
||
def idem_key(integration: models.Integration, *, source: str, job: str, serial: str,
|
||
work_id: str, event: str, event_key: str, revision: int) -> str:
|
||
"""幂等键:默认 ``{source}:{code}:{job}:{event}:{event_key}:{revision}``,随 ``X-Idempotency-Key`` 发出。
|
||
|
||
上游支持幂等时它是"重发也不会多一张凭证"的凭据;上游不支持时,至少本地
|
||
``uk_ob_idem`` 唯一键挡得住重复入队。键里必须有 ``{code}``:一张单挂两个模板时,
|
||
少了它就只剩第一条。
|
||
"""
|
||
values = {
|
||
"source": source, "code": integration.code, "job": job, "serial": serial,
|
||
"work": work_id, "event": event, "event_key": event_key, "revision": str(revision),
|
||
"today": datetime.now().strftime("%Y-%m-%d"),
|
||
}
|
||
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
|
||
|
||
|
||
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/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/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)})")
|
||
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}")
|
||
if event == models.Integration.EVENT_ACTIVITY and not str(integration.get("eventKey") or "").strip():
|
||
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:
|
||
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 {name.strip() for name in TOKEN_ANY.findall(rule)}:
|
||
# 少了模板编码,同一张单上的另一个模板会被本地唯一键当成重复吃掉
|
||
out.append(f"{at}的幂等键没带模板编码 {{{{code}}}}:同一张单挂多个模板时,"
|
||
"后配的那条会被当成重复而悄悄丢掉")
|
||
|
||
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 = 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 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 mount_problems(db: Session, activities: Iterable[object], route_refs: Iterable[str]) -> list[str]:
|
||
"""L3 挂载(环节配置里的 ``writeback``)的毛病。
|
||
|
||
这一层的错最阴:模板本身是好的、流程本身也能发布,只有走到那一环节才发现
|
||
"模板早被删了"或者"响应回写的字段审批人还能改"。所以要在**保存流程**的时候就挡下来。
|
||
"""
|
||
out: list[str] = []
|
||
# 设计器按路由名挑路线、库里存的是路由 id,两种写法都算认得(见 §3.3)
|
||
known_routes = {str(rid or "").strip() for rid in (route_refs or [])}
|
||
wanted: list[str] = []
|
||
mounts: list[tuple[object, dict, list[str]]] = []
|
||
for activity in activities or []:
|
||
config = getattr(activity, "config", None)
|
||
mount = config.get("writeback") if isinstance(config, dict) else None
|
||
if not isinstance(mount, dict):
|
||
continue
|
||
codes = [str(code or "").strip() for code in (mount.get("integrations") or [])]
|
||
codes = [code for code in codes if code]
|
||
wanted.extend(code for code in codes if code not in wanted)
|
||
mounts.append((activity, mount, codes))
|
||
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}
|
||
for activity, mount, codes in mounts:
|
||
at = f"环节「{getattr(activity, 'name', '') or getattr(activity, 'id', '')}」的写回配置"
|
||
if not codes:
|
||
out.append(f"{at}还没选要发哪个写回模板")
|
||
for code in codes:
|
||
if code not in wanted or by_code.get(code) is None:
|
||
out.append(f"{at}点名的写回模板不存在:{code}")
|
||
elif not by_code[code].enabled:
|
||
out.append(f"{at}点名的写回模板「{by_code[code].name}」已经停用,走到这里什么都不会发")
|
||
failure = str(mount.get("on_failure") or "").strip()
|
||
if failure and failure not in models.Integration.FAILURE_POLICIES:
|
||
out.append(f"{at}的失败策略不支持:{failure}")
|
||
route = str(mount.get("fail_route") or "").strip()
|
||
if route and known_routes and route not in known_routes:
|
||
out.append(f"{at}指定的补救路线在这条流程里不存在:{route}")
|
||
perms = ((getattr(activity, "config", None) or {}).get("formPerms")
|
||
if isinstance(getattr(activity, "config", None), dict) else None) or {}
|
||
for code in codes:
|
||
template = by_code.get(code)
|
||
if template is None:
|
||
continue
|
||
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)
|