816 lines
33 KiB
Python
816 lines
33 KiB
Python
"""表单运行时:环节字段权限、明细表、计算公式、金额大写。
|
||
|
||
三件事都是"同一份表单在不同环节长得不一样、值不全靠人手填"这一类问题,
|
||
放在一个模块里,前端对应的镜像是 ``frontend/src/utils/formRuntime.ts``,
|
||
两边的常量(权限取值、明细表列类型、大写金额口径)必须保持一致。
|
||
|
||
- 字段权限:环节 ``config.formPerms`` 记 ``{字段名: hidden|readonly|editable|required}``,
|
||
没配的字段沿用自己的 ``required`` / ``readonly`` / ``hidden``(表单设计器上那个
|
||
「默认隐藏」开关,见 ``effective_perm``)。权限只在服务端算一次数,
|
||
前端拿到的只是同一份结果用来渲染,绕过界面也改不动不该改的字段。
|
||
- 明细表:``type=table`` 的字段存一个对象数组,列定义在 ``columns`` 上;
|
||
空行落库前丢掉,必填列和行数上下界在这里拦。
|
||
- 计算公式:``type=formula`` 的字段由 ``formula`` 表达式算出,走引擎那套受限
|
||
表达式沙箱;每次提交后重算,所以条件分支和统计都能直接用。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import re
|
||
from typing import Any, Iterable
|
||
|
||
#: 环节字段权限的四种取值,与前端 PERM_* 常量一致。
|
||
PERM_HIDDEN = "hidden"
|
||
PERM_READONLY = "readonly"
|
||
PERM_EDITABLE = "editable"
|
||
PERM_REQUIRED = "required"
|
||
PERM_VALUES = (PERM_HIDDEN, PERM_READONLY, PERM_EDITABLE, PERM_REQUIRED)
|
||
|
||
#: 明细表里能用的列类型:只放不需要复杂交互的基础控件,
|
||
#: 附件、人员、子表套子表这些在格子里放不下的都不给。
|
||
#: 明细列能用的类型:与前端 ``types.TABLE_COLUMN_TYPES`` 一一对应,
|
||
#: 也就是主表能填的类型除了标题/系统带出/嵌套明细/公式/排版类之外全部可用。
|
||
#: 明细列与主表共用前端那一个录入控件,所以两边类型清单必须一起改。
|
||
TABLE_COLUMN_TYPES = (
|
||
"text",
|
||
"textarea",
|
||
"number",
|
||
"money",
|
||
"date",
|
||
"datetime",
|
||
"time",
|
||
"daterange",
|
||
"mobile",
|
||
"email",
|
||
"idcard",
|
||
"url",
|
||
"address",
|
||
"select",
|
||
"radio",
|
||
"checkbox",
|
||
"switch",
|
||
"rate",
|
||
"dept",
|
||
"cascader",
|
||
"user",
|
||
"attachment",
|
||
"image",
|
||
"signature",
|
||
"relation",
|
||
)
|
||
|
||
#: 这几类列得有选项来源:字典编码或手写选项,否则格子里连能点的东西都没有。
|
||
OPTION_COLUMN_TYPES = ("select", "radio", "checkbox")
|
||
|
||
#: 不需要参与录入与必填校验的类型。
|
||
NON_INPUT_TYPES = ("divider", "description", "hidden", "auto", "formula")
|
||
|
||
#: 值由系统带出 / 公式算出来的那两类:永远不给录入框,环节也改不了它,但设计者可以让它
|
||
#: 「必填」——要求这一格必须带得出、算得出值。与前端 SYSTEM_FILLED_TYPES 一致。
|
||
SYSTEM_FILLED_TYPES = ("auto", "formula")
|
||
|
||
_CN_DIGITS = "零壹贰叁肆伍陆柒捌玖"
|
||
_CN_UNITS = ["", "拾", "佰", "仟"]
|
||
_CN_GROUPS = ["", "万", "亿", "万亿"]
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 字段与权限
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
def fields_of(content: object) -> list[dict]:
|
||
"""表单 ``content`` 里的字段列表;结构不对就返回空,别让脏数据炸了流程。"""
|
||
if not isinstance(content, dict):
|
||
return []
|
||
raw = content.get("fields")
|
||
return [item for item in raw if isinstance(item, dict)] if isinstance(raw, list) else []
|
||
|
||
|
||
def fillable(field: dict) -> bool:
|
||
return str(field.get("type") or "") not in NON_INPUT_TYPES
|
||
|
||
|
||
def system_filled(field: dict) -> bool:
|
||
"""这一格的值是系统给的还是人填的:系统给的那两类只能要求"算得出值",不能要求人去填。"""
|
||
return str(field.get("type") or "") in SYSTEM_FILLED_TYPES
|
||
|
||
|
||
def perms_of(config: object) -> dict[str, str]:
|
||
"""取环节的字段权限;认 ``formPerms``,顺手兼容历史写法 ``fieldPerms``。"""
|
||
source = config if isinstance(config, dict) else {}
|
||
raw = source.get("formPerms")
|
||
if not isinstance(raw, dict):
|
||
raw = source.get("fieldPerms")
|
||
if not isinstance(raw, dict):
|
||
return {}
|
||
return {
|
||
str(key): str(value)
|
||
for key, value in raw.items()
|
||
if str(value) in PERM_VALUES
|
||
}
|
||
|
||
|
||
def effective_perm(field: dict, perms: dict[str, str], data: dict | None = None) -> str:
|
||
"""单个字段在这个环节上的最终权限.
|
||
|
||
底子是环节配置(没配就看字段自己的 required / readonly / hidden);传了 ``data``
|
||
就再叠一层联动条件。**联动只会往严的方向加**(隐藏 / 只读 / 必填),不会把环节锁死的
|
||
字段放开,这样「环节说只读」不会因为某个字段联动而漏水。
|
||
"""
|
||
key = str(field.get("key") or "")
|
||
# 字段自己在表单设计器上勾了「默认隐藏」:没有哪一环节点名要它,就按隐藏算,
|
||
# 值照样存、公式照总算;某环节显式给了别的权限,就是那一环特意要看见它,字段默认让位。
|
||
override = perms.get(key) or (PERM_HIDDEN if field.get("hidden") else None)
|
||
if override == PERM_HIDDEN:
|
||
return PERM_HIDDEN
|
||
if data is None:
|
||
if override:
|
||
return override
|
||
if not fillable(field):
|
||
return PERM_READONLY
|
||
if field.get("required"):
|
||
return PERM_REQUIRED
|
||
if field.get("readonly"):
|
||
return PERM_READONLY
|
||
return PERM_EDITABLE
|
||
state = _linkage().state_of(field, data)
|
||
if not state["visible"]:
|
||
return PERM_HIDDEN
|
||
base = override or (PERM_READONLY if not fillable(field) else PERM_EDITABLE)
|
||
if base == PERM_HIDDEN: # pragma: no cover - 上面已挡
|
||
return PERM_HIDDEN
|
||
if state["readonly"]:
|
||
return PERM_READONLY
|
||
if state["required"]:
|
||
return PERM_REQUIRED
|
||
if override:
|
||
return override
|
||
if field.get("required"):
|
||
return PERM_REQUIRED
|
||
if field.get("readonly"):
|
||
return PERM_READONLY
|
||
return base
|
||
|
||
|
||
def visible_fields(fields: Iterable[dict], perms: dict[str, str], data: dict | None = None) -> list[dict]:
|
||
return [item for item in fields if effective_perm(item, perms, data) != PERM_HIDDEN]
|
||
|
||
|
||
def editable_keys(fields: Iterable[dict], perms: dict[str, str], data: dict | None = None) -> set[str]:
|
||
return {
|
||
str(item.get("key") or "")
|
||
for item in fields
|
||
if effective_perm(item, perms, data) in (PERM_EDITABLE, PERM_REQUIRED) and item.get("key")
|
||
}
|
||
|
||
|
||
def _linkage():
|
||
"""延迟导入,避开 dicts -> formruntime 的循环(大写金额那条也是同一个套路)。"""
|
||
from . import dicts as _dicts
|
||
|
||
return _dicts
|
||
|
||
|
||
#: 级联选择字段:值是从顶级一路到末级的字典项数组,见 cascader_problems。
|
||
CASCADER_TYPE = "cascader"
|
||
|
||
|
||
def empty_value(field: dict) -> bool:
|
||
"""没填的判定:空串、空数组、空对象都算空,数字 0 和布尔 False 不算。"""
|
||
value = field.get("__value__") if "__value__" in field else field
|
||
if value is None:
|
||
return True
|
||
if isinstance(value, str):
|
||
return not value.strip()
|
||
if isinstance(value, (list, dict, tuple, set)):
|
||
return len(value) == 0
|
||
return False
|
||
|
||
|
||
def missing_required(
|
||
fields: Iterable[dict], perms: dict[str, str], data: dict, *, prefix: str = ""
|
||
) -> list[str]:
|
||
"""这个环节必须填而没填的字段标题,按表单顺序返回。"""
|
||
problems: list[str] = []
|
||
for field in fields:
|
||
perm = effective_perm(field, perms, data)
|
||
key = str(field.get("key") or "")
|
||
if not key:
|
||
continue
|
||
# 必填只认环节的最后一道判断:effective_perm 已经把字段自己的 required 折算进来了,
|
||
# 而环节显式标成 editable 就是"允许留空",不该再拿字段老的 required 卡人。
|
||
must = perm == PERM_REQUIRED
|
||
if not must and perm in (PERM_READONLY, PERM_HIDDEN) and key not in perms:
|
||
# 系统带出与公式没有录入框,权限算出来永远是只读;字段自己勾了必填,就要它算得出值。
|
||
# 字段级「默认隐藏」也走这一条:编号、金额大写这种不显示但仍要有值的格子,
|
||
# 藏起来不等于可以不生成。环节显式隐藏(key in perms)才是真不用管。
|
||
must = system_filled(field) and bool(field.get("required"))
|
||
if not must:
|
||
continue
|
||
if empty_value({"__value__": (data or {}).get(key)}):
|
||
problems.append(f"{prefix}{field.get('label') or key}")
|
||
return problems
|
||
|
||
|
||
def _row_problems(field: dict, rows: list[dict]) -> list[str]:
|
||
"""明细表的行级校验:必填列、行数上下界,返回人能看懂的一句话。"""
|
||
label = str(field.get("label") or field.get("key") or "")
|
||
columns = columns_of(field)
|
||
min_rows = _int(field.get("minRows"), 0)
|
||
max_rows = _int(field.get("maxRows"), 0)
|
||
problems: list[str] = []
|
||
if min_rows and len(rows) < min_rows:
|
||
problems.append(f"「{label}」至少要有 {min_rows} 行")
|
||
if max_rows and len(rows) > max_rows:
|
||
problems.append(f"「{label}」最多只能有 {max_rows} 行")
|
||
for index, row in enumerate(rows, start=1):
|
||
for column in columns:
|
||
if not column.get("required"):
|
||
continue
|
||
column_key = str(column.get("key") or "")
|
||
if not column_key:
|
||
continue
|
||
if empty_value({"__value__": row.get(column_key)}):
|
||
problems.append(f"「{label}」第 {index} 行的「{column.get('label') or column_key}」还没填写")
|
||
return problems
|
||
|
||
|
||
def validate_submit(
|
||
fields: Iterable[dict], perms: dict[str, str], data: dict, cache: object | None = None
|
||
) -> list[str]:
|
||
"""一次提交的表单校验;返回问题列表,空列表就是可以提交。"""
|
||
items = list(fields)
|
||
problems = missing_required(items, perms, data or {})
|
||
for field in items:
|
||
if str(field.get("type") or "") != "table":
|
||
continue
|
||
key = str(field.get("key") or "")
|
||
if effective_perm(field, perms, data) == PERM_HIDDEN or not key:
|
||
continue
|
||
problems.extend(_row_problems(field, rows_of((data or {}).get(key))))
|
||
if problems:
|
||
break
|
||
problems.extend(selection_problems(items, perms, data or {}, cache))
|
||
return problems
|
||
|
||
|
||
def cascader_problems(fields: Iterable[dict], perms: dict[str, str], data: dict, cache: object) -> list[str]:
|
||
"""级联选择(``cascader``):值必须是一条从顶级字典项一路选到某个下级的完整路径。
|
||
|
||
这里不能套用普通下拉的「值必须在可选项里」:层级字典没配 ``cascadeFrom`` 时
|
||
``effective_options`` 只放顶级项,而级联控件天生就要选到第二、第三级,
|
||
照那套口径会把合法的值全判成越界。
|
||
"""
|
||
if cache is None:
|
||
return []
|
||
linkage = _linkage()
|
||
problems: list[str] = []
|
||
for field in fields:
|
||
if str(field.get("type") or "") != CASCADER_TYPE:
|
||
continue
|
||
key = str(field.get("key") or "")
|
||
code = str(field.get("dictCode") or "").strip()
|
||
if not key or not code:
|
||
continue
|
||
if effective_perm(field, perms, data) not in (PERM_EDITABLE, PERM_REQUIRED):
|
||
continue
|
||
picked = [str(item) for item in linkage._values(data.get(key))]
|
||
if not picked:
|
||
continue
|
||
label = str(field.get("label") or key)
|
||
items = {
|
||
str(item.get("value")): item for item in cache.items(code) if item.get("enabled", True) # type: ignore[attr-defined]
|
||
}
|
||
previous = ""
|
||
for depth, value in enumerate(picked):
|
||
item = items.get(value)
|
||
if item is None:
|
||
problems.append(f"「{label}」选到了字典里不存在或已停用的选项")
|
||
break
|
||
parent = str(item.get("parent") or "")
|
||
if not depth and parent:
|
||
problems.append(f"「{label}」要先选上一级")
|
||
break
|
||
if depth and parent != previous:
|
||
problems.append(f"「{label}」的上下级对不上")
|
||
break
|
||
previous = value
|
||
return problems
|
||
|
||
|
||
def selection_problems(fields: Iterable[dict], perms: dict[str, str], data: dict, cache: object) -> list[str]:
|
||
"""联动可选范围校验:选中的值必须是此刻真的能选的项。
|
||
|
||
只管本环节可编辑的字段:陈年旧值不该由一个改不动它的审批人来背锅。
|
||
"""
|
||
if cache is None:
|
||
return []
|
||
linkage = _linkage()
|
||
problems: list[str] = cascader_problems(fields, perms, data, cache)
|
||
for field in fields:
|
||
key = str(field.get("key") or "")
|
||
if not key or effective_perm(field, perms, data) not in (PERM_EDITABLE, PERM_REQUIRED):
|
||
continue
|
||
if not _has_option_rule(field):
|
||
continue
|
||
options = linkage.effective_options(field, data, cache) # type: ignore[arg-type]
|
||
if options is None:
|
||
continue
|
||
allowed = {linkage.option_value(item) for item in options}
|
||
current = linkage._values(data.get(key))
|
||
stale = [value for value in current if value not in allowed]
|
||
if stale:
|
||
parent = str(field.get("cascadeFrom") or "").strip()
|
||
hint = f"(请先选对「{label_of(fields, parent)}」)" if parent else ""
|
||
problems.append(f"「{field.get('label') or key}」的取值已不在可选范围内{hint}")
|
||
return problems
|
||
|
||
|
||
def label_of(fields: Iterable[dict], key: str) -> str:
|
||
for field in fields:
|
||
if str(field.get("key") or "") == key:
|
||
return str(field.get("label") or key)
|
||
return key
|
||
|
||
|
||
def _has_option_rule(field: dict) -> bool:
|
||
"""这个字段的可选项会不会随别的字段变化(字典 / 级联 / 带条件的选项)。"""
|
||
if str(field.get("type") or "") == CASCADER_TYPE:
|
||
# 级联的合法值口径不一样,走 cascader_problems
|
||
return False
|
||
if str(field.get("dictCode") or "").strip():
|
||
return True
|
||
if str(field.get("cascadeFrom") or "").strip():
|
||
return True
|
||
raw = field.get("options")
|
||
if isinstance(raw, list):
|
||
return any(isinstance(item, dict) and item.get("when") for item in raw)
|
||
return False
|
||
|
||
|
||
def linkage_problems(fields: Iterable[dict]) -> list[str]:
|
||
"""设计期检查联动配置本身:引用了不存在的字段、自己依赖自己、条件写了不认识的算子。"""
|
||
items = [item for item in fields if isinstance(item, dict)]
|
||
keys = {str(item.get("key") or "") for item in items}
|
||
linkage = _linkage()
|
||
problems: list[str] = []
|
||
for field in items:
|
||
key = str(field.get("key") or "")
|
||
label = str(field.get("label") or key)
|
||
# 条件 / 级联指向自己是配错(显示与否不能由自己的当前值决定);
|
||
# 带出规则读自己才是常态 —— 从本字段的字典项里取 extra。
|
||
for dep in linkage.condition_dependencies(field):
|
||
if dep == key:
|
||
problems.append(f"「{label}」的联动条件引用了自己")
|
||
elif dep not in keys:
|
||
problems.append(f"「{label}」的联动条件引用了不存在的字段「{dep}」")
|
||
for dep in linkage.auto_fill_dependencies(field):
|
||
if dep != key and dep not in keys:
|
||
problems.append(f"「{label}」的带出规则引用了不存在的字段「{dep}」")
|
||
for dep in linkage.auto_fill_targets(field):
|
||
if dep not in keys:
|
||
problems.append(f"「{label}」的带出规则写向了不存在的字段「{dep}」")
|
||
elif dep == key:
|
||
problems.append(f"「{label}」的带出规则不能写回自己")
|
||
for name in ("visibleWhen", "requiredWhen", "readonlyWhen"):
|
||
condition = field.get(name)
|
||
if condition in (None, "", {}, []):
|
||
continue
|
||
if not isinstance(condition, dict):
|
||
problems.append(f"「{label}」的「{name}」配置格式不对")
|
||
continue
|
||
for rule in condition.get("rules") or []:
|
||
if isinstance(rule, dict) and str(rule.get("op") or "eq") not in linkage.CONDITION_OPS:
|
||
problems.append(f"「{label}」的「{name}」用了不支持的比较符 {rule.get('op')}")
|
||
return problems
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 明细表
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
def columns_of(field: dict) -> list[dict]:
|
||
raw = field.get("columns")
|
||
return [item for item in raw if isinstance(item, dict)] if isinstance(raw, list) else []
|
||
|
||
|
||
def table_column_types() -> tuple[str, ...]:
|
||
return TABLE_COLUMN_TYPES
|
||
|
||
|
||
def _int(value: object, default: int = 0) -> int:
|
||
try:
|
||
return int(value) # type: ignore[arg-type]
|
||
except (TypeError, ValueError):
|
||
return default
|
||
|
||
|
||
def row_is_empty(row: dict, columns: list[dict]) -> bool:
|
||
keys = [str(item.get("key") or "") for item in columns] or list(row.keys())
|
||
return all(empty_value({"__value__": row.get(key)}) for key in keys)
|
||
|
||
|
||
def rows_of(value: object) -> list[dict]:
|
||
"""把明细表字段的值收成对象数组;脏数据、标量、嵌套数组一律丢掉。"""
|
||
if not isinstance(value, list):
|
||
return []
|
||
return [dict(item) for item in value if isinstance(item, dict)]
|
||
|
||
|
||
#: 能配「默认值」的明细列类型,与前端 ``COLUMN_DEFAULT_TYPES`` 一致。
|
||
#: 只收装得下单个值的那几类:多选、选人、部门、附件、图片、签名、日期区间、关联单据
|
||
#: 一格装的不止一个值,级联要的是整条路径——默认成什么都是设计器替人做主,不开这个口子。
|
||
COLUMN_DEFAULT_TYPES = (
|
||
"text",
|
||
"textarea",
|
||
"number",
|
||
"money",
|
||
"date",
|
||
"datetime",
|
||
"time",
|
||
"select",
|
||
"radio",
|
||
"switch",
|
||
"rate",
|
||
)
|
||
|
||
#: 默认值的写法,对齐界面上那几种原生输入框(date / datetime-local / time)的取值。
|
||
_DEFAULT_DATE = re.compile(r"^\d{4}-\d{2}-\d{2}$")
|
||
_DEFAULT_DATETIME = re.compile(r"^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}")
|
||
_DEFAULT_TIME = re.compile(r"^\d{2}:\d{2}")
|
||
|
||
|
||
def _number(raw: object) -> float | None:
|
||
try:
|
||
return float(str(raw).strip())
|
||
except (TypeError, ValueError):
|
||
return None
|
||
|
||
|
||
def _default_text(raw: object) -> str:
|
||
"""把 ``defaultValue`` 收成比对的文本;布尔 ``True`` 按前端一样写作 ``true``。"""
|
||
if isinstance(raw, bool):
|
||
return "true" if raw else ""
|
||
return str(raw if raw is not None else "").strip()
|
||
|
||
|
||
def column_default_problem(column: dict) -> str:
|
||
"""这一列的默认值写歪了没有:写歪给一句人话,能用回空串。
|
||
|
||
与前端 ``utils/formRuntime.columnDefaultProblem`` 同一把尺子。默认值写歪不会挡住保存,
|
||
只会让那一格永远是空的,还得填单的人自己去猜为什么,所以设计器里就得说清楚。
|
||
"""
|
||
raw = column.get("defaultValue")
|
||
text = _default_text(raw)
|
||
if not text:
|
||
return ""
|
||
kind = str(column.get("type") or "")
|
||
shown = f"「{text}」"
|
||
if kind not in COLUMN_DEFAULT_TYPES:
|
||
return f"是 {kind or '未设置'} 列,配不了默认值"
|
||
if kind in ("number", "money"):
|
||
return "" if _number(text) is not None else f"{shown}不是数字,默认值填不进数字格"
|
||
if kind == "rate":
|
||
stars = _number(text)
|
||
top = _int(column.get("max"), 5) or 5
|
||
if stars is None or not float(stars).is_integer() or not 1 <= stars <= top:
|
||
return f"{shown}不是 1-{top} 之间的整数星级"
|
||
return ""
|
||
if kind == "switch":
|
||
return "" if text in ("true", "1") else f"{shown}不是开关认的值(只能选「默认打开」)"
|
||
if kind == "date":
|
||
return "" if _DEFAULT_DATE.match(text) else f"{shown}不是 2026-01-31 这样的日期"
|
||
if kind == "datetime":
|
||
return "" if _DEFAULT_DATETIME.match(text) else f"{shown}不是 2026-01-31 09:00 这样的日期时间"
|
||
if kind == "time":
|
||
return "" if _DEFAULT_TIME.match(text) else f"{shown}不是 09:30 这样的时间"
|
||
# 下拉与单选:静态选项时得选得到一个;绑字典的条目在这儿读不到,交给提交那道闸判。
|
||
if kind in ("select", "radio") and not str(column.get("dictCode") or "").strip():
|
||
options = column.get("options")
|
||
options = options if isinstance(options, list) else []
|
||
if options and not any(
|
||
str((item or {}).get("value") if isinstance(item, dict) else item).strip() == text for item in options
|
||
):
|
||
return f"默认值「{text}」不在这一列的选项里"
|
||
return ""
|
||
|
||
|
||
def column_default(column: dict) -> Any:
|
||
"""这一列真正能落进格子的默认值;没配、类型不支持、写歪、归本行公式算,一律回 ``None``。
|
||
|
||
塑形口径与前端 ``columnDefault`` 一致:数字那三类存数,日期时间存控件认的 ``T`` 写法,
|
||
开关只有「默认打开」值得写(关着本来就等于没配)。
|
||
"""
|
||
if str(column.get("formula") or "").strip():
|
||
return None
|
||
if column_default_problem(column):
|
||
return None
|
||
raw = column.get("defaultValue")
|
||
text = _default_text(raw)
|
||
if not text:
|
||
return None
|
||
kind = str(column.get("type") or "")
|
||
if kind in ("number", "money", "rate"):
|
||
value = _number(text)
|
||
if value is None:
|
||
return None
|
||
return int(value) if float(value).is_integer() else value
|
||
if kind == "switch":
|
||
return True
|
||
return text.replace(" ", "T") if kind == "datetime" else text
|
||
|
||
|
||
def fill_row_defaults(columns: list[dict], row: dict) -> dict:
|
||
"""把配了默认值的列补齐:只补还空着的那一格,别人填过的一个都不动。"""
|
||
fillers = [(str(item.get("key") or ""), column_default(item)) for item in columns]
|
||
targets = [(key, value) for key, value in fillers if key and value is not None]
|
||
for key, value in targets:
|
||
if empty_value({"__value__": row.get(key)}):
|
||
row[key] = value
|
||
return row
|
||
|
||
|
||
def normalise_rows(value: object, field: dict) -> list[dict]:
|
||
"""落库前的整型:只留认识的列、丢空行、补齐默认值、按 ``maxRows`` 截断。
|
||
|
||
默认值排在丢空行之后:整行没碰过的照样丢掉,别拿默认值凭空造出一行来;
|
||
添了行又只填了一格的人,其余空格则由默认值替他填好。
|
||
"""
|
||
columns = columns_of(field)
|
||
allowed = {str(item.get("key") or "") for item in columns}
|
||
rows: list[dict] = []
|
||
for row in rows_of(value):
|
||
kept = {k: v for k, v in row.items() if not allowed or k in allowed}
|
||
if row_is_empty(kept, columns):
|
||
continue
|
||
rows.append(fill_row_defaults(columns, kept))
|
||
max_rows = _int(field.get("maxRows"), 0)
|
||
return rows[:max_rows] if max_rows else rows
|
||
|
||
|
||
def column_total(value: object, field: dict, column_key: str = "") -> float:
|
||
"""明细表某一列的合计;不传列名时取第一个数值列。"""
|
||
columns = columns_of(field)
|
||
target = str(column_key or "")
|
||
if not target:
|
||
numeric = [
|
||
str(item.get("key") or "")
|
||
for item in columns
|
||
if str(item.get("type") or "") in ("number", "money")
|
||
]
|
||
target = numeric[0] if numeric else ""
|
||
if not target:
|
||
return 0.0
|
||
total = 0.0
|
||
for row in rows_of(value):
|
||
try:
|
||
total += float(row.get(target) or 0)
|
||
except (TypeError, ValueError):
|
||
continue
|
||
return round(total, 2)
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 计算公式字段
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
def formula_fields(fields: Iterable[dict]) -> list[dict]:
|
||
out: list[dict] = []
|
||
for item in fields:
|
||
if str(item.get("type") or "") != "formula":
|
||
continue
|
||
if not str(item.get("formula") or "").strip():
|
||
continue
|
||
if not str(item.get("key") or "").strip():
|
||
continue
|
||
out.append(item)
|
||
return out
|
||
|
||
|
||
def compute_formulas(fields: Iterable[dict], data: dict, context: dict) -> dict:
|
||
"""按公式重算 ``formula`` 字段,返回算出来的增量。
|
||
|
||
单个字段算不出来不影响别的字段:把错的那格留空并记进 ``_formulaErrors``,
|
||
界面据此提示,流程不会被一个写坏的表达式卡死。
|
||
"""
|
||
from ..engine import expressions # 延迟导入:engine 反过来会 import 本模块
|
||
|
||
items = formula_fields(fields)
|
||
if not items:
|
||
return {}
|
||
payload = {**context, "data": {**(data or {})}}
|
||
out: dict[str, Any] = {}
|
||
errors: dict[str, str] = {}
|
||
for item in items:
|
||
key = str(item.get("key") or "")
|
||
source = str(item.get("formula") or "")
|
||
payload["data"] = {**(data or {}), **out}
|
||
try:
|
||
value = expressions.evaluate(source, payload)
|
||
except expressions.ExpressionError as exc:
|
||
errors[key] = str(exc)
|
||
continue
|
||
out[key] = _plain(value)
|
||
if out:
|
||
data.update(out)
|
||
if errors:
|
||
data["_formulaErrors"] = errors
|
||
return out
|
||
|
||
|
||
def _plain(value: object) -> Any:
|
||
"""公式结果只留 JSON 存得下的类型,别的(日期、集合)统一转文本。"""
|
||
if value is None or isinstance(value, (str, int, float, bool)):
|
||
return value
|
||
if isinstance(value, (list, tuple)):
|
||
return [_plain(item) for item in value]
|
||
if isinstance(value, dict):
|
||
return {str(k): _plain(v) for k, v in value.items()}
|
||
return str(value)
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 金额中文大写
|
||
# ---------------------------------------------------------------------------
|
||
|
||
_CN_NEGATIVE = "负"
|
||
_CN_ZERO = "零元整"
|
||
|
||
|
||
def chinese_upper(amount: object) -> str:
|
||
"""数字金额转中文大写,口径与财务票据一致(到角分,整尾补「整」)。"""
|
||
try:
|
||
value = float(amount) # type: ignore[arg-type]
|
||
except (TypeError, ValueError):
|
||
return ""
|
||
if value != value: # NaN
|
||
return ""
|
||
if abs(value) >= 1e16:
|
||
return ""
|
||
negative = value < 0
|
||
value = abs(round(value + 1e-9, 2))
|
||
yuan = int(value)
|
||
cents = int(round((value - yuan) * 100))
|
||
if yuan == 0 and cents == 0:
|
||
return _CN_ZERO
|
||
parts: list[str] = []
|
||
if yuan:
|
||
parts.append(_yuan_text(yuan))
|
||
jiao, fen = divmod(cents, 10)
|
||
if jiao == 0 and fen == 0:
|
||
parts.append("整")
|
||
else:
|
||
if jiao:
|
||
parts.append(f"{_CN_DIGITS[jiao]}角")
|
||
elif yuan:
|
||
parts.append("零")
|
||
if fen:
|
||
parts.append(f"{_CN_DIGITS[fen]}分")
|
||
elif jiao:
|
||
parts.append("整")
|
||
text = "".join(parts)
|
||
if not text:
|
||
text = _CN_ZERO
|
||
return (_CN_NEGATIVE if negative else "") + text
|
||
|
||
|
||
def _yuan_text(yuan: int) -> str:
|
||
"""元以上的部分,按四位一节拼 万 / 亿;不足四位的前面补零(壹佰零贰万零叁佰零肆)。"""
|
||
text = ""
|
||
group = 0
|
||
remaining = yuan
|
||
while remaining:
|
||
section = remaining % 10_000
|
||
remaining //= 10_000
|
||
if section:
|
||
# 低节不足四位说明中间空了高位,读出来要带个零。
|
||
lead = "零" if text and section < 1_000 else ""
|
||
text = _section_text(section) + _CN_GROUPS[group] + lead + text
|
||
group += 1
|
||
return f"{text}元"
|
||
|
||
|
||
def _section_text(section: int) -> str:
|
||
digits = [int(ch) for ch in str(section)]
|
||
length = len(digits)
|
||
out = ""
|
||
zero = False
|
||
for index, digit in enumerate(digits):
|
||
unit = _CN_UNITS[length - index - 1]
|
||
if digit == 0:
|
||
zero = True
|
||
continue
|
||
if zero and out:
|
||
out += "零"
|
||
out += _CN_DIGITS[digit] + unit
|
||
zero = False
|
||
return out
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 设计器校验(前端 validateFields 的服务端镜像)
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
#: 带「单位」这一栏的字段类型:数字、金额、计算公式三类共用同一套数字展现配置,
|
||
#: 与前端 ``FieldInspector.NUMBER_FORMAT_TYPES`` 一致。明细表列没有公式,只有前两类。
|
||
UNIT_FIELD_TYPES = ("number", "money", "formula")
|
||
UNIT_COLUMN_TYPES = ("number", "money")
|
||
#: 单位只是贴在数字框里侧的一小截后缀,超宽会把明细表的格子顶开。
|
||
UNIT_MAX_LENGTH = 8
|
||
#: 纯数字(含符号、小数、千分位)不算单位。
|
||
_NUMERIC_UNIT = re.compile(r"^[-+]?[\d,.]+$")
|
||
|
||
|
||
def unit_problem(raw: object) -> str:
|
||
"""「单位」这一栏写得能不能用,能用回空串。
|
||
|
||
单位是贴在数字框里侧的后缀(``1,200.00 元`` 后面那一小截灰字),不是值。
|
||
填成一个数字(费用报销单曾被填成 ``11``)就麻烦了:它跟输入框里的数值长得
|
||
一模一样,填单的人只会问「这个 11 是哪来的」,说不清是自己填的还是系统算的;
|
||
导出、大写金额、条件分支读的都是数值,这一栏从头到尾只影响观感。
|
||
"""
|
||
unit = str(raw or "").strip()
|
||
if not unit:
|
||
return ""
|
||
if _NUMERIC_UNIT.match(unit):
|
||
return (
|
||
f"「{unit}」是个数字:它会贴在数字框里侧,看着就像填进去的数值。"
|
||
"请写单位(如「元」)或留空"
|
||
)
|
||
if len(unit) > UNIT_MAX_LENGTH:
|
||
return f"「{unit}」太长了,最多 {UNIT_MAX_LENGTH} 个字符"
|
||
return ""
|
||
|
||
|
||
def display_unit(raw: object) -> str:
|
||
"""真贴得出去的单位;配歪的一律当没配(调用方决定要不要补默认值)。
|
||
|
||
新校验只管保存那一刻,库里已经躺着的老表单不会被追溯改写,渲染这层再兜一道:
|
||
「11」这种单位与其在数字框里演一个数值,不如什么都不显示。
|
||
"""
|
||
unit = str(raw or "").strip()
|
||
return "" if not unit or unit_problem(unit) else unit
|
||
|
||
|
||
def validate_schema(fields: Iterable[dict]) -> list[str]:
|
||
"""表单定义本身的问题:明细表没有可用列、公式为空、联动引用悬空等。"""
|
||
problems: list[str] = linkage_problems(fields)
|
||
for index, field in enumerate(fields, start=1):
|
||
key = str(field.get("key") or "")
|
||
label = str(field.get("label") or key) or f"第 {index} 个字段"
|
||
kind = str(field.get("type") or "")
|
||
if kind == "table":
|
||
columns = columns_of(field)
|
||
if not columns:
|
||
problems.append(f"「{label}」还没有任何列")
|
||
seen: set[str] = set()
|
||
# 「选台账」那一列的选项由额度台账供,不要求表单自己配字典或静态选项
|
||
from . import quota as quota_service
|
||
|
||
picked = quota_service.pick_columns(field)
|
||
for column in columns:
|
||
column_key = str(column.get("key") or "").strip()
|
||
column_type = str(column.get("type") or "")
|
||
if not column_key:
|
||
problems.append(f"「{label}」有列没填列名")
|
||
elif column_key in seen:
|
||
problems.append(f"「{label}」列名「{column_key}」重复")
|
||
else:
|
||
seen.add(column_key)
|
||
if column_type not in TABLE_COLUMN_TYPES:
|
||
problems.append(f"「{label}」的列「{column.get('label') or column_key}」类型不支持:{column_type}")
|
||
# 选择类列得有个来源,不然填单时那一格是空的,谁也发现不了
|
||
column_label = str(column.get("label") or column_key)
|
||
sourced = bool(str(column.get("dictCode") or "").strip()) or bool(column.get("options"))
|
||
if column_type == CASCADER_TYPE:
|
||
if not sourced:
|
||
problems.append(f"「{label}」的列「{column_label}」还没选择要用的层级字典")
|
||
elif column_type in OPTION_COLUMN_TYPES and not sourced and column_key not in picked:
|
||
problems.append(f"「{label}」的列「{column_label}」既没写选项也没选字典")
|
||
if column_type in UNIT_COLUMN_TYPES:
|
||
reason = unit_problem(column.get("unit"))
|
||
if reason:
|
||
problems.append(f"「{label}」的列「{column_label}」的单位{reason}")
|
||
# 默认值写歪 = 表单存得下来、那一格却永远空着;带出来源那一条在
|
||
# ``autofill.problems`` 里一起判,两边都是保存那一刻挡下来。
|
||
default_problem = column_default_problem(column)
|
||
if default_problem:
|
||
problems.append(f"「{label}」的列「{column_label}」{default_problem}")
|
||
min_rows = _int(field.get("minRows"), 0)
|
||
max_rows = _int(field.get("maxRows"), 0)
|
||
if min_rows and max_rows and min_rows > max_rows:
|
||
problems.append(f"「{label}」的最少行数大于最多行数")
|
||
if kind == CASCADER_TYPE and not str(field.get("dictCode") or "").strip():
|
||
problems.append(f"「{label}」还没选择要用的层级字典")
|
||
if kind == "formula" and not str(field.get("formula") or "").strip():
|
||
problems.append(f"「{label}」还没有填写计算公式")
|
||
if kind in UNIT_FIELD_TYPES:
|
||
reason = unit_problem(field.get("unit"))
|
||
if reason:
|
||
problems.append(f"「{label}」的单位{reason}")
|
||
return problems
|