1896 lines
94 KiB
Python
1896 lines
94 KiB
Python
"""Process design time: categories, forms, processes, activities, routes."""
|
||
|
||
from __future__ import annotations
|
||
|
||
import ast
|
||
import copy
|
||
|
||
from fastapi import APIRouter, Depends, Query
|
||
from sqlalchemy import delete, func, or_, select
|
||
from sqlalchemy.orm import Session
|
||
|
||
from .. import models, parallel, schemas, serializers
|
||
from ..db import get_db
|
||
from ..deps import CurrentUser, actor_of, current_user, require_permission
|
||
from ..engine import definition as definition_module
|
||
from ..service import (autofill, dedupaudit, dicts, fetch, formruntime, linkfill, mapping, node_approve,
|
||
numbering, org,
|
||
quota, simulator, starters, terminate as terminate_service, threshold, titles)
|
||
from ..engine import engine, expressions
|
||
from ..envelope import bad_request, not_found, ok
|
||
from ..query import tri_state
|
||
|
||
router = APIRouter(tags=["design"])
|
||
|
||
|
||
# ------------------------------- categories ------------------------------
|
||
|
||
|
||
@router.get("/process/categories")
|
||
def list_categories(db: Session = Depends(get_db), _: CurrentUser = Depends(current_user)) -> dict:
|
||
rows = db.execute(
|
||
select(models.Category).order_by(models.Category.order_number, models.Category.name)
|
||
).scalars().all()
|
||
return ok([serializers.category(r) for r in rows])
|
||
|
||
|
||
@router.post("/process/categories", dependencies=[Depends(require_permission("design:category"))])
|
||
def create_category(body: schemas.CategoryBody, db: Session = Depends(get_db)) -> dict:
|
||
row = models.Category(
|
||
name=body.name, description=body.description,
|
||
order_number=body.order_number, enabled=body.enabled,
|
||
)
|
||
db.add(row)
|
||
db.commit()
|
||
return ok(serializers.category(row))
|
||
|
||
|
||
@router.put("/process/categories/{category_id}", dependencies=[Depends(require_permission("design:category"))])
|
||
def update_category(category_id: str, body: schemas.CategoryBody, db: Session = Depends(get_db)) -> dict:
|
||
row = db.get(models.Category, category_id)
|
||
if row is None:
|
||
raise not_found("分类不存在")
|
||
row.name = body.name
|
||
row.description = body.description
|
||
row.order_number = body.order_number
|
||
row.enabled = body.enabled
|
||
for process in db.execute(select(models.Process).where(models.Process.category == category_id)).scalars().all():
|
||
process.category_name = body.name
|
||
db.commit()
|
||
return ok(serializers.category(row))
|
||
|
||
|
||
@router.delete("/process/categories/{category_id}", dependencies=[Depends(require_permission("design:category"))])
|
||
def delete_category(category_id: str, db: Session = Depends(get_db)) -> dict:
|
||
row = db.get(models.Category, category_id)
|
||
if row is None:
|
||
raise not_found("分类不存在")
|
||
if db.execute(select(func.count(models.Process.id)).where(models.Process.category == category_id)).scalar():
|
||
raise bad_request("该分类下仍有流程")
|
||
db.delete(row)
|
||
db.commit()
|
||
return ok({"success": True})
|
||
|
||
|
||
# --------------------------------- forms ---------------------------------
|
||
|
||
|
||
FIELD_TYPES = {
|
||
# 基础录入
|
||
"text", "textarea", "number", "money", "date", "datetime", "time", "daterange",
|
||
"month", "months", "year", "timerange", "richtext",
|
||
"mobile", "email", "idcard", "url", "address", "location",
|
||
# 选择类(cascader:一个控件在层级字典里一路选到底,值是顶级到末级的字典项数组)
|
||
"select", "radio", "checkbox", "switch", "rate", "dept", "cascader", "week",
|
||
# 人员与附件
|
||
"user", "attachment", "image",
|
||
# 手写签名(存 PNG data URL)、关联审批单(存对方 job),
|
||
# 以及下拉选择(与下拉框同一只挑选器,候选来自外部数据源 / 别的流程的单据)
|
||
"signature", "relation", "picker",
|
||
# 系统自动带出
|
||
"auto",
|
||
# 流程标题:这一格的值就是 work.title,规则算出来的一切都写回它(见 service/titles.py)
|
||
"title",
|
||
# 计算与汇总:明细表(子表格)与公式字段,值由服务端算,见 service/formruntime.py
|
||
"table", "formula",
|
||
# 排版与占位
|
||
"divider", "description", "group", "spacer", "hidden",
|
||
# 外部页面:把别的业务系统的页面嵌进这一格,自己不产生值(docs/embed-page-field-design.md)
|
||
"embed",
|
||
# 标签页:把这张单切成几页,其中一页可以整页让给外部系统(docs/form-tabs-embed-design.md)
|
||
"tabs",
|
||
}
|
||
OPTION_FIELD_TYPES = {"select", "radio", "checkbox"}
|
||
#: 纯排版、没有值的类型:必填对它们没有任何可落地的判定,保存时挡下来。
|
||
#: 系统带出与公式计算不在此列——它们没有录入框,但设计者可以让它们「必填」,
|
||
#: 意思是这一格必须带得出 / 算得出值,判定在 formruntime.missing_required 里。
|
||
#: ``embed`` 也在这一列(它没有值,"必填"落不了地),但校验不放过它:它的 key 是环节字段
|
||
#: 权限的挂点,divider 那条"连字段名都不查"的捷径它不能走。
|
||
LAYOUT_ONLY_TYPES = {"divider", "description", "group", "spacer", "embed", "tabs"}
|
||
#: 不需要字段标题的类型:只有空白格(口径与前端 utils/formLayout.ts:LABELLESS_TYPES 一致)。
|
||
#: 它的标题上屏后一个字都不显示,硬要设计者编一句等于让人写废话;上一行那份
|
||
#: 「不能必填」的清单不一样——分组标题的 label 就是那行抬头,照旧得有。
|
||
LABELLESS_TYPES = {"spacer"}
|
||
#: 隐藏字段连输入框都不渲染,标了必填就是「必须填一个看不见也填不了的格子」,
|
||
#: 整张单直接提交不了,所以同样挡在保存这一步(设计器里这两个开关也是灰的)。
|
||
HIDDEN_FIELD_TYPE = "hidden"
|
||
|
||
#: 数字金额的展现配置:每类字段只认自己那一套,换了类型还留着上一类的写法,
|
||
#: 就会在新控件上悄悄生效(金额改成公式还带着中文大写就是这么来的)。
|
||
FORMAT_KEYS = ("numberFormat", "precision", "unit", "uppercase", "min", "max", "step")
|
||
FORMAT_OWNERS: dict[str, set[str]] = {
|
||
"number": {"numberFormat", "precision", "unit", "min", "max", "step"},
|
||
"money": {"numberFormat", "precision", "unit", "uppercase", "min", "max"},
|
||
"formula": {"numberFormat", "precision", "unit", "uppercase"},
|
||
# 评分的 max 是满星数,不是取值范围,别被当成数字格式收掉
|
||
"rate": {"max"},
|
||
}
|
||
|
||
#: 每类字段自带的「限制」配置:文本的字数与正则、附件的类型 / 个数 / 大小、空白格的高度。
|
||
#: 收法与 FORMAT_KEYS 一模一样——换了类型就收掉上一类留下的那几样。区别只在管的不是
|
||
#: "长什么样"而是"能不能填进去",所以另立一份,别混进数字金额那套展现格式里。
|
||
LIMIT_KEYS = ("maxLength", "pattern", "accept", "maxFiles", "maxSizeMb", "height")
|
||
LIMIT_OWNERS: dict[str, set[str]] = {
|
||
"text": {"maxLength", "pattern"},
|
||
"textarea": {"maxLength", "pattern"},
|
||
"richtext": {"maxLength", "pattern"},
|
||
"attachment": {"accept", "maxFiles", "maxSizeMb"},
|
||
"image": {"accept", "maxFiles", "maxSizeMb"},
|
||
"spacer": {"height"},
|
||
}
|
||
|
||
|
||
def clean_formats(content: object) -> dict:
|
||
"""按字段类型收掉不属于它的展现配置(明细列同理),返回一份新的表单内容。
|
||
|
||
设计器换类型时已经清过一遍,这里再兜一道:从接口、AI 起草或流程副本进来的表单
|
||
也得有同一个结果,否则上一个类型留下的格式会藏在新控件下面继续生效。
|
||
"""
|
||
if not isinstance(content, dict):
|
||
return {} if content is None else {"fields": []}
|
||
|
||
def clean(item: dict) -> dict:
|
||
fresh = dict(item)
|
||
kind = str(fresh.get("type") or "")
|
||
owned = FORMAT_OWNERS.get(kind, set())
|
||
for key in FORMAT_KEYS:
|
||
if key in fresh and key not in owned:
|
||
fresh.pop(key)
|
||
# 限制类配置同样按类型收:从接口 / AI 起草 / 流程副本进来的表单也走这一道
|
||
for key in LIMIT_KEYS:
|
||
if key in fresh and key not in LIMIT_OWNERS.get(kind, set()):
|
||
fresh.pop(key)
|
||
if isinstance(fresh.get("columns"), list):
|
||
fresh["columns"] = [clean(col) if isinstance(col, dict) else col for col in fresh["columns"]]
|
||
return fresh
|
||
|
||
fields = content.get("fields")
|
||
if not isinstance(fields, list):
|
||
return dict(content)
|
||
return {**content, "fields": [clean(item) if isinstance(item, dict) else item for item in fields]}
|
||
|
||
|
||
#: 每种候选来源各自那几格:换了来源,上一家那几格就不该再留在字段上。
|
||
SOURCE_OWNED_KEYS: dict[str, tuple[str, ...]] = {
|
||
dicts.SOURCE_MANUAL: ("options",),
|
||
dicts.SOURCE_DICT: ("dictCode", "cascadeFrom", "autoFill"),
|
||
dicts.SOURCE_PROCESS: (
|
||
"relationProcess", "relationStatuses", "relationScope", linkfill.LINK_FILL_KEY
|
||
),
|
||
dicts.SOURCE_DATA_SOURCE: ("dataSourceCode", formruntime.OPTION_ARGS_KEY),
|
||
}
|
||
_ALL_SOURCE_KEYS = tuple({key for keys in SOURCE_OWNED_KEYS.values() for key in keys})
|
||
|
||
|
||
def clean_option_source(content: object) -> dict:
|
||
"""按字段声明的候选来源收掉不属于它的配置(明细列同理),返回一份新的表单内容。
|
||
|
||
从字典换成外部数据源之后,老的 ``dictCode`` 要是还躺在字段上:后端读候选优先认的就是
|
||
字典编码,于是界面显示新源搜出来的候选、提交时按老字典判越界——同一格两套口径。
|
||
设计器换来源时已经清过一遍,这里兜的是接口直传、AI 起草和流程副本那几条进来的路。
|
||
只动**明写过** ``optionSource`` 的字段:老表单没写这个字段,按老写法推出来的来源
|
||
就是它自己的来源,那时候清别的键等于替历史做主。
|
||
"""
|
||
if not isinstance(content, dict):
|
||
return {} if content is None else {"fields": []}
|
||
|
||
def clean(item: dict, top: bool = True) -> dict:
|
||
fresh = dict(item)
|
||
field_type = str(fresh.get("type") or "")
|
||
# 关联单据带出只挂在主表字段上:明细列里那一格挂的也可以是单据,但「这一行的那张
|
||
# 单 → 另一张表的几行」在界面上没人能预期,那一层要带数据走「从另一个流程带数据」。
|
||
# 放在最前面是因为下面那两条捷径会提前 return,残骸照样得收干净。
|
||
if not top:
|
||
fresh.pop(linkfill.LINK_FILL_KEY, None)
|
||
# 级联选择只挂层级字典:``dictCode`` / ``cascadeFrom`` 是它自己的配置,不是"候选来源"
|
||
# 那四类留下的残骸。它不在 source_kinds_of 的清单里,跟着下面"这一类型挑不了来源就
|
||
# 整份撤掉"会被连 dictCode 一起抹掉——validate_schema 又要求级联必须挂字典,
|
||
# 结果是凡是带级联字段的表单(含明细列)一律存不下去。
|
||
if field_type == formruntime.CASCADER_TYPE:
|
||
fresh.pop("optionSource", None)
|
||
fresh.pop(dicts.OPTION_ROUTES_KEY, None)
|
||
return fresh
|
||
# 多选月份:候选是那一年那 12 个月,谈不上候选来源那四类,但它共用同一套「挑选方式」
|
||
# (字段上的 ``pickerStyle``:下拉多选 / 弹出框多选 / 平铺点选)。它不在
|
||
# source_kinds_of 的清单里,跟着下面那句"没有来源就整份撤掉"会把挑选方式一起抹掉——
|
||
# 于是配的人挑了弹出框、存一次就默默掉回下拉。
|
||
if field_type == formruntime.MONTHS_TYPE:
|
||
fresh.pop("optionSource", None)
|
||
if str(fresh.get("pickerStyle") or "").strip() not in formruntime.MONTHS_STYLES:
|
||
fresh.pop("pickerStyle", None)
|
||
return fresh
|
||
declared = str(fresh.get("optionSource") or "").strip()
|
||
kinds = dicts.source_kinds_of(field_type)
|
||
# 条件路由清单先收:认不出的来源、配到一半的空条目、第 9 条起多出来的都丢掉,
|
||
# 每条只留属于它那一种来源的那几格(口径在 ``dicts.clean_routes``)。
|
||
# 放在「来源挑错了就整份撤掉」那句之前——老写法没写 ``optionSource`` 的字段也能挂路由,
|
||
# 跟着那条 return 走的话这份清单会原样落库,没人洗过。
|
||
if not kinds:
|
||
fresh.pop(dicts.OPTION_ROUTES_KEY, None)
|
||
elif dicts.OPTION_ROUTES_KEY in fresh:
|
||
cleaned_routes = dicts.clean_routes(fresh)
|
||
if cleaned_routes:
|
||
fresh[dicts.OPTION_ROUTES_KEY] = cleaned_routes
|
||
else:
|
||
fresh.pop(dicts.OPTION_ROUTES_KEY, None)
|
||
# 「带出的值不在候选里也收下」只属于有候选来源的那几类字段,而且只认真布尔值:
|
||
# 一个文本框带着它、或一个字符串 "true" 落进来,读的人都得猜这是哪一档
|
||
if not kinds or not isinstance(fresh.get(dicts.ALLOW_OUTSIDE_VALUE_KEY), bool):
|
||
fresh.pop(dicts.ALLOW_OUTSIDE_VALUE_KEY, None)
|
||
if declared not in kinds:
|
||
# 这一类字段没有候选来源可言(文本框、明细表……),或来源本身挑错了:整份撤掉,
|
||
# 退回它自己的老口径,别让一个不认识的来源把候选配置带进下一个控件里。
|
||
fresh.pop("optionSource", None)
|
||
if not kinds:
|
||
for key in _ALL_SOURCE_KEYS:
|
||
fresh.pop(key, None)
|
||
fresh.pop("pickerStyle", None)
|
||
fresh.pop("optionMap", None)
|
||
fresh.pop("picker", None)
|
||
fresh.pop("multiple", None)
|
||
return fresh
|
||
owned = SOURCE_OWNED_KEYS[declared]
|
||
if declared != dicts.SOURCE_DICT and dicts.dict_route_codes(fresh):
|
||
# 字段自己挂的不是字典,但**某一条候选来源是字典**:那一条命中时带的就是它那本的附加值,
|
||
# ``autoFill`` 是这一档唯一的配法(外部数据源那一条自己带 ``fill``),不能当残骸清掉。
|
||
owned = owned + (dicts.AUTO_FILL_KEY,)
|
||
for key in _ALL_SOURCE_KEYS:
|
||
if key not in owned:
|
||
fresh.pop(key, None)
|
||
# 「关联带出」那几格跟着来源走:写歪的规则、认不出的合并档在这儿收干净,
|
||
# 一条有效规则都不剩时整格抹掉(留一份空 rules 只会让下一任以为配过什么)
|
||
if declared == dicts.SOURCE_PROCESS and linkfill.LINK_FILL_KEY in fresh:
|
||
cleaned_fill = linkfill.clean(fresh.get(linkfill.LINK_FILL_KEY))
|
||
if cleaned_fill:
|
||
fresh[linkfill.LINK_FILL_KEY] = cleaned_fill
|
||
else:
|
||
fresh.pop(linkfill.LINK_FILL_KEY, None)
|
||
style = str(fresh.get("pickerStyle") or "").strip()
|
||
# 装不下的姿势只剩一种:搜出来的候选铺不成一排(手上只有搜到的那一页)。
|
||
# 一串值配下拉是成立的——那只下拉带勾选框,挑中的几条挂在框里(``Select`` 的 multiple),
|
||
# 以前这里会把 dropdown 撤掉,等于把多选下拉这一档从界面上擦了一遍。
|
||
if style == "inline" and declared in dicts.SEARCHED_SOURCES:
|
||
fresh.pop("pickerStyle", None)
|
||
elif style and style not in dicts.PICKER_STYLES:
|
||
fresh.pop("pickerStyle", None)
|
||
# 「可以选好几个」只属于那两格下拉组件与多选、关联审批单;配不上一律撤掉,
|
||
# 否则一个文本字段带着它,下一任配的人无从知道这一格到底存不存一串值
|
||
if not dicts.holds_list_value(fresh):
|
||
fresh.pop("multiple", None)
|
||
# 「各档看哪几列」跟「显示 / 存值」一样是逐来源写的:收一遍,全跟默认一样的不留
|
||
cleaned_picker = dicts.clean_picker(fresh)
|
||
if cleaned_picker is None:
|
||
fresh.pop("picker", None)
|
||
else:
|
||
fresh["picker"] = cleaned_picker
|
||
# 「显示哪一列、存哪一列」跟着来源走:列名对不上这一来源的不认(退回默认列),
|
||
# 跟默认一模一样的那份不留——冗余配置只会让下一任配的人以为它有什么特别的
|
||
normalized = dicts.normalize_option_map(fresh)
|
||
if normalized is None:
|
||
fresh.pop("optionMap", None)
|
||
else:
|
||
fresh["optionMap"] = normalized
|
||
return fresh
|
||
|
||
def walk(item: dict, top: bool = True) -> dict:
|
||
fresh = clean(item, top=top)
|
||
if isinstance(fresh.get("columns"), list):
|
||
fresh["columns"] = [
|
||
walk(col, top=False) if isinstance(col, dict) else col for col in fresh["columns"]
|
||
]
|
||
return fresh
|
||
|
||
fields = content.get("fields")
|
||
if not isinstance(fields, list):
|
||
return dict(content)
|
||
return {**content, "fields": [walk(item) if isinstance(item, dict) else item for item in fields]}
|
||
|
||
|
||
# The sheet designer lays fields out on a 12-column grid; older forms only ever
|
||
# stored 1 or 2 columns, which the renderer still folds into the same grid.
|
||
GRID_COLS = 12
|
||
LEGACY_LAYOUT_COLUMNS = (1, 2, GRID_COLS)
|
||
|
||
|
||
def _positive_int(value: object) -> bool:
|
||
return isinstance(value, int) and not isinstance(value, bool) and value >= 1
|
||
|
||
|
||
def formula_cycle_problems(sources: dict[str, str]) -> list[str]:
|
||
"""公式字段互相引用(A 由 B 算、B 又由 A 算)得在设计阶段就拦住。
|
||
|
||
运行时按表单顺序算一遍就过去了,环上的字段会静默拿到旧值,
|
||
这种错到审批页根本看不出为什么数字不对,所以宁可保存不下来。
|
||
"""
|
||
if len(sources) < 2:
|
||
return []
|
||
deps: dict[str, set[str]] = {}
|
||
for key, source in sources.items():
|
||
try:
|
||
tree = ast.parse((source or "None").strip() or "None", mode="eval")
|
||
except SyntaxError:
|
||
deps[key] = set()
|
||
continue
|
||
names = {node.id for node in ast.walk(tree) if isinstance(node, ast.Name)}
|
||
deps[key] = {other for other in sources if other != key and other in names}
|
||
|
||
problems: list[str] = []
|
||
state: dict[str, int] = {}
|
||
|
||
def visit(node: str, trail: list[str]) -> None:
|
||
mark = state.get(node, 0)
|
||
if mark == 2:
|
||
return
|
||
if mark == 1:
|
||
chain = trail[trail.index(node):] + [node] if node in trail else [node]
|
||
problems.append("计算公式互相引用:" + " -> ".join(chain))
|
||
return
|
||
state[node] = 1
|
||
for nxt in sorted(deps.get(node, ())):
|
||
visit(nxt, trail + [node])
|
||
state[node] = 2
|
||
|
||
for key in sources:
|
||
visit(key, [])
|
||
return problems
|
||
|
||
|
||
def schema_problems(content: dict, db=None) -> list[str]:
|
||
"""设计器保存前的表单校验:字段本身 + 明细表结构 + 公式引用关系。
|
||
|
||
``db`` 一路传到 ``option_source_problems``:候选来源指向的那张源被删了、停用了、
|
||
配成了取一个值的,都得在保存这一刻说清楚,而不是等填单的人点开一个空下拉。
|
||
"""
|
||
body = content or {}
|
||
fields = [item for item in (body.get("fields") or []) if isinstance(item, dict)]
|
||
problems = formruntime.validate_schema(fields, db)
|
||
sources = {
|
||
str(item.get("key") or "").strip(): str(item.get("formula") or "")
|
||
for item in fields
|
||
if str(item.get("type") or "") == "formula" and str(item.get("key") or "").strip()
|
||
}
|
||
problems.extend(formula_cycle_problems(sources))
|
||
return problems
|
||
|
||
|
||
def form_problems(content: dict, db: Session | None = None) -> list[str]:
|
||
"""Designer-level problems that would break the form at approval time.
|
||
|
||
Both the write endpoints and the ``/validate`` preview use this, so a form
|
||
that passes the preview can always be saved.
|
||
"""
|
||
body = content or {}
|
||
fields = body.get("fields")
|
||
if fields is None:
|
||
fields = []
|
||
if not isinstance(fields, list):
|
||
return ["表单字段必须是数组"]
|
||
|
||
problems: list[str] = []
|
||
seen: dict[str, int] = {}
|
||
title_at = 0
|
||
for index, item in enumerate(fields, start=1):
|
||
if not isinstance(item, dict):
|
||
problems.append(f"第 {index} 个字段格式不正确")
|
||
continue
|
||
ftype = str(item.get("type") or "").strip()
|
||
if ftype not in FIELD_TYPES:
|
||
problems.append(f"第 {index} 个字段类型无效:{ftype or '未设置'}")
|
||
continue
|
||
if item.get("required") and (ftype in LAYOUT_ONLY_TYPES or ftype == HIDDEN_FIELD_TYPE):
|
||
shown = str(item.get("label") or item.get("key") or "").strip() or "未命名"
|
||
reason = "不参与填写" if ftype == HIDDEN_FIELD_TYPE else "只用于展示"
|
||
problems.append(f"第 {index} 个字段「{shown}」{reason},不能设为必填")
|
||
if ftype == "divider":
|
||
# 分隔线只是排版,不参与字段名/选项等校验
|
||
continue
|
||
key = str(item.get("key") or "").strip()
|
||
label = str(item.get("label") or "").strip()
|
||
if not label and ftype not in LABELLESS_TYPES:
|
||
problems.append(f"第 {index} 个字段缺少字段标题")
|
||
if not key:
|
||
problems.append(f"第 {index} 个字段缺少字段名")
|
||
elif key in seen:
|
||
problems.append(f"字段名「{key}」重复(第 {seen[key]} 个与第 {index} 个)")
|
||
else:
|
||
seen[key] = index
|
||
# 选项有四种来源:字典、别的流程的单据、外部数据源都不用在表单里抄一份选项,
|
||
# 只有「手填」这一条真空着手会害得填单那一格一个能点的都没有。
|
||
# 字典与数据源那两条选了却没挑到底,由 validate_schema 报「还没选字典 / 还没选源」。
|
||
# 挂了候选来源清单的那一格也不算空着手:候选来自清单里那几条,字段自己这一份留给
|
||
# 「一条都不成立」时兜底(先选分类再问那一家,分类没选时本来就没得挑)。
|
||
if ftype in OPTION_FIELD_TYPES \
|
||
and dicts.source_kind_of(item) == dicts.SOURCE_MANUAL \
|
||
and not (item.get("options") or []) \
|
||
and not dicts.routes_of(item):
|
||
problems.append(f"第 {index} 个字段「{label or key}」未配置任何选项")
|
||
if ftype == "auto":
|
||
source = str(item.get("auto") or "").strip()
|
||
if not source:
|
||
problems.append(f"第 {index} 个字段「{label or key}」还没选择要带出的系统值")
|
||
elif source not in autofill.ALL_KEYS:
|
||
problems.append(f"第 {index} 个字段「{label or key}」的系统值不支持:{source}")
|
||
# 生成规则写在字段上(编号的前缀/日期段/位数/归零周期,日期的时间格式,
|
||
# 其余系统值的前后缀):写歪了当场挡下来,别等发起时才看见编号长得不对。
|
||
problems.extend(
|
||
numbering.problems(item.get(numbering.FIELD_RULE_KEY), f"第 {index} 个字段「{label or key}」的生成规则")
|
||
)
|
||
if ftype == titles.TITLE_FIELD_TYPE:
|
||
# 一张表单只留一个标题字段:两个字段都说自己是标题,work.title 只有一个。
|
||
mode = str(item.get("titleMode") or "rule").strip()
|
||
if mode not in titles.TITLE_FIELD_MODES:
|
||
problems.append(f"第 {index} 个字段「{label or key}」的标题生成方式不支持:{mode}")
|
||
# 字段自带的标题规则用流程那把同一把尺子量:写坏了在保存时就拦下来,
|
||
# 别等发起人点「发起流程」才发现标题生成失败——那时单子已经发出去了。
|
||
rule = item.get(titles.FIELD_RULE_KEY)
|
||
if rule is not None and not isinstance(rule, dict):
|
||
problems.append(f"第 {index} 个字段「{label or key}」的标题规则格式不对")
|
||
elif isinstance(rule, dict) and rule:
|
||
try:
|
||
titles.clean_config(rule)
|
||
except ValueError as exc:
|
||
problems.append(f"第 {index} 个字段「{label or key}」的标题规则有问题:{exc}")
|
||
if title_at:
|
||
problems.append(f"流程标题字段只能有一个(第 {title_at} 个与第 {index} 个)")
|
||
else:
|
||
title_at = index
|
||
if ftype == "rate":
|
||
stars = item.get("max")
|
||
if isinstance(stars, int) and not isinstance(stars, bool) and not 1 <= stars <= 10:
|
||
problems.append(f"第 {index} 个字段「{label or key}」的评分星级要在 1-10 之间")
|
||
low, high = item.get("min"), item.get("max")
|
||
if isinstance(low, (int, float)) and isinstance(high, (int, float)) and not isinstance(low, bool) \
|
||
and not isinstance(high, bool) and low > high:
|
||
problems.append(f"第 {index} 个字段「{label or key}」的最小值大于最大值")
|
||
|
||
if ftype == "formula":
|
||
source = str(item.get("formula") or "").strip()
|
||
if not source:
|
||
problems.append(f"第 {index} 个字段「{label or key}」还没有填写计算公式")
|
||
else:
|
||
error = expressions.validate_script(source)
|
||
if error:
|
||
problems.append(f"第 {index} 个字段「{label or key}」的公式有问题:{error}")
|
||
if ftype == "money" and item.get("uppercase") not in (None, True, False):
|
||
problems.append(f"第 {index} 个字段「{label or key}」的大写金额开关格式不对")
|
||
|
||
# 普通字段的自动带出(申请人 / 申请部门 / 审批人…):来源写在这类字段带不出来的值上,
|
||
# 表单存得下来、发起时那一格却永远是空的。保存时挡下来,与前端 utils/autoPreset 同口径。
|
||
problems.extend(autofill.problems([item for item in fields if isinstance(item, dict)]))
|
||
# 额度控制:引用的定义在不在、三个数写去哪、金额取自哪个字段——配错了当场挡下来,
|
||
# 别等发起人点提交才知道那一笔额度根本没生效(前端 utils/formLayout 镜像同一把尺子)。
|
||
problems.extend(quota.problems([item for item in fields if isinstance(item, dict)], db))
|
||
# 外部取数同理:数据源存不存在、入参引用的字段在不在、带出的键有没有声明过。
|
||
problems.extend(fetch.problems([item for item in fields if isinstance(item, dict)], db))
|
||
problems.extend(threshold.problems([item for item in fields if isinstance(item, dict)]))
|
||
# 明细表的列结构与公式引用关系交给共用校验器,前端镜像同一套规则。
|
||
problems.extend(schema_problems(body, db))
|
||
|
||
layout = body.get("layout") or {}
|
||
if not isinstance(layout, dict):
|
||
return problems
|
||
columns = layout.get("columns", 2)
|
||
if columns not in LEGACY_LAYOUT_COLUMNS:
|
||
problems.append(f"布局列数只支持 {GRID_COLS} 列网格(旧表单的 1 栏、2 栏仍可打开)")
|
||
return problems
|
||
if columns == GRID_COLS:
|
||
for index, item in enumerate(fields, start=1):
|
||
if not isinstance(item, dict):
|
||
continue
|
||
for name in ("row", "col"):
|
||
value = item.get(name)
|
||
if value is not None and not _positive_int(value):
|
||
problems.append(f"第 {index} 个字段的{name}必须是正整数")
|
||
span = item.get("span")
|
||
if span is not None and (not _positive_int(span) or span > GRID_COLS):
|
||
problems.append(f"第 {index} 个字段的宽度需在 1-{GRID_COLS} 列之间")
|
||
col, width = item.get("col"), item.get("span")
|
||
if _positive_int(col) and _positive_int(width) and col + width - 1 > GRID_COLS:
|
||
problems.append(f"第 {index} 个字段超出了 {GRID_COLS} 列网格")
|
||
return problems
|
||
|
||
|
||
def _form_rank(row: models.FormElement, process_id: str, default_id: str) -> int:
|
||
"""设计器下拉的排序口径:本流程默认表单 → 本流程表单 → 通用表单 → 别的流程的表单。
|
||
|
||
只做排序,不做过滤:表单是独立资产,别的流程的表单照样能选,
|
||
只是排在后面,取第一条时仍然是原来那张。
|
||
"""
|
||
if row.id == default_id:
|
||
return 0
|
||
if row.process == process_id:
|
||
return 1
|
||
return 2 if not row.process else 3
|
||
|
||
|
||
def _form_usages(db: Session, form_id: str = "") -> dict[str, list[dict]]:
|
||
"""反查「这张表单正被哪些流程用着」,表单侧只读这一份口径。
|
||
|
||
表单不再靠 ``oa_form.process`` 记归属,真正的引用只有两处:
|
||
流程默认表单 ``process.latest_form`` 与环节自己的 ``activity.form``。
|
||
"""
|
||
grouped: dict[str, dict[str, dict]] = {}
|
||
|
||
def entry(bound_form: str, process_id: str, process_name: str) -> dict:
|
||
return grouped.setdefault(bound_form, {}).setdefault(
|
||
process_id, {"id": process_id, "name": process_name, "default": False, "activities": []}
|
||
)
|
||
|
||
process_stmt = (
|
||
select(models.Process.id, models.Process.name, models.Process.latest_form)
|
||
.order_by(models.Process.name, models.Process.id)
|
||
)
|
||
activity_stmt = (
|
||
select(models.Activity.form, models.Activity.name, models.Process.id, models.Process.name)
|
||
.join(models.Process, models.Process.id == models.Activity.process)
|
||
.where(models.Activity.form != "")
|
||
.order_by(models.Activity.order_number, models.Activity.id)
|
||
)
|
||
if form_id:
|
||
process_stmt = process_stmt.where(models.Process.latest_form == form_id)
|
||
activity_stmt = activity_stmt.where(models.Activity.form == form_id)
|
||
|
||
for process_id, process_name, latest_form in db.execute(process_stmt).all():
|
||
if latest_form:
|
||
entry(latest_form, process_id, process_name)["default"] = True
|
||
for bound_form, activity_name, process_id, process_name in db.execute(activity_stmt).all():
|
||
item = entry(bound_form, process_id, process_name)
|
||
if activity_name and activity_name not in item["activities"]:
|
||
item["activities"].append(activity_name)
|
||
return {key: list(items.values()) for key, items in grouped.items()}
|
||
|
||
|
||
@router.get("/process/forms")
|
||
def list_forms(
|
||
db: Session = Depends(get_db),
|
||
_: CurrentUser = Depends(current_user),
|
||
process: str = Query(""),
|
||
) -> dict:
|
||
"""表单清单:一张都不藏,``process`` 只管排序,不做过滤。
|
||
|
||
建表单不用先想着给谁用——流程设计器要选就能在这儿选到。
|
||
``process`` 传了就只影响顺序,第一条仍是这条流程自己的表单,
|
||
发起页「取第一条兜底渲染」的老口径不受影响。
|
||
"""
|
||
rows = db.execute(
|
||
select(models.FormElement).order_by(models.FormElement.order_number, models.FormElement.name)
|
||
).scalars().all()
|
||
default_id = ""
|
||
if process:
|
||
default_row = db.get(models.Process, process)
|
||
default_id = default_row.latest_form if default_row else ""
|
||
rows = sorted(rows, key=lambda item: (_form_rank(item, process, default_id), item.order_number, item.name))
|
||
usages = _form_usages(db)
|
||
return ok([serializers.form(row, used_by=usages.get(row.id, [])) for row in rows])
|
||
|
||
|
||
@router.post("/process/forms", dependencies=[Depends(require_permission("design:form"))])
|
||
def create_form(body: schemas.FormBody, user: CurrentUser = Depends(current_user), db: Session = Depends(get_db)) -> dict:
|
||
content = clean_option_source(clean_formats(body.content))
|
||
problems = form_problems(content, db)
|
||
if problems:
|
||
raise bad_request(problems[0])
|
||
row = models.FormElement(
|
||
name=body.name, alias=body.alias, description=body.description, process=body.process or "",
|
||
content=content, editable=body.editable, order_number=body.order_number, person=user.person_id,
|
||
)
|
||
db.add(row)
|
||
db.commit()
|
||
# 新建这一刻还没有流程引用它,但表单载荷永远带 used_by,前端不用分情况猜。
|
||
return ok(serializers.form(row, used_by=_form_usages(db, row.id).get(row.id, [])))
|
||
|
||
|
||
@router.get("/process/forms/{form_id}", dependencies=[Depends(current_user)])
|
||
def get_form(form_id: str, db: Session = Depends(get_db)) -> dict:
|
||
row = db.get(models.FormElement, form_id)
|
||
if row is None:
|
||
raise not_found("表单不存在")
|
||
return ok(serializers.form(row, used_by=_form_usages(db, form_id).get(form_id, [])))
|
||
|
||
|
||
@router.put("/process/forms/{form_id}", dependencies=[Depends(require_permission("design:form"))])
|
||
def update_form(form_id: str, body: schemas.FormBody, db: Session = Depends(get_db)) -> dict:
|
||
row = db.get(models.FormElement, form_id)
|
||
if row is None:
|
||
raise not_found("表单不存在")
|
||
content = clean_option_source(clean_formats(body.content))
|
||
problems = form_problems(content, db)
|
||
if problems:
|
||
raise bad_request(problems[0])
|
||
changed = row.content != content
|
||
row.name = body.name
|
||
row.alias = body.alias
|
||
row.description = body.description
|
||
# 不传就当作没改归属:表单设计器不再摆这个选择器,老数据里「某流程自建自用的表单」
|
||
# 不能被一次普通的保存顺手改成通用,否则删流程时的清理与复制都会跟着变味。
|
||
if body.process is not None:
|
||
row.process = body.process
|
||
row.editable = body.editable
|
||
row.order_number = body.order_number
|
||
if changed:
|
||
row.content = content
|
||
row.version = (row.version or 1) + 1
|
||
db.commit()
|
||
return ok(serializers.form(row, used_by=_form_usages(db, form_id).get(form_id, [])))
|
||
|
||
|
||
@router.post("/process/form-title/variables")
|
||
def form_title_variables(
|
||
body: schemas.FormTitleVariablesBody,
|
||
db: Session = Depends(get_db),
|
||
_: CurrentUser = Depends(current_user),
|
||
) -> dict:
|
||
"""表单设计器要用的标题变量清单 + 样例数据。
|
||
|
||
规则挪到表单字段上之后,配规则的人手上多半还没有流程(表单可以先建好再挂),
|
||
所以这套变量不能只挂在流程下面。设计器把画布上那份**还没保存**的字段一起递进来,
|
||
新建的表单、刚拖进来还没保存的字段也都当场能点成变量。
|
||
变量口径仍由 ``service/titles.py`` 一个人说了算,前端不许自己再拼一份变量表。
|
||
"""
|
||
try:
|
||
return ok(
|
||
titles.form_variables(
|
||
db, body.form, fields=body.fields or None, name=body.name
|
||
)
|
||
)
|
||
except ValueError as exc:
|
||
raise not_found(str(exc)) from exc
|
||
|
||
|
||
@router.post("/process/form-serial/preview")
|
||
def form_serial_preview(
|
||
body: schemas.FormSerialPreviewBody,
|
||
db: Session = Depends(get_db),
|
||
_: CurrentUser = Depends(current_user),
|
||
) -> dict:
|
||
"""表单设计器的编号预览:按画布上这份规则算出「下一个编号会长成什么样」。
|
||
|
||
只读不占号——设计者改一次前缀就看掉一个流水号是不可接受的。流程由表单反查,
|
||
表单还没挂流程时按「本期第一个」给个样子,规则本身照样当场见效。
|
||
"""
|
||
if body.auto_rule is not None:
|
||
rule = numbering.normalise_rule(body.auto_rule)
|
||
elif body.fields:
|
||
rule = numbering.serial_rule_of(body.fields)
|
||
else:
|
||
rule = numbering.serial_rule_of(autofill.form_fields(db, body.form))
|
||
process = titles.process_of_form(db, body.form)
|
||
return ok(numbering.peek(db, str(getattr(process, "id", "") or ""), rule))
|
||
|
||
|
||
@router.post("/process/form-title/preview")
|
||
def form_title_preview(
|
||
body: schemas.FormTitlePreviewBody,
|
||
user: CurrentUser = Depends(current_user),
|
||
db: Session = Depends(get_db),
|
||
) -> dict:
|
||
"""表单设计器的标题实时预览:规则还在草稿里、表单还没落库,也先看得到效果。
|
||
|
||
走的是发起时同一份 ``titles.preview``,流程设计器、发起页、引擎看到的是同一套口径。
|
||
"""
|
||
try:
|
||
return ok(
|
||
titles.form_preview(
|
||
db, body.form, body.title_config,
|
||
fields=body.fields or None, name=body.name,
|
||
data=body.data, actor=actor_of(user), use_sample=body.use_sample,
|
||
)
|
||
)
|
||
except ValueError as exc:
|
||
raise not_found(str(exc)) from exc
|
||
|
||
|
||
def _inherit_form(default_form: str, form_id: str) -> str:
|
||
"""环节自己挑的表单和流程默认表单是同一张时,收回成「沿用」。
|
||
|
||
运行时本来就是 ``activity.form or 默认表单``,所以这一收不改任何行为,只是把
|
||
「每个环节都把默认表单再点一遍」这种噪音挡在设计数据之外:默认表单只定一次,
|
||
环节上要么空着(沿用),要么真有一张不一样的。保存设计、复制流程都会顺带收敛,
|
||
界面也就能一直如实显示「谁沿用了、谁单独指定」。
|
||
"""
|
||
return "" if form_id and default_form and form_id == default_form else form_id
|
||
|
||
|
||
def _use_default_form(db: Session, process: models.Process, form_id: str) -> None:
|
||
"""把这张表单设成流程的默认表单,只写流程这一侧。
|
||
|
||
以前绑定时会顺手把 ``form.process`` 也改成这条流程,等于"一绑定就归它",
|
||
同一张表单别家流程就选不到了。表单是独立资产,归属与可见性都不该被
|
||
一次绑定动作改动;"谁在用" 交给 ``_form_usages`` 从真实引用反查。
|
||
"""
|
||
form_row = db.get(models.FormElement, form_id) if form_id else None
|
||
process.latest_form = form_row.id if form_row else ""
|
||
process.latest_form_name = form_row.name if form_row else ""
|
||
|
||
|
||
def _form_usage(db: Session, form_id: str) -> str:
|
||
"""这张表单正被谁用着;删除拦截和提示语共用一份口径。
|
||
|
||
与 ``used_by`` 是同一份反查。表单可以同时被多条流程选走,所以这里得按
|
||
「一串使用方」说话:早先一条流程只认一张默认表单,随手 ``scalar_one_or_none``
|
||
够用,共用之后它会直接抛 MultipleResultsFound,把删除拦阻变成 500。
|
||
"""
|
||
usages = _form_usages(db, form_id).get(form_id, [])
|
||
if not usages:
|
||
return ""
|
||
shown = usages[:3]
|
||
parts = []
|
||
for item in shown:
|
||
where = []
|
||
if item["default"]:
|
||
where.append("默认表单")
|
||
if item["activities"]:
|
||
where.append("环节「" + "、".join(item["activities"]) + "」")
|
||
parts.append(f"流程「{item['name']}」的" + "与".join(where))
|
||
text = ";".join(parts)
|
||
if len(usages) > len(shown):
|
||
text += f";等 {len(usages)} 条流程"
|
||
return text
|
||
@router.delete("/process/forms/{form_id}", dependencies=[Depends(require_permission("design:form"))])
|
||
def delete_form(form_id: str, db: Session = Depends(get_db)) -> dict:
|
||
row = db.get(models.FormElement, form_id)
|
||
if row is None:
|
||
raise not_found("表单不存在")
|
||
usage = _form_usage(db, form_id)
|
||
if usage:
|
||
raise bad_request(f"表单正被{usage}使用,不能删除")
|
||
db.delete(row)
|
||
db.commit()
|
||
return ok({"success": True})
|
||
|
||
|
||
@router.post("/process/forms/validate")
|
||
def validate_form(
|
||
body: dict, db: Session = Depends(get_db), _: CurrentUser = Depends(require_permission("design:form"))
|
||
) -> dict:
|
||
problems = form_problems((body or {}).get("content") or {}, db)
|
||
return ok({"valid": not problems, "problems": problems})
|
||
|
||
|
||
# ------------------------------- processes -------------------------------
|
||
|
||
|
||
@router.get("/process/processes")
|
||
def list_processes(
|
||
db: Session = Depends(get_db),
|
||
user: CurrentUser = Depends(current_user),
|
||
category: str = Query(""),
|
||
keyword: str = Query(""),
|
||
enabled: str = Query(""),
|
||
mine: str = Query(""),
|
||
startable: str = Query(""),
|
||
with_definition: bool = Query(True, description="0=不回设计稿(canvas 等四列回空对象),清单页用它"),
|
||
count_scope: str = Query("", description="mine=在途/办结只算本人发起的单(发起页用它),留空是全流程口径"),
|
||
) -> dict:
|
||
"""流程清单。
|
||
|
||
``startable=1`` 只留当前这个人能发起的流程:发起页与工作台用它,免得把发不起的
|
||
也列出来、点进去才弹一句没权限。设计器不传这个参数,照样看全部。
|
||
每条都带回 ``startable``,界面上想标「限 X 人发起」也够用。
|
||
|
||
``running_count`` / ``completed_count`` 默认是**这条流程在全系统**的在途数与办结数,
|
||
设计器的流程清单要的就是这个——那里看的是这条流程跑得怎么样。带
|
||
``count_scope=mine`` 换成只算当前这个人发起的单(口径与「我发起的」列表同一条,
|
||
见 ``app.api.runtime._created_clause``):发起页上那两个数字是给人挑流程当参考的,
|
||
别人在这条流程上压了三张单,对点进去的人毫无意义,读起来还像是自己已经排到了队尾。
|
||
管理员也按本人算,这一页问的是"我"。
|
||
|
||
设计稿(``canvas`` / ``data_template`` / ``approval_config`` / ``title_config``)默认照样
|
||
给,带 ``with_definition=0`` 才省:这一页几乎被每个界面的筛选器拉一次(发起页、待办、
|
||
监控、统计都拉),而画布只有设计器和发起页在用,它们本来就走
|
||
``GET /process/processes/{id}`` 单独取。清单里逐条发画布等于让报文跟着流程数量线性
|
||
长,前端那几处调用都已经带上 ``with_definition=0``;默认值留着是给可能的老调用方,
|
||
带 0 的时候库里那几列也压根不查(见 serializers.process_list_defer)。
|
||
"""
|
||
stmt = select(models.Process)
|
||
if not with_definition:
|
||
stmt = stmt.options(*serializers.process_list_defer())
|
||
if category:
|
||
stmt = stmt.where(models.Process.category == category)
|
||
if keyword:
|
||
like = f"%{keyword}%"
|
||
stmt = stmt.where(or_(models.Process.name.like(like), models.Process.alias.like(like)))
|
||
enabled_flag = tri_state(enabled)
|
||
if enabled_flag is not None:
|
||
stmt = stmt.where(models.Process.enabled.is_(enabled_flag))
|
||
if mine == "1":
|
||
stmt = stmt.where(models.Process.creator == user.person_id)
|
||
if not user.is_admin:
|
||
stmt = stmt.where(models.Process.enabled.is_(True))
|
||
rows = db.execute(stmt.order_by(models.Process.order_number, models.Process.name)).scalars().all()
|
||
can_start = starters.startable_map(
|
||
db, rows,
|
||
identities=None if user.is_admin else starters.actor_identities(db, user),
|
||
is_admin=user.is_admin,
|
||
)
|
||
wanted = tri_state(startable)
|
||
if wanted is not None:
|
||
rows = [row for row in rows if bool(can_start.get(row.id)) == wanted]
|
||
# 在办数与办结数各查一张表,互不相干:并起来问只等一趟到库的来回。
|
||
# 收成本人口径时两张表都走 creator_identity 等值——它正好是
|
||
# idx_oa_work_creator / idx_oa_work_completed_creator 的前缀,加这个筛子不会把分组
|
||
# 统计退化成全表扫,反倒是少扫一大截。
|
||
mine_only = count_scope.strip().lower() == "mine"
|
||
|
||
def running_counts(session: Session):
|
||
stmt = select(models.Work.process, func.count(models.Work.id)).group_by(models.Work.process)
|
||
if mine_only:
|
||
stmt = stmt.where(models.Work.creator_identity == user.ref)
|
||
return dict(session.execute(stmt).all())
|
||
|
||
def completed_counts(session: Session):
|
||
stmt = (
|
||
select(models.WorkCompleted.process, func.count(models.WorkCompleted.id))
|
||
.group_by(models.WorkCompleted.process)
|
||
)
|
||
if mine_only:
|
||
stmt = stmt.where(models.WorkCompleted.creator_identity == user.ref)
|
||
return dict(session.execute(stmt).all())
|
||
|
||
loaded = parallel.gather(db, {"running": running_counts, "completed": completed_counts})
|
||
counts, completed_counts = loaded["running"], loaded["completed"]
|
||
items = [
|
||
serializers.process(
|
||
r,
|
||
with_definition=with_definition,
|
||
running_count=int(counts.get(r.id, 0)),
|
||
completed_count=int(completed_counts.get(r.id, 0)),
|
||
startable=bool(can_start.get(r.id, True)),
|
||
)
|
||
for r in rows
|
||
]
|
||
return ok(items)
|
||
|
||
|
||
@router.post("/process/starters/preview", dependencies=[Depends(require_permission("design:process"))])
|
||
def preview_starters(body: schemas.StartersPreviewBody, db: Session = Depends(get_db)) -> dict:
|
||
"""发起范围预览:这串来源现在解析成谁、哪些名字已经认不出来了。
|
||
|
||
与环节审批人的预览一样,配置存的是来源而不是人员名单,所以人挪了部门、退了休,
|
||
这里念出来的数字会跟着变——设计器要在保存之前就把这件事说给人听。
|
||
"""
|
||
return ok(starters.preview(db, body.selectors))
|
||
|
||
|
||
@router.post("/process/processes", dependencies=[Depends(require_permission("design:process"))])
|
||
def create_process(
|
||
body: schemas.ProcessBody, user: CurrentUser = Depends(current_user), db: Session = Depends(get_db)
|
||
) -> dict:
|
||
category = db.get(models.Category, body.category) if body.category else None
|
||
row = models.Process(
|
||
name=body.name, alias=body.alias or body.name, description=body.description,
|
||
category=category.id if category else body.category,
|
||
category_name=category.name if category else "",
|
||
icon=body.icon, color=body.color, order_number=body.order_number,
|
||
open_create=body.open_create,
|
||
start_identity_list=starters.clean_selectors(body.start_identity_list),
|
||
manageable_identity_list=body.manageable_identity_list,
|
||
visible_identity_list=body.visible_identity_list,
|
||
data_template=body.data_template,
|
||
canvas=body.canvas,
|
||
approval_config=_clean_approval(body.approval_config or {}, DEFAULT_APPROVAL),
|
||
title_config=_clean_title_config(body.title_config or {}),
|
||
serial_config=_clean_serial_config(body.serial_config or {}),
|
||
# 建流程这一刻还没有环节清单,环节那一项不判(默认起手图里的环节 id 也还没生成)
|
||
terminate_config=_clean_terminate_config(
|
||
db, body.terminate_config or {}, None, None, body.latest_form or ""),
|
||
creator=user.person_id,
|
||
creator_name=user.display_name,
|
||
)
|
||
db.add(row)
|
||
db.flush()
|
||
# 建流程时就选过表单 → 用那张,别再塞一张重复的起手表单;没选才现建一张。
|
||
chosen = db.get(models.FormElement, body.latest_form) if body.latest_form else None
|
||
if body.latest_form and chosen is None:
|
||
raise bad_request("选定的表单不存在,重新选一张或改成新建表单")
|
||
_add_default_design(db, row, chosen.id if chosen else "")
|
||
db.commit()
|
||
return ok(serializers.process(row))
|
||
|
||
|
||
STARTER_FORM: dict = {
|
||
"fields": [{"key": "reason", "label": "申请事由", "type": "textarea", "required": True, "span": 24}],
|
||
"layout": {"columns": 2},
|
||
}
|
||
|
||
|
||
def _add_default_design(db: Session, process: models.Process, form_id: str = "") -> None:
|
||
"""新流程自带「开始-填写申请-结束」和一张只有一个字段的表单,建完就能发起。
|
||
|
||
表单在这里定一次就够:三个环节都不写 ``activity.form``,运行时一律回落到流程默认
|
||
表单(见 engine 里 ``activity.form or definition.latest_form``)。已经选好表单的
|
||
流程不再另建一张,免得表单库里多出一张没人要的「XX表单」。
|
||
"""
|
||
if form_id:
|
||
row = db.get(models.FormElement, form_id)
|
||
process.latest_form = row.id if row else ""
|
||
process.latest_form_name = row.name if row else ""
|
||
else:
|
||
form_row = models.FormElement(
|
||
name=f"{process.name}表单", alias=process.alias, description="",
|
||
process=process.id, content=copy.deepcopy(STARTER_FORM), person=process.creator,
|
||
)
|
||
db.add(form_row)
|
||
db.flush()
|
||
process.latest_form = form_row.id
|
||
process.latest_form_name = form_row.name
|
||
begin = models.Activity(
|
||
process=process.id, type="begin", name="开始", alias="开始", x=120, y=200, order_number=0,
|
||
config={},
|
||
)
|
||
manual = models.Activity(
|
||
process=process.id, type="manual", name="填写申请", alias="填写申请", x=340, y=200, order_number=1,
|
||
config={"mode": "any", "first": True, "taskValues": [{"type": "creator", "data": []}]},
|
||
)
|
||
end = models.Activity(
|
||
process=process.id, type="end", name="结束", alias="结束", x=580, y=200, order_number=2, config={},
|
||
)
|
||
db.add_all([begin, manual, end])
|
||
db.flush()
|
||
db.add_all(
|
||
[
|
||
models.Route(process=process.id, name="提交", alias="提交", from_activity=begin.id, to_activity=manual.id, order_number=0),
|
||
models.Route(process=process.id, name="办结", alias="办结", from_activity=manual.id, to_activity=end.id, order_number=0),
|
||
]
|
||
)
|
||
|
||
|
||
def _read_process(db: Session, process_id: str) -> dict:
|
||
row = db.get(models.Process, process_id)
|
||
if row is None:
|
||
raise not_found("流程不存在")
|
||
activities = db.execute(
|
||
select(models.Activity).where(models.Activity.process == process_id).order_by(models.Activity.order_number)
|
||
).scalars().all()
|
||
routes = db.execute(
|
||
select(models.Route).where(models.Route.process == process_id).order_by(models.Route.order_number)
|
||
).scalars().all()
|
||
form_row = db.get(models.FormElement, row.latest_form) if row.latest_form else None
|
||
# 逐环节带上运行时那份锁状态:发起页(任何登录用户可读这条)要据此把那颗「发起」
|
||
# 置灰并说出去哪儿办。判据仍只在 service/node_approve 一处,前端不拿 config 自己推第二遍。
|
||
locks = node_approve.lock_states_for_process(db, process_id)
|
||
return ok(
|
||
serializers.process(
|
||
row,
|
||
activities=[
|
||
{**serializers.activity(a), "oa_lock": locks.get(str(a.id))}
|
||
for a in activities
|
||
],
|
||
routes=[serializers.route(r) for r in routes],
|
||
form=serializers.form(form_row) if form_row else None,
|
||
)
|
||
)
|
||
|
||
|
||
@router.get("/process/processes/{process_id}")
|
||
def get_process(
|
||
process_id: str, db: Session = Depends(get_db), _: CurrentUser = Depends(current_user)
|
||
) -> dict:
|
||
"""流程定义(含环节、路由、表单):任何登录用户可读,改动要 design:process。"""
|
||
return _read_process(db, process_id)
|
||
|
||
|
||
@router.put("/process/processes/{process_id}", dependencies=[Depends(require_permission("design:process"))])
|
||
def update_process(process_id: str, body: schemas.ProcessUpdateBody, db: Session = Depends(get_db)) -> dict:
|
||
row = db.get(models.Process, process_id)
|
||
if row is None:
|
||
raise not_found("流程不存在")
|
||
payload = body.model_dump(exclude_none=True)
|
||
if "approval_config" in payload:
|
||
payload["approval_config"] = _clean_approval(
|
||
payload["approval_config"] or {}, row.approval_config or {}
|
||
)
|
||
if "title_config" in payload:
|
||
payload["title_config"] = _clean_title_config(
|
||
payload["title_config"] or {}, row.title_config or {}
|
||
)
|
||
if "serial_config" in payload:
|
||
payload["serial_config"] = _clean_serial_config(
|
||
payload["serial_config"] or {}, row.serial_config or {}
|
||
)
|
||
if "terminate_config" in payload:
|
||
payload["terminate_config"] = _clean_terminate_config(
|
||
db, payload["terminate_config"] or {}, row.terminate_config or {},
|
||
[item.id for item in row.activities],
|
||
str(payload.get("latest_form") or row.latest_form or ""),
|
||
)
|
||
if "start_identity_list" in payload:
|
||
payload["start_identity_list"] = starters.clean_selectors(payload["start_identity_list"] or [])
|
||
if "category" in payload:
|
||
category = db.get(models.Category, payload["category"]) if payload["category"] else None
|
||
row.category_name = category.name if category else ""
|
||
if "latest_form" in payload:
|
||
_use_default_form(db, row, payload.pop("latest_form") or "")
|
||
for key, value in payload.items():
|
||
setattr(row, key, value)
|
||
db.commit()
|
||
return ok(serializers.process(row))
|
||
|
||
|
||
def _release_forms(db: Session, process_id: str) -> None:
|
||
"""流程删掉后,它独有的表单跟着走;别的流程还引用的退回通用,别留没人认领的孤儿表单。"""
|
||
owned = db.execute(select(models.FormElement).where(models.FormElement.process == process_id)).scalars().all()
|
||
if not owned:
|
||
return
|
||
form_ids = [row.id for row in owned]
|
||
referenced = set(
|
||
db.execute(
|
||
select(models.Activity.form).where(
|
||
models.Activity.form.in_(form_ids), models.Activity.process != process_id
|
||
)
|
||
).scalars().all()
|
||
)
|
||
referenced |= set(
|
||
db.execute(
|
||
select(models.Process.latest_form).where(
|
||
models.Process.latest_form.in_(form_ids), models.Process.id != process_id
|
||
)
|
||
).scalars().all()
|
||
)
|
||
for row in owned:
|
||
if row.id in referenced:
|
||
row.process = ""
|
||
else:
|
||
db.delete(row)
|
||
|
||
|
||
@router.delete("/process/processes/{process_id}", dependencies=[Depends(require_permission("design:process"))])
|
||
def delete_process(process_id: str, db: Session = Depends(get_db)) -> dict:
|
||
row = db.get(models.Process, process_id)
|
||
if row is None:
|
||
raise not_found("流程不存在")
|
||
if db.execute(select(func.count(models.Work.id)).where(models.Work.process == process_id)).scalar():
|
||
raise bad_request("这个流程还有在途单据,不能删除")
|
||
_release_forms(db, process_id)
|
||
# 在途单据挡在上面那一句里已经查过:走到这里,还在认这张图的只剩**已经办结归档**的单据
|
||
# 与它们的已办行。那些引用得留着——归档单详情页读的就是它走完时那一版设计,把图连着
|
||
# 流程一起删掉,等于把一张早就落定的单的历史也抹了(详情页只能空着打开,环节、路由、
|
||
# 表单全没了)。没人认领的那些跟着流程走,别在库里堆一堆查无此图的行。
|
||
claimed = set(db.execute(
|
||
select(models.WorkCompleted.design_snapshot).where(
|
||
models.WorkCompleted.process == process_id, models.WorkCompleted.design_snapshot != "")
|
||
).scalars().all())
|
||
claimed |= set(db.execute(
|
||
select(models.TaskCompleted.design_snapshot).where(
|
||
models.TaskCompleted.process == process_id, models.TaskCompleted.design_snapshot != "")
|
||
).scalars().all())
|
||
stale = delete(models.ProcessSnapshot).where(models.ProcessSnapshot.process == process_id)
|
||
if claimed:
|
||
stale = stale.where(models.ProcessSnapshot.id.notin_(claimed))
|
||
db.execute(stale)
|
||
db.delete(row)
|
||
db.commit()
|
||
return ok({"success": True})
|
||
|
||
|
||
EDGE_STYLES = {"orthogonal", "straight", "curve"}
|
||
|
||
#: 审批人去重的可选口径,与前端 process.dedupXxx 文案一一对应。
|
||
DEDUP_MODES = {"none", "all"}
|
||
#: 前瞻去重(后面还要他批,前面这一环就跳过)的三档:不算 / 后面每条路径都必经 /
|
||
#: 后面有一条路径可能经过。激进一步就要多担一份「分支没走到,他一次都没批」的风险,
|
||
#: 所以默认那档是 none,中间那档 all 才是给日常用的。
|
||
DEDUP_AHEAD_MODES = {"none", "all", "any"}
|
||
#: 新流程出厂两条去重规则都是关的:每个人在每一环都真的收到一条待办。
|
||
#: 「发起人不重复审批」开了以后,起草环节(审批人就是发起人本人)会在发起当场
|
||
#: 被自动通过,发起人手上再也看不到自己的单,退回也没有落脚点了;
|
||
#: 「审批人去重」开了以后,同一人后面的环节会被静默跳过。
|
||
#: 「后面还要他批就跳过前面」出厂也是关的:它免掉的是前面那一签,判断依据是
|
||
#: 对后续路径的预测,得由设计者看着自己的流程图决定敢不敢开。
|
||
#: 三条都是可选策略,让使用者在「流程设置 → 审批规则」里按公司习惯自己打开。
|
||
DEFAULT_APPROVAL: dict = {"skipStarter": False, "dedup": "none", "dedupAhead": "none"}
|
||
|
||
|
||
def _clean_approval(payload: dict, base: dict | None = None) -> dict:
|
||
"""归一化流程级审批规则;认得 skipStarter / dedup / dedupAhead / dedupAheadKeepOne。"""
|
||
out: dict = dict(base or {})
|
||
if "skipStarter" in payload or "skip_starter" in payload:
|
||
out["skipStarter"] = bool(payload.get("skipStarter", payload.get("skip_starter")))
|
||
dedup = str(payload.get("dedup") or "").strip()
|
||
if dedup:
|
||
if dedup not in DEDUP_MODES:
|
||
raise bad_request(f"审批人去重口径不支持: {dedup}", reason="APPROVAL_INVALID")
|
||
out["dedup"] = dedup
|
||
ahead = str(payload.get("dedupAhead") or payload.get("dedup_ahead") or "").strip()
|
||
if ahead:
|
||
if ahead not in DEDUP_AHEAD_MODES:
|
||
raise bad_request(f"前瞻去重口径不支持: {ahead}", reason="APPROVAL_INVALID")
|
||
out["dedupAhead"] = ahead
|
||
if (
|
||
"dedupAheadKeepOne" in payload
|
||
or "dedup_ahead_keep_one" in payload
|
||
):
|
||
out["dedupAheadKeepOne"] = bool(
|
||
payload.get("dedupAheadKeepOne", payload.get("dedup_ahead_keep_one"))
|
||
)
|
||
return out
|
||
|
||
|
||
def _clean_title_config(payload: dict, base: dict | None = None) -> dict:
|
||
"""归一化流程标题规则;模板与表达式写坏在这里就报出去。
|
||
|
||
规则是设计器配的,等发起人点「发起流程」才发现标题算不出来最难查:
|
||
那时单据已经发出去了,而且回滚还来不及。
|
||
"""
|
||
try:
|
||
return titles.clean_config(payload or {}, base or {})
|
||
except ValueError as exc:
|
||
raise bad_request(str(exc), reason="TITLE_RULE_INVALID") from exc
|
||
|
||
|
||
def _clean_serial_config(payload: dict, base: dict | None = None) -> dict:
|
||
"""归一化「编号什么时候生成」,写歪的当场报出去,不悄悄退回默认口径。
|
||
|
||
宽容收敛只用在读的时候(``numbering.clean_timing``):接口/老数据里写歪一句,
|
||
读的时候按默认口径跑就好;但设计者亲手点了「到指定环节才生成」而服务端悄悄
|
||
存成「发起时生成」,那种"存进去是一回事、跑起来是另一回事"最难查,所以写的时候严格。
|
||
"""
|
||
body = dict(base or {})
|
||
body.update({key: value for key, value in dict(payload or {}).items() if key in ("at", "activity", "when")})
|
||
problems = numbering.timing_problems(body)
|
||
if problems:
|
||
raise bad_request("编号生成时机有问题:" + ";".join(problems), reason="SERIAL_TIMING_INVALID")
|
||
return numbering.clean_timing(body)
|
||
|
||
|
||
def _clean_terminate_config(
|
||
db: Session,
|
||
payload: dict,
|
||
base: dict | None = None,
|
||
activity_ids: list[str] | None = None,
|
||
form: str = "",
|
||
) -> dict:
|
||
"""归一化「终止」那一格:谁能终止、到什么时候为止、终止那一刻发什么写回。
|
||
分寸与 :func:`_clean_serial_config` 一样——读的时候宽容收敛,**写的时候严格**:
|
||
设计者亲手点了「走到部门主管之后不许发起人终止」而服务端悄悄存成「随时能终止」,
|
||
又是那种"界面说一套、跑起来做一套"最难查的账。环节 id 也在这儿验:它是每条流程
|
||
自己的主键,复制流程、恢复版本都会换掉它,指着一个已经不存在的环节等于这条规矩
|
||
永远不生效;写回那半当场点名三种病(模板被删、被停用、绑的是另一张表单),判据与
|
||
全库体检共用一份(``mapping.mount_code_problems``),``form`` 传这条流程的默认表单。
|
||
"""
|
||
body = dict(base or {})
|
||
body.update({key: value for key, value in dict(payload or {}).items()
|
||
if key in ("allowStarter", "until", "untilActivity", "untilHours", "writeback")})
|
||
problems = terminate_service.problems(body, activity_ids)
|
||
|
||
for problem in mapping.mount_code_problems(
|
||
db, terminate_service.writeback_mount(body), form=str(form or "")
|
||
):
|
||
problems.append(f"终止时要发的写回:{problem}")
|
||
if problems:
|
||
raise bad_request("终止配置有问题:" + ";".join(problems), reason="TERMINATE_CONFIG_INVALID")
|
||
return terminate_service.clean(body)
|
||
|
||
|
||
def _clean_open_approve(payload: dict, base: dict | None = None) -> dict:
|
||
"""归一化流程级「外部审批接口」默认档;写歪的键在这里就报出去。
|
||
|
||
与环节上那份 ``config.openApprove`` 共用一份键的判据(``service/node_approve``),
|
||
这里只管流程默认档这一层:环节显式配置逐键覆盖这里,没配的键继承这里。
|
||
"""
|
||
body = dict(base or {})
|
||
if "enabled" in payload:
|
||
body["enabled"] = bool(payload.get("enabled"))
|
||
apps = payload.get("apps")
|
||
if apps is not None:
|
||
if not isinstance(apps, list) or not all(isinstance(item, str) for item in apps):
|
||
raise bad_request("外部审批的应用白名单要是一串应用编码", reason="OPEN_APPROVE_INVALID")
|
||
body["apps"] = [str(item).strip() for item in apps if str(item).strip()]
|
||
confirm = str(payload.get("confirm") or "").strip().lower()
|
||
if confirm:
|
||
if confirm not in node_approve.CONFIRM_MODES:
|
||
raise bad_request("外部审批的确认模式只认 confirm / auto", reason="OPEN_APPROVE_INVALID")
|
||
body["confirm"] = confirm
|
||
decisions = payload.get("decisions")
|
||
if decisions is not None:
|
||
if not isinstance(decisions, dict):
|
||
raise bad_request("外部审批的决策词表要是一组「对方词 → 结论」", reason="OPEN_APPROVE_INVALID")
|
||
for word, kind in decisions.items():
|
||
if str(kind).strip().lower() not in node_approve.DECISIONS:
|
||
raise bad_request(f"决策词「{word}」只能映到 agree / refuse / submit", reason="OPEN_APPROVE_INVALID")
|
||
body["decisions"] = {str(word).strip(): str(kind).strip().lower() for word, kind in decisions.items() if str(word).strip()}
|
||
fields = payload.get("fields")
|
||
if fields is not None:
|
||
if not isinstance(fields, list) or not all(isinstance(item, str) for item in fields):
|
||
raise bad_request("外部审批的可写字段要是一串表单字段名", reason="OPEN_APPROVE_INVALID")
|
||
body["fields"] = [str(item).strip() for item in fields if str(item).strip()]
|
||
routes = payload.get("routes")
|
||
if routes is not None:
|
||
if not isinstance(routes, dict):
|
||
raise bad_request("外部审批的出口钉配要是一组「结论 → 出口名」", reason="OPEN_APPROVE_INVALID")
|
||
for kind, route_name in routes.items():
|
||
if str(kind).strip().lower() not in node_approve.DECISIONS:
|
||
raise bad_request(f"出口钉配「{kind}」不是认识的结论(agree / refuse / submit)", reason="OPEN_APPROVE_INVALID")
|
||
body["routes"] = {str(kind).strip().lower(): str(route).strip()
|
||
for kind, route in routes.items()
|
||
if str(kind).strip() and str(route).strip()}
|
||
opinion = payload.get("opinion")
|
||
if opinion is not None:
|
||
if not isinstance(opinion, dict):
|
||
raise bad_request("外部审批的意见模板要是一组「结论 → 模板」", reason="OPEN_APPROVE_INVALID")
|
||
for kind, template in opinion.items():
|
||
if str(kind).strip().lower() not in node_approve.DECISIONS:
|
||
raise bad_request(f"意见模板「{kind}」不是认识的结论(agree / refuse / submit)", reason="OPEN_APPROVE_INVALID")
|
||
body["opinion"] = {str(kind).strip().lower(): str(template) for kind, template in opinion.items() if str(template or "").strip()}
|
||
note = str(payload.get("note") or "").strip()
|
||
if note:
|
||
body["note"] = note
|
||
lock = payload.get(node_approve.LOCK_KEY)
|
||
if lock is not None:
|
||
# 这一处是**逐键挑着抄**的:不认识 oaLock 就会把流程默认档里那一段悄悄丢掉,
|
||
# 环节上显式配的倒是没事——两边一比较,"默认锁全部环节"就成了只看得到开关的摆设。
|
||
if not isinstance(lock, dict):
|
||
raise bad_request(
|
||
"OA 按钮锁定要是一组开关(enabled / actions / allowConfirm / text)",
|
||
reason="OPEN_APPROVE_INVALID",
|
||
)
|
||
cleaned: dict = {}
|
||
if "enabled" in lock:
|
||
cleaned["enabled"] = bool(lock.get("enabled"))
|
||
actions = lock.get("actions")
|
||
if actions is not None:
|
||
if not isinstance(actions, list) or not all(isinstance(item, str) for item in actions):
|
||
raise bad_request(
|
||
"OA 按钮锁定要是一串动作名(handle / start / goBack / recall / addTask / transfer)",
|
||
reason="OPEN_APPROVE_INVALID",
|
||
)
|
||
picked = list(dict.fromkeys(str(item).strip() for item in actions if str(item).strip()))
|
||
unknown = [item for item in picked if item not in node_approve.LOCK_ACTIONS]
|
||
if unknown:
|
||
raise bad_request(
|
||
f"OA 按钮锁定认不出动作「{'、'.join(unknown)}」,"
|
||
f"只认 {' / '.join(node_approve.LOCK_ACTIONS)}",
|
||
reason="OPEN_APPROVE_INVALID",
|
||
)
|
||
if picked:
|
||
cleaned["actions"] = picked
|
||
if "allowConfirm" in lock:
|
||
cleaned["allowConfirm"] = bool(lock.get("allowConfirm"))
|
||
text = str(lock.get("text") or "").strip()
|
||
if text:
|
||
cleaned["text"] = text
|
||
body[node_approve.LOCK_KEY] = cleaned
|
||
return body
|
||
|
||
|
||
def _clean_canvas(payload: dict) -> dict:
|
||
"""只留认识的画布偏好,别让脏字段一路带到前端去。"""
|
||
canvas: dict = {}
|
||
style = str(payload.get("edge_style") or payload.get("edgeStyle") or "").strip()
|
||
if style in EDGE_STYLES:
|
||
canvas["edge_style"] = style
|
||
try:
|
||
canvas["edge_radius"] = max(0, min(24, int(float(payload.get("edge_radius", payload.get("edgeRadius", 8))))))
|
||
except (TypeError, ValueError):
|
||
pass
|
||
return canvas
|
||
|
||
|
||
#: 环节与路由的 id 列是 ``String(32)``,名称与别名是 ``String(255)``。
|
||
ID_COLUMN_LENGTH = 32
|
||
NAME_COLUMN_LENGTH = 255
|
||
|
||
|
||
def _id_is_storable(wanted: str) -> bool:
|
||
"""客户端带来的环节/路由 id 能不能直接当主键用。
|
||
|
||
超长的 id 拖到 INSERT 才炸成 MySQL 1406,接口回身就是一个 500;这里跟
|
||
「id 已被占用」按同一口径处理——换个新 id,画布靠 id_map 照样接得上。
|
||
"""
|
||
return bool(wanted) and len(wanted) <= ID_COLUMN_LENGTH
|
||
|
||
|
||
def _check_name_length(kind: str, value: str) -> None:
|
||
"""名称超长要当场说清楚,这东西没法替设计者截断。"""
|
||
if len(str(value or "")) > NAME_COLUMN_LENGTH:
|
||
raise bad_request(f"{kind}的名称太长了,最多 {NAME_COLUMN_LENGTH} 个字")
|
||
|
||
|
||
@router.put("/process/processes/{process_id}/design", dependencies=[Depends(require_permission("design:process"))])
|
||
def save_design(process_id: str, body: schemas.ProcessDesignBody, db: Session = Depends(get_db)) -> dict:
|
||
"""Whole-graph save used by the visual designer (activities + routes)."""
|
||
process = db.get(models.Process, process_id)
|
||
if process is None:
|
||
raise not_found("流程不存在")
|
||
|
||
existing_activities = {a.id: a for a in db.execute(select(models.Activity).where(models.Activity.process == process_id)).scalars().all()}
|
||
existing_routes = {r.id: r for r in db.execute(select(models.Route).where(models.Route.process == process_id)).scalars().all()}
|
||
|
||
keep_activities: set[str] = set()
|
||
id_map: dict[str, str] = {}
|
||
created_activities: list[models.Activity] = []
|
||
# 本批次已经占用掉的 id:db.get() 看不见还没 flush 的新行,同一份载荷里
|
||
# 重名的临时 id(设计器 bug 或复制粘贴)会在这儿撞主键。
|
||
taken_activities: set[str] = set(existing_activities)
|
||
taken_routes: set[str] = set(existing_routes)
|
||
|
||
for item in body.activities:
|
||
wanted = item.id
|
||
if wanted and wanted in existing_activities:
|
||
row = existing_activities[wanted]
|
||
keep_activities.add(row.id)
|
||
else:
|
||
# Designer supplied a temporary id (e.g. "n1"); keep it so the
|
||
# routes in the same payload can reference it. 环节 id 是全局主键,
|
||
# 已经被别的流程占用时换个新 id,路由靠 id_map 照样能接上。
|
||
# id 必须在这儿就定下来:列默认值是 INSERT 才生成的,先 db.add 再读
|
||
# row.id 会拿到 None,路由翻译跟着把 None 当环节 id 写进库。
|
||
if not _id_is_storable(wanted) or (
|
||
wanted in taken_activities or db.get(models.Activity, wanted) is not None
|
||
):
|
||
wanted = models.new_id()
|
||
row = models.Activity(process=process_id, id=wanted or models.new_id())
|
||
db.add(row)
|
||
created_activities.append(row)
|
||
keep_activities.add(row.id)
|
||
taken_activities.add(row.id)
|
||
id_map[item.id or row.id] = row.id
|
||
_check_name_length("环节", item.name)
|
||
row.type = item.type
|
||
row.name = item.name
|
||
row.alias = item.alias or item.name
|
||
row.description = item.description
|
||
row.x = item.x
|
||
row.y = item.y
|
||
# 与默认表单相同的指定在这一刻就收回成沿用(口径见 _inherit_form)
|
||
row.form = _inherit_form(body.latest_form, item.form or "")
|
||
row.order_number = item.order_number
|
||
row.config = item.config
|
||
# 新环节要先把字段填完再落库:先 flush 会拿 type=NULL 去 INSERT,非空列直接报错
|
||
if created_activities:
|
||
db.flush()
|
||
|
||
for row_id, row in existing_activities.items():
|
||
if row_id not in keep_activities:
|
||
db.delete(row)
|
||
db.flush()
|
||
|
||
def translate(value: str) -> str:
|
||
return id_map.get(value, value)
|
||
|
||
keep_routes: set[str] = set()
|
||
for item in body.routes:
|
||
from_id = translate(item.from_activity)
|
||
to_id = translate(item.to_activity)
|
||
if from_id not in keep_activities or to_id not in keep_activities:
|
||
raise bad_request(f"路由 {item.name} 的环节不存在")
|
||
row = existing_routes.get(item.id) if item.id else None
|
||
if row is None:
|
||
# 路由 id 同样是全局主键:画布上的 "r1" 在每条流程里都可能重复,
|
||
# 撞上了就换个新 id,反正路由之间互不引用。
|
||
wanted = item.id or ""
|
||
if not _id_is_storable(wanted) or (
|
||
wanted in taken_routes or db.get(models.Route, wanted) is not None
|
||
):
|
||
wanted = models.new_id()
|
||
row = models.Route(process=process_id, id=wanted or models.new_id())
|
||
db.add(row)
|
||
keep_routes.add(row.id)
|
||
taken_routes.add(row.id)
|
||
_check_name_length("路由", item.name)
|
||
row.name = item.name
|
||
row.alias = item.alias or item.name
|
||
row.from_activity = from_id
|
||
row.to_activity = to_id
|
||
row.decision = item.decision
|
||
row.expression = item.expression
|
||
row.order_number = item.order_number
|
||
for row_id, row in existing_routes.items():
|
||
if row_id not in keep_routes:
|
||
db.delete(row)
|
||
|
||
if body.canvas is not None:
|
||
process.canvas = _clean_canvas(body.canvas)
|
||
if body.approval_config is not None:
|
||
process.approval_config = _clean_approval(body.approval_config, process.approval_config or {})
|
||
if body.title_config is not None:
|
||
process.title_config = _clean_title_config(body.title_config, process.title_config or {})
|
||
if body.serial_config is not None:
|
||
process.serial_config = _clean_serial_config(body.serial_config, process.serial_config or {})
|
||
if body.terminate_config is not None:
|
||
# 环节清单按**这一次一起交上来的**那份验:设计器里刚删掉的环节,保存这一刻就该喊,
|
||
# 不用等下一单走进终止才发现窗口指着一张已经不存在的环节。
|
||
process.terminate_config = _clean_terminate_config(
|
||
db, body.terminate_config, process.terminate_config or {},
|
||
[str(item.id or "") for item in body.activities if str(item.id or "")],
|
||
str(process.latest_form or ""),
|
||
)
|
||
if body.open_approve is not None:
|
||
process.open_approve = _clean_open_approve(body.open_approve, process.open_approve or {})
|
||
# 写回挂载(环节配置里的 writeback)也在这一次保存里验:模板被删了、补救路线不存在、
|
||
# 响应回写的字段这一环节还能改——这三种都要在保存时就喊,等流程走到那一环节再发现,
|
||
# 少发的那一条报文就是上游少的一张凭证。
|
||
mounted = list(db.execute(select(models.Activity).where(models.Activity.process == process_id)).scalars())
|
||
route_refs = [value for row in db.execute(
|
||
select(models.Route.id, models.Route.name).where(models.Route.process == process_id)
|
||
).all() for value in row]
|
||
writeback_problems = mapping.mount_problems(
|
||
db, mounted, route_refs, engine.goback_universe_for(db, process_id))
|
||
if writeback_problems:
|
||
raise bad_request("写回挂载还有问题:" + ";".join(writeback_problems[:6]), reason="DESIGN_INVALID")
|
||
# 外部审批接口:决策词翻不翻得出来、白名单里那个字段还在不在、挂阈值的格子收没收——
|
||
# 保存时点名,别等第三方第一次调用才撞上一句「出口不存在」。
|
||
open_approve_problems = []
|
||
for row in mounted:
|
||
open_approve_problems.extend(node_approve.problems(db, process, row))
|
||
if open_approve_problems:
|
||
raise bad_request("外部审批接口还有问题:" + ";".join(open_approve_problems[:6]), reason="DESIGN_INVALID")
|
||
# 编号时机指着的那个环节必须真在这张图上。环节被删掉、改了 id 而配置还留着的话,
|
||
# 这条流程上没人会再触发排号,出来的单子一路到办结都是空号——发布校验(
|
||
# definition.validate)也管这件事,但那要等点发布,改完设计就该说清楚。
|
||
timing = numbering.timing_of(process)
|
||
if timing["at"] == numbering.TIMING_ACTIVITY and timing["activity"]:
|
||
wanted = timing["activity"]
|
||
known = {row.id for row in mounted} | {row.name for row in mounted} | {row.alias for row in mounted}
|
||
if wanted not in known:
|
||
raise bad_request(
|
||
f"编号要在环节「{wanted}」生成,但这次保存的设计里没有这个环节。"
|
||
"请重新选一个环节,或把生成时机改回发起时",
|
||
reason="DESIGN_INVALID",
|
||
)
|
||
_use_default_form(db, process, body.latest_form)
|
||
db.commit()
|
||
return _read_process(db, process_id)
|
||
|
||
|
||
@router.post("/process/processes/{process_id}/validate", dependencies=[Depends(require_permission("design:process"))])
|
||
def validate_process(process_id: str, db: Session = Depends(get_db)) -> dict:
|
||
process = db.get(models.Process, process_id)
|
||
if process is None:
|
||
raise not_found("流程不存在")
|
||
definition = definition_module.load(db, process_id)
|
||
problems = definition_module.validate(definition)
|
||
for route in definition.routes:
|
||
error = expressions.validate_script(route.expression)
|
||
if error:
|
||
problems.append(f"路由 {route.name} 条件脚本错误: {error}")
|
||
for activity in definition.activities.values():
|
||
for key, value in (activity.config or {}).items():
|
||
if isinstance(value, str) and key.lower().endswith("script"):
|
||
error = expressions.validate_script(value)
|
||
if error:
|
||
problems.append(f"环节 {activity.name} 脚本错误: {error}")
|
||
# 挂在环节上的写回模板:模板在不在、还启不启用、补救路线还在不在
|
||
problems.extend(mapping.mount_problems(
|
||
db, definition.activities.values(), [value for r in definition.routes for value in (r.id, r.name)],
|
||
# 落点全集一起给:勾了「退回到哪些环节才发」而那个落点根本退不到,也是死配置
|
||
engine.goback_universe(definition),
|
||
))
|
||
# 外部审批接口与写回挂载同一档次:发布前逐环节点一遍名
|
||
for activity in definition.activities.values():
|
||
problems.extend(node_approve.problems(db, process, activity))
|
||
# 发起范围也算流程配置的一部分:配成没人能发起,跟画布画错一样是发布不出去的问题。
|
||
problems.extend(starters.scope_problems(db, process))
|
||
return ok({"valid": not problems, "problems": problems})
|
||
|
||
|
||
@router.post("/process/processes/{process_id}/goback-options", dependencies=[Depends(require_permission("design:process"))])
|
||
def goback_options(
|
||
process_id: str, body: dict | None = None, db: Session = Depends(get_db)
|
||
) -> dict:
|
||
"""每一环**退得到哪些环节**:给流程设计器那一格「退回到哪些环节才发」当候选清单。
|
||
|
||
判据必须在后端只有一份:绕开回头线的"上游可达"(``definition.feedback_route_ids`` 那一套)
|
||
与 ``goBackConfig`` 的收窄,前端再写一遍就会与待办页那颗「退回」算出两个答案——下拉里给得出、
|
||
点确定却被引擎拒掉,或者反过来。``activities`` / ``routes`` 传画布上当前这份(含还没保存的
|
||
改动),没传回退到库里的设计稿,与 ``dedup-audit`` / ``simulate`` 同一套取值口径。
|
||
"""
|
||
if db.get(models.Process, process_id) is None:
|
||
raise not_found("流程不存在")
|
||
payload = body or {}
|
||
activities = payload.get("activities")
|
||
routes = payload.get("routes")
|
||
definition = simulator.draft_definition(
|
||
db, process_id,
|
||
activities if isinstance(activities, list) else None,
|
||
routes if isinstance(routes, list) else None,
|
||
None,
|
||
)
|
||
begin_id = definition.begin.id if definition.begin is not None else ""
|
||
names = {node.id: (node.alias or node.name or node.id) for node in definition.activities.values()}
|
||
out: dict[str, list[dict]] = {}
|
||
for activity_id, lands in engine.goback_universe(definition).items():
|
||
origin = definition.activity(activity_id)
|
||
out[activity_id] = [
|
||
{"id": land, "name": names.get(land, land), "is_starter": bool(begin_id) and land == begin_id}
|
||
for land in lands
|
||
] if origin is not None and bool((origin.config or {}).get("allowGoBack", True)) else []
|
||
return ok(out)
|
||
|
||
|
||
@router.post("/process/processes/{process_id}/dedup-audit", dependencies=[Depends(require_permission("design:process"))])
|
||
def audit_duplicate_approvers(
|
||
process_id: str,
|
||
body: dict | None = None,
|
||
user: CurrentUser = Depends(current_user),
|
||
db: Session = Depends(get_db),
|
||
) -> dict:
|
||
"""设计期「重复审批人」体检:同一张单会被同一个人签几次,现在的配置管住了没有。
|
||
|
||
画布上还没保存的改动也能直接算:``activities`` / ``routes`` / ``approval`` 传了就用传的,
|
||
没传就回退到库里那份设计稿。``asIdentity`` 是试算上级、部门负责人这类找人方式用的
|
||
样例身份,默认拿当前登录人。
|
||
"""
|
||
if db.get(models.Process, process_id) is None:
|
||
raise not_found("流程不存在")
|
||
payload = body or {}
|
||
|
||
def rows(key: str) -> list[dict] | None:
|
||
value = payload.get(key)
|
||
return value if isinstance(value, list) else None
|
||
|
||
approval = payload.get("approval") or payload.get("approvalConfig") or payload.get("approval_config")
|
||
return ok(
|
||
dedupaudit.audit(
|
||
db,
|
||
process_id=process_id,
|
||
activities=rows("activities"),
|
||
routes=rows("routes"),
|
||
approval=approval if isinstance(approval, dict) else None,
|
||
as_identity=str(payload.get("asIdentity") or payload.get("as_identity") or user.ref or ""),
|
||
)
|
||
)
|
||
|
||
|
||
@router.post("/process/processes/{process_id}/simulate", dependencies=[Depends(require_permission("design:process"))])
|
||
def simulate_process(
|
||
process_id: str,
|
||
body: dict | None = None,
|
||
user: CurrentUser = Depends(current_user),
|
||
db: Session = Depends(get_db),
|
||
) -> dict:
|
||
"""流程试跑:选好发起人、填好表单,先把这一单预先走一遍再发布。
|
||
|
||
``starterIdentity`` 是替他发起的那个身份,``data`` 是发起人填的表单;
|
||
``activities`` / ``routes`` / ``approval`` 传了就用传的(画布上还没保存的改动照样能试),
|
||
没传就回退到库里那份设计稿。全程只读:不落库、不派待办、不发通知、不执行脚本与外部调用。
|
||
"""
|
||
if db.get(models.Process, process_id) is None:
|
||
raise not_found("流程不存在")
|
||
payload = body or {}
|
||
data = payload.get("data")
|
||
activities = payload.get("activities")
|
||
routes = payload.get("routes")
|
||
approval = payload.get("approval") or payload.get("approvalConfig") or payload.get("approval_config")
|
||
try:
|
||
result = simulator.simulate(
|
||
db,
|
||
process_id=process_id,
|
||
data=data if isinstance(data, dict) else {},
|
||
starter_identity=str(
|
||
payload.get("starterIdentity")
|
||
or payload.get("starter_identity")
|
||
or payload.get("asIdentity")
|
||
or user.ref
|
||
or ""
|
||
),
|
||
activities=activities if isinstance(activities, list) else None,
|
||
routes=routes if isinstance(routes, list) else None,
|
||
approval=approval if isinstance(approval, dict) else None,
|
||
)
|
||
except ValueError as exc:
|
||
raise bad_request(str(exc)) from exc
|
||
return ok(result)
|
||
|
||
|
||
@router.post("/process/processes/{process_id}/publish", dependencies=[Depends(require_permission("design:process"))])
|
||
def publish_process(
|
||
process_id: str,
|
||
body: schemas.PublishBody,
|
||
user: CurrentUser = Depends(current_user),
|
||
db: Session = Depends(get_db),
|
||
) -> dict:
|
||
process = db.get(models.Process, process_id)
|
||
if process is None:
|
||
raise not_found("流程不存在")
|
||
definition = definition_module.load(db, process_id)
|
||
problems = definition_module.validate(definition) + starters.scope_problems(db, process)
|
||
if problems:
|
||
raise bad_request("流程校验未通过:" + ";".join(problems[:6]), reason="DESIGN_INVALID")
|
||
process.enabled = True
|
||
process.published = True
|
||
process.version = (process.version or 1) + 1
|
||
snapshot = {
|
||
"process": serializers.process(process),
|
||
"activities": [serializers.activity(a) for a in db.execute(select(models.Activity).where(models.Activity.process == process_id)).scalars().all()],
|
||
"routes": [serializers.route(r) for r in db.execute(select(models.Route).where(models.Route.process == process_id)).scalars().all()],
|
||
}
|
||
version = models.ProcessVersion(
|
||
process=process_id, process_name=process.name, version=process.version,
|
||
snapshot=copy.deepcopy(snapshot), comment=body.comment,
|
||
creator=user.person_id, creator_name=user.display_name,
|
||
)
|
||
db.add(version)
|
||
db.commit()
|
||
return ok(serializers.process(process))
|
||
|
||
|
||
@router.post("/process/processes/{process_id}/disable", dependencies=[Depends(require_permission("design:process"))])
|
||
def disable_process(process_id: str, db: Session = Depends(get_db)) -> dict:
|
||
process = db.get(models.Process, process_id)
|
||
if process is None:
|
||
raise not_found("流程不存在")
|
||
process.enabled = False
|
||
db.commit()
|
||
return ok(serializers.process(process))
|
||
|
||
|
||
@router.get("/process/processes/{process_id}/versions", dependencies=[Depends(require_permission("design:process"))])
|
||
def list_versions(process_id: str, db: Session = Depends(get_db)) -> dict:
|
||
rows = db.execute(
|
||
select(models.ProcessVersion)
|
||
.where(models.ProcessVersion.process == process_id)
|
||
.order_by(models.ProcessVersion.version.desc())
|
||
).scalars().all()
|
||
return ok([serializers.process_version(r) for r in rows])
|
||
|
||
|
||
@router.get("/process/processes/{process_id}/title/variables")
|
||
def title_variables(
|
||
process_id: str, db: Session = Depends(get_db), _: CurrentUser = Depends(current_user)
|
||
) -> dict:
|
||
"""标题规则能用的变量清单 + 预览样例:设计器点选插入,不必手打变量名。
|
||
|
||
任何登录用户可读:发起页也要靠它把「标题怎么来的」讲清楚。
|
||
"""
|
||
try:
|
||
return ok(titles.variables(db, process_id))
|
||
except ValueError as exc:
|
||
raise not_found(str(exc)) from exc
|
||
|
||
|
||
@router.get("/process/versions/{version_id}", dependencies=[Depends(require_permission("design:process"))])
|
||
def get_version(version_id: str, db: Session = Depends(get_db)) -> dict:
|
||
row = db.get(models.ProcessVersion, version_id)
|
||
if row is None:
|
||
raise not_found("版本不存在")
|
||
return ok({"id": row.id, "process": row.process, "version": row.version, "snapshot": row.snapshot or {}})
|
||
|
||
|
||
@router.post(
|
||
"/process/processes/{process_id}/versions/{version_id}/rollback",
|
||
dependencies=[Depends(require_permission("design:process"))],
|
||
)
|
||
def rollback_version(process_id: str, version_id: str, db: Session = Depends(get_db)) -> dict:
|
||
"""把设计稿恢复成某次发布时的样子(发布过的版本不只有历史价值,还得能用)。
|
||
|
||
只回滚设计内容,不改发布状态:恢复完仍是"未发布的草稿",
|
||
要生效仍需再走一次校验与发布,避免手滑点一下就改了线上正在跑的口径。
|
||
"""
|
||
process = db.get(models.Process, process_id)
|
||
if process is None:
|
||
raise not_found("流程不存在")
|
||
version = db.get(models.ProcessVersion, version_id)
|
||
if version is None or version.process != process_id:
|
||
raise not_found("版本不存在")
|
||
snapshot = version.snapshot or {}
|
||
activities = snapshot.get("activities")
|
||
routes = snapshot.get("routes")
|
||
if not isinstance(activities, list) or not isinstance(routes, list):
|
||
raise bad_request("该版本快照不完整,无法回滚")
|
||
|
||
db.execute(delete(models.Route).where(models.Route.process == process_id))
|
||
db.execute(delete(models.Activity).where(models.Activity.process == process_id))
|
||
db.flush()
|
||
for item in activities:
|
||
db.add(
|
||
models.Activity(
|
||
id=str(item.get("id") or "") or models.new_id(),
|
||
process=process_id,
|
||
type=str(item.get("type") or "manual"),
|
||
name=str(item.get("name") or "未命名环节"),
|
||
alias=str(item.get("alias") or item.get("name") or ""),
|
||
description=str(item.get("description") or ""),
|
||
x=float(item.get("x") or 0),
|
||
y=float(item.get("y") or 0),
|
||
order_number=int(item.get("order_number") or 0),
|
||
form=str(item.get("form") or ""),
|
||
config=dict(item.get("config") or {}),
|
||
)
|
||
)
|
||
for item in routes:
|
||
db.add(
|
||
models.Route(
|
||
id=str(item.get("id") or "") or models.new_id(),
|
||
process=process_id,
|
||
name=str(item.get("name") or "路由"),
|
||
alias=str(item.get("alias") or item.get("name") or ""),
|
||
from_activity=str(item.get("from_activity") or ""),
|
||
to_activity=str(item.get("to_activity") or ""),
|
||
decision=str(item.get("decision") or ""),
|
||
expression=str(item.get("expression") or ""),
|
||
order_number=int(item.get("order_number") or 0),
|
||
)
|
||
)
|
||
meta = snapshot.get("process") or {}
|
||
if isinstance(meta, dict):
|
||
process.description = str(meta.get("description") or process.description)
|
||
process.canvas = dict(meta.get("canvas") or {}) or process.canvas
|
||
process.approval_config = dict(meta.get("approval_config") or {}) or process.approval_config
|
||
process.title_config = dict(meta.get("title_config") or {}) or process.title_config
|
||
_use_default_form(db, process, str(meta.get("latest_form") or "") if isinstance(meta, dict) else "")
|
||
process.published = False
|
||
db.commit()
|
||
return ok(serializers.process(process))
|
||
|
||
|
||
def _clone_forms(db: Session, source: models.Process, clone: models.Process, form_ids: list[str]) -> dict[str, str]:
|
||
"""流程副本要能独立改表单:本流程独有的表单复制一份,通用表单继续共用。"""
|
||
mapping: dict[str, str] = {}
|
||
for form_id in dict.fromkeys(item for item in form_ids if item):
|
||
row = db.get(models.FormElement, form_id)
|
||
if row is None or row.process != source.id:
|
||
continue
|
||
fresh = models.FormElement(
|
||
name=f"{row.name} 副本", alias=row.alias, description=row.description,
|
||
process=clone.id, content=copy.deepcopy(row.content or {}),
|
||
editable=row.editable, order_number=row.order_number, person=row.person,
|
||
)
|
||
db.add(fresh)
|
||
db.flush()
|
||
mapping[form_id] = fresh.id
|
||
return mapping
|
||
|
||
|
||
@router.post("/process/processes/{process_id}/copy", dependencies=[Depends(require_permission("design:process"))])
|
||
def copy_process(
|
||
process_id: str, user: CurrentUser = Depends(current_user), db: Session = Depends(get_db)
|
||
) -> dict:
|
||
source = db.get(models.Process, process_id)
|
||
if source is None:
|
||
raise not_found("流程不存在")
|
||
clone = models.Process(
|
||
name=f"{source.name} 副本", alias=source.alias, description=source.description,
|
||
category=source.category, category_name=source.category_name, enabled=False,
|
||
data_template=copy.deepcopy(source.data_template or {}),
|
||
title_config=copy.deepcopy(source.title_config or {}),
|
||
serial_config=copy.deepcopy(source.serial_config or {}),
|
||
terminate_config=copy.deepcopy(source.terminate_config or {}),
|
||
start_identity_list=list(source.start_identity_list or []),
|
||
manageable_identity_list=list(source.manageable_identity_list or []),
|
||
visible_identity_list=list(source.visible_identity_list or []),
|
||
icon=source.icon, color=source.color, order_number=source.order_number + 1,
|
||
creator=user.person_id, creator_name=user.display_name,
|
||
)
|
||
db.add(clone)
|
||
db.flush()
|
||
source_activities = db.execute(
|
||
select(models.Activity).where(models.Activity.process == process_id)
|
||
).scalars().all()
|
||
form_map = _clone_forms(db, source, clone, [source.latest_form] + [a.form for a in source_activities])
|
||
default_form = db.get(models.FormElement, form_map.get(source.latest_form, source.latest_form)) if source.latest_form else None
|
||
clone.latest_form = default_form.id if default_form else ""
|
||
clone.latest_form_name = default_form.name if default_form else ""
|
||
mapping: dict[str, str] = {}
|
||
for activity in source_activities:
|
||
fresh = models.Activity(
|
||
process=clone.id, type=activity.type, name=activity.name, alias=activity.alias,
|
||
description=activity.description, x=activity.x, y=activity.y,
|
||
order_number=activity.order_number,
|
||
# 副本同样只留真正不一样的绑定,与默认表单相同的直接沿用
|
||
form=_inherit_form(clone.latest_form, form_map.get(activity.form, activity.form)),
|
||
config=copy.deepcopy(activity.config or {}),
|
||
)
|
||
db.add(fresh)
|
||
db.flush()
|
||
mapping[activity.id] = fresh.id
|
||
for route in db.execute(select(models.Route).where(models.Route.process == process_id)).scalars().all():
|
||
db.add(
|
||
models.Route(
|
||
process=clone.id, name=route.name, alias=route.alias,
|
||
from_activity=mapping.get(route.from_activity, route.from_activity),
|
||
to_activity=mapping.get(route.to_activity, route.to_activity),
|
||
decision=route.decision, expression=route.expression, order_number=route.order_number,
|
||
)
|
||
)
|
||
# 编号时机指着的那一环在副本里换了 id:跟着环节映射换一次,否则副本上那条配置
|
||
# 指的是原流程的环节 id,副本自己的单子永远排不出号。按名字引用的原样留着也对得上
|
||
# (副本连名字一起抄)。
|
||
timing = numbering.timing_of(clone)
|
||
if timing["at"] == numbering.TIMING_ACTIVITY and timing["activity"]:
|
||
timing["activity"] = mapping.get(timing["activity"], timing["activity"])
|
||
clone.serial_config = timing
|
||
# 「走到某环节之后不许发起人终止」指着的那一环同理:副本里环节换了 id,
|
||
# 不换过来这条窗口就指着一个不在副本图里的 id,等于副本上发起人随时能终止。
|
||
terminate_body = terminate_service.clean(clone.terminate_config or {})
|
||
if terminate_body["untilActivity"]:
|
||
terminate_body["untilActivity"] = mapping.get(
|
||
terminate_body["untilActivity"], terminate_body["untilActivity"]
|
||
)
|
||
clone.terminate_config = terminate_body
|
||
db.commit()
|
||
return ok(serializers.process(clone))
|
||
|
||
|
||
@router.post("/process/script/validate", dependencies=[Depends(require_permission("design:process"))])
|
||
def validate_script(body: dict) -> dict:
|
||
script = str((body or {}).get("script") or "")
|
||
error = expressions.validate_script(script)
|
||
return ok({"valid": error is None, "error": error or ""})
|
||
|
||
|
||
# ------------------------------- approvers -------------------------------
|
||
|
||
|
||
@router.get("/process/approvers", dependencies=[Depends(require_permission("design:process"))])
|
||
def approver_directory(db: Session = Depends(get_db)) -> dict:
|
||
"""设计器选审批人用的岗位角色 / 分组 / 部门清单,各自带解析后的成员."""
|
||
return ok(org.approver_directory(db))
|
||
|
||
|
||
@router.post("/process/approvers/preview", dependencies=[Depends(require_permission("design:process"))])
|
||
def preview_approvers(body: dict, db: Session = Depends(get_db)) -> dict:
|
||
"""按当前审批人配置算一遍会落到哪些身份,并报告解析不到的名字."""
|
||
rows = (body or {}).get("taskValues") or []
|
||
if not isinstance(rows, list):
|
||
raise bad_request("taskValues 必须是数组")
|
||
sample = str((body or {}).get("asIdentity") or (body or {}).get("as_identity") or "")
|
||
script = str((body or {}).get("taskScript") or (body or {}).get("task_script") or "")
|
||
return ok(org.preview_selectors(db, rows, sample, script))
|
||
|
||
|
||
@router.get("/process/scripts")
|
||
def list_scripts(
|
||
db: Session = Depends(get_db),
|
||
_: CurrentUser = Depends(current_user),
|
||
process: str = Query(""),
|
||
) -> dict:
|
||
stmt = select(models.ScriptElement)
|
||
if process:
|
||
stmt = stmt.where(models.ScriptElement.process == process)
|
||
rows = db.execute(stmt.order_by(models.ScriptElement.name)).scalars().all()
|
||
return ok(
|
||
[
|
||
{
|
||
"id": r.id,
|
||
"name": r.name,
|
||
"type": r.type,
|
||
"description": r.description,
|
||
"process": r.process,
|
||
"activity": r.activity,
|
||
"script": r.script,
|
||
}
|
||
for r in rows
|
||
]
|
||
)
|
||
|
||
|
||
@router.post("/process/scripts", dependencies=[Depends(require_permission("design:process"))])
|
||
def upsert_script(body: dict, db: Session = Depends(get_db)) -> dict:
|
||
script = str(body.get("script") or "")
|
||
error = expressions.validate_script(script)
|
||
if error:
|
||
raise bad_request(error, reason="SCRIPT_INVALID")
|
||
row = db.get(models.ScriptElement, str(body.get("id") or "")) if body.get("id") else None
|
||
if row is None:
|
||
row = models.ScriptElement(name=str(body.get("name") or "脚本"))
|
||
db.add(row)
|
||
row.name = str(body.get("name") or row.name)
|
||
row.type = str(body.get("type") or "python")
|
||
row.description = str(body.get("description") or "")
|
||
row.process = str(body.get("process") or "")
|
||
row.activity = str(body.get("activity") or "")
|
||
row.script = script
|
||
db.commit()
|
||
return ok({"id": row.id, "name": row.name})
|