696 lines
31 KiB
Python
696 lines
31 KiB
Python
"""从接口一句话建出一张流程草稿:认流程、列参数、校验数据、落库,全收在这一处。
|
||
|
||
为什么单独一个 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, numbering, 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.perm_map(begin.config if begin is not None else {}, form_fields(db, process))
|
||
|
||
|
||
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 = "表单内置选项"
|
||
# value 是「这一格真正要存进去的那一列」:字段配过「显示 / 存值」就按它配的来,
|
||
# AI 起草填出来的值才与前端下拉、后端越界判断用的是同一套
|
||
out = [row for row in dicts.project_options(field, items) if row["value"]]
|
||
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
|
||
|
||
|
||
class TypeBag:
|
||
"""一批流程的「表单字段 + 开始环节权限」,各一次 ``IN`` 查完。
|
||
|
||
``GET /draft/types`` 要给每个可发起的类型列出参数,而一个参数清单要问两件事:
|
||
默认表单里有哪些字段、开始环节把这些字段的权限改成了什么。一条条问就是每条流程
|
||
两个数据库来回(实测五个类型 14 趟),库在另一台机器上时就是小半秒。查法与
|
||
:func:`form_fields` / :func:`begin_perms` 一致,只是并成一批;没预载到的流程
|
||
照旧回退去查库,不会出现「批量路径偷偷给了空清单」。
|
||
|
||
顺带攒出 :attr:`dict_codes`——这一批流程一共用到哪几本字典。字典是按流程逐条
|
||
预取的,攒齐了让调用方一次问完,五个类型就从「五条批量查询」并成一条。
|
||
"""
|
||
|
||
def __init__(self, db: Session, processes: Iterable[models.Process]) -> None:
|
||
rows = list(processes)
|
||
form_ids = [
|
||
key
|
||
for key in dict.fromkeys(str(row.latest_form or "").strip() for row in rows)
|
||
if key
|
||
]
|
||
self.fields: dict[str, list[dict]] = {}
|
||
if form_ids:
|
||
for form in db.execute(
|
||
select(models.FormElement).where(models.FormElement.id.in_(form_ids))
|
||
).scalars().all():
|
||
items = (form.content or {}).get("fields")
|
||
self.fields[form.id] = (
|
||
[item for item in items if isinstance(item, dict)]
|
||
if isinstance(items, list)
|
||
else []
|
||
)
|
||
pids = [row.id for row in rows if row.id]
|
||
self.perms: dict[str, dict[str, str]] = {}
|
||
if not pids:
|
||
return
|
||
begin: dict[str, models.Activity] = {}
|
||
for row in db.execute(
|
||
select(models.Activity)
|
||
.where(models.Activity.process.in_(pids), models.Activity.type == BEGIN_ACTIVITY)
|
||
.order_by(models.Activity.order_number)
|
||
).scalars().all():
|
||
begin.setdefault(row.process, row)
|
||
# 展开「藏整片 / 藏一页」要拿这份权限对应的字段清单;这份清单上面已经按
|
||
# latest_form 一次查完,没有预载到(表单被删之类)就照旧不展开,与 fields_of()
|
||
# 那句"没预载到回 None 让调用方自己查库"同一个分寸。
|
||
form_of = {row.id: str(row.latest_form or "").strip() for row in rows}
|
||
for pid in pids:
|
||
row = begin.get(pid)
|
||
self.perms[pid] = formruntime.perm_map(
|
||
row.config if row is not None else {}, self.fields.get(form_of.get(pid) or "")
|
||
)
|
||
|
||
#: 这一批流程的表单里出现过的字典码(含明细表列上的),去重保序
|
||
self.dict_codes = dicts.codes_of([item for group in self.fields.values() for item in group])
|
||
|
||
def fields_of(self, process: models.Process) -> list[dict] | None:
|
||
"""预载过就给清单,没预载过回 ``None`` 让调用方自己去查。"""
|
||
return self.fields.get(str(process.latest_form or "").strip()) if self.fields else None
|
||
|
||
def perms_of(self, process: models.Process) -> dict[str, str] | None:
|
||
return self.perms.get(process.id) if self.perms else None
|
||
|
||
|
||
def param_specs(
|
||
db: Session,
|
||
process: models.Process,
|
||
*,
|
||
fields: Iterable[dict] | None = None,
|
||
cache: dicts.DictCache | None = None,
|
||
perms: dict[str, str] | None = None,
|
||
) -> list[dict]:
|
||
"""这条流程要传哪些参数:一个字段一行,照着填就能建草稿。
|
||
|
||
``required`` 已经折过了开始环节的字段权限(口径同 ``formruntime``),所以它说的
|
||
是"发起时到底要不要填",不是设计器上那个早就过时的勾选框。系统带出与公式那两类
|
||
标成 ``system``:值由系统给,调用方不用传,传了也会被引擎按真实数据重算掉。
|
||
"""
|
||
items = list(fields) if fields is not None else form_fields(db, process)
|
||
# 权限口径:调用方批量预载过就用那份,否则现查(口径始终是 begin_perms)
|
||
perms = begin_perms(db, process) if perms is None else perms
|
||
bag = cache if cache is not None else dicts.DictCache(db)
|
||
# 整张表用到的字典一次问完:逐个问是每个字典一趟 Redis,本部署到 Redis 一趟 9ms
|
||
bag.prefetch(dicts.codes_of(items))
|
||
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,
|
||
bag: TypeBag | 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,
|
||
fields=bag.fields_of(process) if bag is not None else None,
|
||
perms=bag.perms_of(process) if bag is not None else None,
|
||
)
|
||
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 {})
|
||
# 选人那一格先按人落成账号(与引擎提交同一道洗法),草稿转发起时那一格才不会
|
||
# 还攥着对不上号的一串字符串
|
||
formruntime.normalize_person_values(db, list(items), payload)
|
||
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)
|
||
cache.prefetch(dicts.codes_of(items))
|
||
# 必填:标题字段这一格由标题规则负责填,没填不能算成调用方的漏子。
|
||
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 reserve_serial(db: Session, process: models.Process, *, fields: list[dict] | None = None) -> str:
|
||
"""流程把编号时机配成「存草稿就生成」或「新建就生成」时,替这张新草稿占一个号。
|
||
|
||
取号走 :func:`app.service.numbering.take`,与引擎发起时是同一本计数器:
|
||
先起草稿后发起、直接从接口发起、走到指定环节才补号,几条路共用一本账,
|
||
不会谁把流水号排回 1。代价照旧是**弃掉的草稿会跳号**,所以默认不开这两档。
|
||
|
||
``create`` 那一档平时走的是"打开填写页就先占号"(见
|
||
:func:`app.service.numbering.reserve`),存草稿时把那张凭条换成号交到这里;
|
||
没有凭条(比如直接从拟稿箱新建)就在这里自己占一个,别让草稿空着号。
|
||
"""
|
||
if numbering.timing_of(process)["at"] not in (numbering.TIMING_DRAFT, numbering.TIMING_CREATE):
|
||
return ""
|
||
shown = fields if fields is not None else form_fields(db, process)
|
||
return numbering.take(db, process.id, numbering.serial_rule_of(shown))
|
||
|
||
|
||
def build(
|
||
db: Session,
|
||
*,
|
||
process: models.Process,
|
||
actor,
|
||
data: dict | None = None,
|
||
title: str = "",
|
||
draft: models.Draft | None = None,
|
||
reserved: str = "",
|
||
) -> tuple[models.Draft, Inspection]:
|
||
"""算出草稿该长成什么样,**不落库**。
|
||
|
||
``reserved`` 是调用方手里已经有的那个号(「新建就生成」那张凭条换出来的),
|
||
存草稿时接过来用,不再另占一个。
|
||
|
||
``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())
|
||
# 编号时机配成「存草稿就生成」时,在这张草稿第一次落库这一刻占一个号,
|
||
# 之后反复保存沿用同一个号(跳号只可能来自被删掉的草稿,设计器里写明了这一代价)。
|
||
# 号先落在草稿行上,发起时由接口原样交给引擎,引擎不会再排第二个。
|
||
serial = str(draft.serial or "") if draft is not None else ""
|
||
if not serial:
|
||
# 已有号 > 手里那张凭条 > 这一档自己占一个;顺序反了就会一张草稿吃两个号
|
||
serial = str(reserved or "").strip()[:64] or reserve_serial(db, process, fields=fields)
|
||
row.serial = serial
|
||
if serial:
|
||
# 顺手填进表单那几格「单据编号」:拟稿箱与发起页当场就看得见自己的号,
|
||
# 也让标题里的 {单号} 在这一步就算得出真号,而不是等发起之后才补上。
|
||
inspection.data = autofill.fill_serial(inspection.data, fields, serial)
|
||
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.ref
|
||
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,
|
||
reserved: str = "",
|
||
) -> tuple[models.Draft, Inspection]:
|
||
"""建(或改)一张草稿。返回草稿本体和这次的数据体检结果。
|
||
|
||
调用方管事务:页面直接 commit,脚本可以攒着一起提交,开放平台也是自己 commit。
|
||
``reserved`` 是调用方凭条已经换来的那个号,原样接过来用(见 :func:`build`)。
|
||
"""
|
||
if check_startable:
|
||
guard_startable(db, process, actor)
|
||
row, inspection = build(
|
||
db, process=process, actor=actor, data=data, title=title, draft=draft, reserved=reserved
|
||
)
|
||
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)}
|