"""表单运行时:环节字段权限、明细表、计算公式、金额大写。 三件事都是"同一份表单在不同环节长得不一样、值不全靠人手填"这一类问题, 放在一个模块里,前端对应的镜像是 ``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 os 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", "month", "months", "year", "timerange", "week", "mobile", "email", "idcard", "url", "address", "location", "select", "radio", "checkbox", "switch", "rate", "dept", "cascader", "user", "attachment", "image", "signature", "relation", "picker", ) #: 这几类列得有选项来源:字典编码或手写选项,否则格子里连能点的东西都没有。 OPTION_COLUMN_TYPES = ("select", "radio", "checkbox") #: 天生存一串值的字段类型;下拉框与下拉选择那一格另外看字段上的 ``multiple`` #: (真正该问的是下面那一句,两份清单一起改最容易漏)。 LIST_VALUE_TYPES = ("checkbox", "relation") def holds_list_value(field: dict) -> bool: """这一格存的是一串值吗(多选、关联审批单,以及勾了「可以选好几个」的下拉框 / 下拉选择)。""" return _linkage().holds_list_value(field) #: 不需要参与录入与必填校验的类型。 #: 分组标题与空白占位是纯版面:没有值、没有控件,必填与权限都轮不到它们。 #: ``embed`` 也在这一列:它把一块地方让给外部系统的页面,自己不产生值(方案见 #: docs/embed-page-field-design.md §1)。但它**不是 divider**——它的 key 是环节字段权限 #: 的挂点,"哪一环能看见这个外部页面"是安全边界,api/design.py 那边不放过它。 NON_INPUT_TYPES = ("divider", "description", "group", "spacer", "hidden", "auto", "formula", "embed", "tabs") #: 值由系统带出 / 公式算出来的那两类:永远不给录入框,环节也改不了它,但设计者可以让它 #: 「必填」——要求这一格必须带得出、算得出值。与前端 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 normalize_person_values(db, fields: list[dict], data: dict) -> dict: """把选人字段(含明细表里的选人列)写成登录账号,就地返回同一份 ``data``。 选人控件交出来的本来就是账号,这一层管的是**别人写进来的**:开放接口、找人脚本、 数据源带出的值。DN 会随部门改名漂,落库之前不洗成账号,这一格以后就谁也认不出是谁 (口径见 :mod:`app.service.personref`)。 换的是**认得出是谁**的那些值(一批格子一次换算完,:func:`personref.map_accounts`), 认不出的一律原样留着。这里刻意不按 DN 尾巴剪一刀:部门改过一次名之后 DN 末段就是 姓名(``hub_sync._sync_identity_rows_of`` 按身份名重算),照着尾巴剪等于把一个人洗成 一段中文,比留着原值更糟。同理,只动 ``type=user`` 的格子,文本里带反斜杠的 (``a\\b\\c`` 这种)一律不碰。 """ from . import personref # 延迟导入:这一层是叶子模块,模块级不拽别的服务 if not isinstance(data, dict): return data # (所在容器, 该洗的格子):主表一项,明细表每行一项 targets: list[tuple[dict, tuple[str, ...]]] = [] for field in fields or []: key = str(field.get("key") or "") kind = str(field.get("type") or "") if not key or key not in data: continue if kind == "user": targets.append((data, (key,))) elif kind == "table": columns = tuple( str(column.get("key") or "") for column in columns_of(field) if str(column.get("type") or "") == "user" and str(column.get("key") or "") ) if not columns or not isinstance(data[key], list): continue # 明细行是请求体里的同一批对象,改之前先复制,别把调用方手里的快照也改了 rows: list = [] for row in data[key]: if not isinstance(row, dict): rows.append(row) continue copied = dict(row) rows.append(copied) targets.append((copied, columns)) data[key] = rows values = [ str(item) for container, keys in targets for key in keys for item in (container[key] if isinstance(container[key], list) else [container[key]]) if str(item or "").strip() ] if not values: return data mapping = personref.map_accounts(db, values) if not mapping: return data for container, keys in targets: for key in keys: current = container[key] if isinstance(current, list): container[key] = [mapping.get(str(item).strip(), item) for item in current] elif str(current or "").strip(): container[key] = mapping.get(str(current).strip(), current) return data 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 perm_map(config: object, fields: Iterable[dict] | None = None) -> dict[str, str]: """环节那份字段权限,外加「标签页藏整片 / 藏一页」展开出来的那几笔 hidden。 凡是**要拿这份字典去判某个格子**的地方都走这里,别再直接 :func:`perms_of`:展开这件事 只要有一处漏了,那一处就会对着一格看不见、却仍然必填的字段喊「请填写」——那张单就地卡死。 界面那份(``form_perms`` 原样摊给前端)留的是没展开的原件,前端用 ``utils/tabPages.ts:expandPerms`` 展开同一份,判据只有一份实现的说法不成立, 但两句措辞由 ``check_tabs.py`` 与 ``tabPages.spec.ts`` 钉在一起。 """ perms = perms_of(config) if not perms or not fields: return perms from . import tabpages # 延迟导入:那一层要读 embed,模块级互相引用会绕成圈 return tabpages.expand_perms(fields, perms) def hidden_by_default(field: dict) -> bool: """「默认隐藏」这一档此刻真的算隐藏吗。 只在**这一格没配显示条件**时才算。勾了「默认隐藏」又配了「显示条件」的格子说的是 同一件事的两头:"平时不露,条件成立才露"——说话的是条件,默认值不能把它盖成 "永远不露"。这种配法在设计器里最自然(这一格只归某几个部门填),一旦被默认值吃掉, 格子在哪个环节都不出现,而提交时那一格的值也跟着被丢掉(``editable_keys`` 认的就是 这一句)。没配条件的格子(单据编号、金额大写那类)一个字都不变,照旧全局不露。 前端镜像在 ``utils/formRuntime.hiddenByDefault``。 """ return bool(field.get("hidden")) and not _linkage().has_rules(field.get("visibleWhen")) def effective_perm(field: dict, perms: dict[str, str], data: dict | None = None) -> str: """单个字段在这个环节上的最终权限. 底子是环节配置(没配就看字段自己的 required / readonly / hidden);传了 ``data`` 就再叠一层联动条件。**联动只会往严的方向加**(隐藏 / 只读 / 必填),不会把环节锁死的 字段放开,这样「环节说只读」不会因为某个字段联动而漏水。 """ key = str(field.get("key") or "") named = perms.get(key) if named == PERM_HIDDEN: return PERM_HIDDEN if data is None: # 没有这份数据就算不了联动:勾了「默认隐藏」的格子保守按隐藏算(回看那一屏的口径不变)。 # 字段自己在表单设计器上勾了「默认隐藏」:没有哪一环节点名要它,就按隐藏算, # 值照样存、公式照总算;某环节显式给了别的权限,就是那一环特意要看见它,字段默认让位。 override = named or (PERM_HIDDEN if field.get("hidden") else None) if override == PERM_HIDDEN: return PERM_HIDDEN 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 # 环节显式给了别的权限就是那一环特意要看见它,字段默认让位;没点名时按「默认隐藏」算, # 而配了显示条件并由条件放行到这里的格子,默认值不再说话(见 :func:`hidden_by_default`)。 override = named or (PERM_HIDDEN if hidden_by_default(field) else None) 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 field_hidden(field: dict, perms: "dict[str, str] | None", data: dict | None = None) -> bool: """这一格在这一环**到底露不露**:这个问句的判据只留在这一处。 必填(:func:`missing_required`)、阈值那句红字(前端 ``utils/formThreshold.ts`` 的镜像)、 阈值与额度要不要当场拦人(``threshold.blocked_here`` / ``quota.hidden_keys``)、 外部取数失败要不要当场拦人(``fetch.apply_form``)读的都是这一句——只要有一处自己另写一份, 就会出现"界面上没说、后端真挡"那道缝:审批人点同意被一条屏幕上根本没出现的规则卡在这一环, 看不见、改不动、也没有那句可照着改的话。 ``perms`` 必须是 :func:`perm_map` 展开过的那一份(环节直接设的隐藏、标签页整页隐藏 落到每一格头上的那几笔都在里面),``data`` 用来算字段自己的联动条件。 没给 ``perms``(调用方不知道是哪个环节,例如试算与外部脚本)一律按**露着**算: 宁可按配置挡,也不要在无人知情时悄悄放行。 """ if perms is None: return False return effective_perm(field, perms, data) == PERM_HIDDEN def visible_fields(fields: Iterable[dict], perms: dict[str, str], data: dict | None = None) -> list[dict]: return [item for item in fields if not field_hidden(item, perms, data)] 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 def _kernel(): """取数内核(取值写法 / 源的健康判据 / 入参引用检查),同样延迟导入。""" from . import binding as _binding return _binding #: 候选来源=外部数据源时,那张源除了关键词还要按什么筛(``{form.x}`` 那一份入参表)。 #: 与字段上外部取数的 ``args`` 同一个形状、同一套解析,见 service/binding.py。 OPTION_ARGS_KEY = "dataSourceArgs" #: 级联选择字段:值是从顶级一路到末级的字典项数组,见 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 #: 天生有值的类型:只有开与关两档,没有「没填」这一档 ALWAYS_ANSWERED_TYPES = ("switch",) def answered(field: dict, value: Any) -> bool: """这一格算不算「已经填了」:必填那道闸用它,前端镜像在 ``utils/formRuntime.ts:isAnswered``。 开关是唯一的例外:控件摆出来就是关着的,压根没拨过与存了 ``False`` 是同一件事。 以前这两种都按空算,于是给开关勾上必填的人,只要没去碰那一下就被说成「还没填写」—— 一个根本没有空可填的格子在问人要值。关着就是回答「不」。 """ kind = str(field.get("type") or "").strip() if kind in ALWAYS_ANSWERED_TYPES: return True # 定位那一格存的是一个物件:全是空串的物件要算没填,只写了一句地址要算填了。 if kind == LOCATION_TYPE: return location_filled(value) return not empty_value({"__value__": value}) # --------------------------------------------------------------------------- # 定位 / 时间段 / 星期 / 富文本这几类的取值与把关 # --------------------------------------------------------------------------- #: 定位那格存的物件只认这三个键,脏键一律丢掉(前端镜像 ``utils/formRuntime.locationValue``)。 LOCATION_TYPE = "location" LOCATION_KEYS = ("lng", "lat", "address") #: 星期几的取值:1-7(周一到周日),与前端 ``WEEK_DAY_VALUES`` 一致。 WEEK_DAY_VALUES = ("1", "2", "3", "4", "5", "6", "7") #: 能配「字数上限 / 校验正则」的文本类字段,与前端 ``TEXT_LIMIT_TYPES`` 一致。 TEXT_LIMIT_TYPES = ("text", "textarea", "richtext") #: 能配「允许类型 / 最多几个 / 单个多大」的附件类字段,与前端 ``FILE_LIMIT_TYPES`` 一致。 FILE_LIMIT_TYPES = ("attachment", "image") #: 空白格的高度区间(px),与前端 ``SPACER_MIN_HEIGHT`` / ``SPACER_MAX_HEIGHT`` 一致。 SPACER_MIN_HEIGHT = 8 SPACER_MAX_HEIGHT = 240 #: 正则的判定方式:**整格匹配**(``fullmatch``)。半匹配会让 ``\d{6}`` 放过 #: ``abc123456def``,配的人以为挡住了、其实没挡,所以按整格算并把这句写在属性面板的提示里。 def location_value(value: object) -> dict: """把定位那一格的取值整形成只含 lng / lat / address 的物件,空的那几栏剔掉。""" if not isinstance(value, dict): return {} out: dict[str, str] = {} for key in LOCATION_KEYS: text = str(value.get(key) or "").strip() if text: out[key] = text return out def location_filled(value: object) -> bool: """有经纬度,或者只写了一句地址,都算填了。 浏览器定位在台式机、没授权、非 https 的页面上本来就取不到,只让人补一句地址是 这里有意留的活口——不然外勤单子在没有手机的桌面上就发不出去。 """ hit = location_value(value) return bool(hit.get("address") or (hit.get("lng") and hit.get("lat"))) def location_text(value: object) -> str: """只读、导出、打印里的那一句人话:地址在前,经纬度收在小括号里。""" hit = location_value(value) coord = f"{hit['lng']}, {hit['lat']}" if "lng" in hit and "lat" in hit else (hit.get("lng") or hit.get("lat") or "") address = hit.get("address", "") if address and coord: return f"{address}({coord})" return address or coord def range_text(value: object, sep: str = " ~ ") -> str: """日期区间 / 时间段那两项写成一句人话。""" items = value if isinstance(value, (list, tuple)) else [value] return sep.join(str(item).strip() for item in items if str(item or "").strip()) #: 星期几的中文名(1=周一):导出与标题都念这一份,界面上的那份在前端 i18n。 WEEK_LABELS = {"1": "周一", "2": "周二", "3": "周三", "4": "周四", "5": "周五", "6": "周六", "7": "周日"} def week_text(value: object) -> str: """星期那格念成「周一、周三」;库里存的是 1-7,认不得的值原样退回。""" items = value if isinstance(value, (list, tuple)) else ([] if value in (None, "") else [value]) return "、".join(WEEK_LABELS.get(str(item), str(item)) for item in items if str(item or "").strip()) #: 多选月份那一格的写法:与「月份」同一句式(``2026-10``),跨年也照这个排。 #: 前端镜像在 ``utils/formRuntime.ts`` 的 ``monthList`` / ``monthsText``。 _MONTH_ITEM = re.compile(r"^\d{4}-(0[1-9]|1[0-2])$") def month_list(value: object) -> list[str]: """多选月份的值整形:只留 2026-10 这样的写法,去重、按时间先后排好。""" items = value if isinstance(value, (list, tuple)) else ([] if value in (None, "") else [value]) picked = {text for text in (str(item or "").strip() for item in items) if _MONTH_ITEM.match(text)} return sorted(picked) def months_text(value: object) -> str: """多选月份念成一句人话:连着几个月并成一段。 一年之内写作「2026年10-11月」,跨年写作「2026年12月-2027年2月」,中间断开的各写各的; 同一年里断开的好几段只报一次年份(「2026年1月、3-5月」)。库里存的是 ``["2026-10", "2026-11"]``,直接转字符串会把中括号灌进单元格。 """ indexes = [int(item[:4]) * 12 + int(item[5:]) - 1 for item in month_list(value)] if not indexes: return "" runs: list[list[int]] = [] for index in indexes: if runs and index == runs[-1][1] + 1: runs[-1][1] = index else: runs.append([index, index]) parts: list[str] = [] # 上一年说过一次就不再重复;跨年那一段把两头都写全,之后的一段重新报年, # 否则「、5月」会挂到别人家的年份底下去。 spoken_year: int | None = None for start_index, end_index in runs: start_year, start_month = divmod(start_index, 12) end_year, end_month = divmod(end_index, 12) if start_year != end_year: spoken_year = None parts.append(f"{start_year}年{start_month + 1}月-{end_year}年{end_month + 1}月") continue span = f"{start_month + 1}月" if start_index == end_index else f"{start_month + 1}-{end_month + 1}月" if spoken_year == start_year: parts.append(span) else: spoken_year = start_year parts.append(f"{start_year}年{span}") return "、".join(parts) #: 多选月份那三档挑选姿势:取值与设计器里「挑选方式」是同一套(前端 ``monthsStyleOf``)。 #: #: 这一格的候选是那一年那 12 个月,谈不上候选来源,所以这里**没有「自动」这一档**: #: 没配过就是下拉多选。平铺那一档摊开是 12 个格子、要吃掉一整行,不能当默认。 #: 与前端 ``utils/formRuntime.ts`` 的 ``MONTHS_STYLES`` / ``monthsStyleOf`` 同一份口径。 MONTHS_TYPE = "months" MONTHS_STYLES = ("dropdown", "dialog", "inline") MONTHS_STYLE_DEFAULT = "dropdown" def months_style_of(field: dict) -> str: """这一格该用哪一种姿势挑:认不出的写法(手改的、别的类型留下的)一律回落到默认那档。""" style = str((field or {}).get("pickerStyle") or "").strip() return style if style in MONTHS_STYLES else MONTHS_STYLE_DEFAULT def months_config_problems(field: dict) -> list[str]: """多选月份这一格自己的配置问题(设计期):眼下只有挑选姿势认不认这一条。 保存时 ``api/design.py`` 会把认不出的写法收掉,这一句是给接口与 AI 起草那条路兜底—— 一个不认识的值活到填单那一刻,就只剩渲染器替人猜该画哪一只控件了。 """ style = str(field.get("pickerStyle") or "").strip() if style and style not in MONTHS_STYLES: return [f"的挑选方式不认识:{style}(下拉多选 / 弹出框多选 / 平铺点选 三选一)"] return [] def markdown_text(value: object) -> str: """把 Markdown 原文压成一段适合进表格 / 标题的纯文本。 富文本格存的是原文而不是 HTML,导出时不 strip 的话,一整段排版会连 ``##``、 ``-``、``**`` 一起灌进单元格,Excel 里根本没法读。这里只去记号、不解析语义。 """ text = str(value or "") if not text.strip(): return "" text = re.sub(r"```.*?```", " ", text, flags=re.S) # 整块代码 text = re.sub(r"`([^`]*)`", r"\1", text) # 行内代码 text = re.sub(r"!\[([^\]]*)\]\(([^)]*)\)", r"\1", text) # 图片:只留 alt text = re.sub(r"\[([^\]]*)\]\(([^)]*)\)", r"\1(\2)", text) # 链接:文字(地址) text = re.sub(r"^\s{0,3}#{1,6}\s*", "", text, flags=re.M) # 标题井号 text = re.sub(r"^\s{0,3}>\s?", "", text, flags=re.M) # 引用 text = re.sub(r"^\s*[-*+]\s+", "", text, flags=re.M) # 无序列表 text = re.sub(r"^\s*\d+[.)]\s+", "", text, flags=re.M) # 有序列表 text = re.sub(r"(\*\*|__|\*|_)", "", text) # 加粗斜体 text = re.sub(r"^\s*([-*_]\s*){3,}$", "", text, flags=re.M) # 分割线 return re.sub(r"[ ]+", " ", text).strip() def _text_limit(field: dict) -> int: """字段配的字数上限;没配或配歪回 0(= 不限)。""" raw = field.get("maxLength") try: value = int(str(raw).strip()) except (TypeError, ValueError): return 0 return value if value > 0 else 0 def _pattern_of(field: dict) -> str: return str(field.get("pattern") or "").strip() def text_config_problems(field: dict) -> list[str]: """字数上限与校验正则**本身**配得对不对(设计期判,与前端 ``textConfigProblems`` 同口径)。 编译不过的式子在提交时会被判成"永远不匹配",那一格从此谁都填不对, 所以宁可保存那一刻就挡下来。 """ problems: list[str] = [] raw = field.get("maxLength") if raw is not None and str(raw).strip(): try: value = int(str(raw).strip()) except (TypeError, ValueError): problems.append("的字数上限要是一个整数") else: if value < 1 or value > 100000: problems.append("的字数上限要在 1-100000 之间") pattern = _pattern_of(field) if pattern: try: re.compile(pattern) except re.error: problems.append(f"的校验正则「{pattern}」编译不过,检查括号与转义") return problems def file_config_problems(field: dict) -> list[str]: """附件那三个限制配得对不对(设计期)。""" problems: list[str] = [] files = field.get("maxFiles") if files is not None and str(files).strip(): try: count = int(str(files).strip()) except (TypeError, ValueError): problems.append("的最多文件数要是一个整数") else: if count < 0 or count > 99: problems.append("的最多文件数要在 0-99 之间(0 = 不限)") size = field.get("maxSizeMb") if size is not None and str(size).strip(): try: megabytes = float(str(size).strip()) except (TypeError, ValueError): problems.append("的单个大小要是一个数字") else: if megabytes < 0 or megabytes > 1024: problems.append("的单个大小要在 0-1024 MB 之间(0 = 不限)") return problems def _file_mime(name: object) -> str: import mimetypes return mimetypes.guess_type(str(name or ""))[0] or "" def accept_hits(accept: object, name: object, extension: object = "") -> bool: """这个文件命中 ``accept`` 那套写法吗(``.pdf`` / ``image/*`` / ``image/png``)。 没配 accept 就是不限;图片那一格默认收 ``image/*``,口径与前端 ``utils/formRuntime.acceptOf`` 一致——界面挡的是体验,这里挡的是绕过界面塞进来的文件。 """ text = str(accept or "").strip() if not text: return True label = str(name or "").strip().lower() ext = str(extension or "").strip().lstrip(".").lower() or ( os.path.splitext(label)[1].lstrip(".") if label else "" ) mime = _file_mime(label or (f"file.{ext}" if ext else "")) for item in (part.strip().lower() for part in text.split(",")): if not item: continue if item.startswith("."): if item[1:] == ext: return True elif item.endswith("/*"): if mime and mime.startswith(item[:-1]): return True elif item == ext or item == label: return True return False def effective_accept(field: dict) -> str: """这一格真正生效的 accept:图片格没配也还是只收图片。""" custom = str(field.get("accept") or "").strip() kind = str(field.get("type") or "") if kind == "image": return custom or "image/*" if kind == "attachment": return custom return "" def _file_items(value: object) -> list[dict]: return rows_of(value) def value_problems(fields: Iterable[dict], perms: dict[str, str], data: dict) -> list[str]: """提交时按字段类型判一次值本身:长度、正则、月份写法、时间段顺序、附件限制。 只判本环节**改得动**的那几格:上一环节留下的旧值格式不对,不该由一个改不动它的 审批人背锅(口径与 ``selection_problems`` 同一套)。 """ problems: list[str] = [] 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 kind = str(field.get("type") or "") value = (data or {}).get(key) label = str(field.get("label") or key) if kind in TEXT_LIMIT_TYPES: text = value if isinstance(value, str) else ("" if value is None else str(value)) limit = _text_limit(field) if limit and len(text.strip()) > limit: problems.append(f"「{label}」超出字数上限({limit} 字,现在 {len(text.strip())} 字)") pattern = _pattern_of(field) if pattern and text.strip(): try: matched = re.fullmatch(pattern, text.strip()) except re.error: # 编译不过的式子在保存那道闸就挡了;库里躺着的旧配置不拦人,只跳过这一条 matched = None if matched is None: problems.append(f"「{label}」的写法不对,要符合{pattern}") elif kind == "month": text = str(value or "").strip() if text and not _DEFAULT_MONTH.match(text): problems.append(f"「{label}」不是 2026-01 这样的月份") elif kind == "year": text = str(value or "").strip() if text and not _DEFAULT_YEAR.match(text): problems.append(f"「{label}」不是 2026 这样的年份") elif kind == "months": items = value if isinstance(value, (list, tuple)) else ([] if value in (None, "") else [value]) odd = [str(item) for item in items if not _MONTH_ITEM.match(str(item or "").strip())] if odd: problems.append(f"「{label}」里有不是 2026-01 这样写法的月份({'、'.join(odd)})") elif kind in ("timerange", "daterange", "week", LOCATION_TYPE): problem = _shape_problem(kind, value) if problem: problems.append(f"「{label}」{problem}") elif kind in FILE_LIMIT_TYPES: problems.extend(_file_problems(field, value, label)) return problems def _shape_problem(kind: str, value: object) -> str: """这几类的值形状:星期几只能是 1-7,时间段得有先后,定位得是个物件。""" if kind == "week": items = value if isinstance(value, (list, tuple)) else ([] if value in (None, "") else [value]) odd = [str(item) for item in items if str(item) not in WEEK_DAY_VALUES] return f"只能勾周一到周日,「{'、'.join(odd)}」不在其中" if odd else "" if kind == "timerange": items = [str(item or "").strip() for item in (value if isinstance(value, (list, tuple)) else [])] filled = [item for item in items if item] odd = [item for item in filled if not _DEFAULT_CLOCK.match(item)] if odd: return f"不是 09:30 这样的钟点({'、'.join(odd)})" if len(filled) == 2 and filled[0] > filled[1]: return f"的结束时间({filled[1]})早于开始时间({filled[0]})" return "" if kind == "daterange": items = [str(item or "").strip() for item in (value if isinstance(value, (list, tuple)) else [])] filled = [item for item in items if item] if len(filled) == 2 and filled[0] > filled[1]: return f"的结束日期({filled[1]})早于开始日期({filled[0]})" return "" if kind == LOCATION_TYPE and value not in (None, "", {}) and not isinstance(value, dict): return "装的不是一个位置(经纬度 + 地址)" return "" def _file_problems(field: dict, value: object, label: str) -> list[str]: """附件格的三道限制:几个、单个多大、什么类型。库里存的每条自带 name / extension / length。""" problems: list[str] = [] items = _file_items(value) if not items: return problems max_files = _int(field.get("maxFiles"), 0) if max_files and len(items) > max_files: problems.append(f"「{label}」最多只能挂 {max_files} 个文件,现在有 {len(items)} 个") megabytes = _number(field.get("maxSizeMb")) or 0 if megabytes > 0: for item in items: size = _number(item.get("length")) or 0 if size > megabytes * 1024 * 1024: problems.append( f"「{label}」里的「{item.get('name') or '未命名'}」有 {round(size / 1024 / 1024, 1)} MB," f"超过这一格限的 {megabytes:g} MB" ) accept = effective_accept(field) if accept: for item in items: if not accept_hits(accept, item.get("name"), item.get("extension")): problems.append( f"「{label}」里的「{item.get('name') or '未命名'}」不是允许的类型(只收 {accept})" ) return problems 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 not answered(field, (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 not answered(column, row.get(column_key)): problems.append(f"「{label}」第 {index} 行的「{column.get('label') or column_key}」还没填写") # 列里那几样新限制(字数、正则、月份写法、时间段先后、星期、附件三个限制)也判: # 明细列与主表共用一只控件,只判主表等于列上开了个口子。 for problem in value_problems([column], {}, row): problems.append(problem.replace(f"「{column.get('label') or column_key}」", f"「{label}」第 {index} 行的「{column.get('label') or column_key}」", 1)) 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 {}) # 值本身合不合这一格的规矩(字数、正则、月份写法、时间段先后、附件的类型与大小): # 界面上都挡过一遍,这里是有权威权的那一道,绕不过去。 problems.extend(value_problems(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.stored_of(field, 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 "" if _kernel().entries(field.get("fetch")): # 那一格不是人选的,是提交这一刻外部取数写进来的。不说这句,填单的人 # 就只能站在一个自己填不了的格子前问「这个值是哪来的」 problems.append( f"「{field.get('label') or key}」由外部取数带回的取值不在可选范围内" f"(候选来自{'数据字典' if str(field.get('dictCode') or '').strip() else '手填选项'}," "把那一项补进清单,或把这一格的候选来源改成外部数据源 / 流程单据)" ) continue 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: """这个字段的可选项会不会随别的字段变化(字典 / 级联 / 带条件的选项)。""" linkage = _linkage() # 候选来自流程单据 / 外部数据源的格子:服务端手上只有搜出来的那一页, # 拿它当合法值清单会把人正常选中的单据判成越界,这一类交给对面系统说话。 if not linkage.constrains_values(field): return False 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", "month", "year", "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}") _DEFAULT_MONTH = re.compile(r"^\d{4}-(0[1-9]|1[0-2])$") _DEFAULT_YEAR = re.compile(r"^\d{4}$") _DEFAULT_CLOCK = re.compile(r"^([01]\d|2[0-3]):[0-5]\d$") 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 == "month": return "" if _DEFAULT_MONTH.match(text) else f"{shown}不是 2026-01 这样的月份" if kind == "year": return "" if _DEFAULT_YEAR.match(text) else f"{shown}不是 2026 这样的年份" # 下拉与单选:静态选项时得选得到一个;绑字典的条目在这儿读不到,交给提交那道闸判。 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", "year"): 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 data_source_row(db, code: str): """候选来源指向的那张数据源;没给 ``db``(设计器镜像那一份)就不去查库。""" if db is None or not str(code or "").strip(): return None from sqlalchemy import select from .. import models return db.execute( select(models.DataSource).where(models.DataSource.code == str(code).strip()) ).scalar_one_or_none() def option_source_problems(field: dict, db=None, keys: set[str] | None = None) -> list[str]: """候选来源与挑选方式配到哪一步了,几句话说明白(前端镜像 ``utils/optionSource.optionSourceProblems``)。 管三类毛病:配得半截(选了字典没挑字典、选了源没挑源、样式跟这一格不搭)、 指向的源已经不能用(删了 / 停了 / 不是列表型 / 方向只在往外写),以及这一格同时 挂着外部取数、两边口径互相打脸。前两类是「存得下来、填单时那一格是空的」, 第三类是「界面看着挺好、提交那一刻被拦」,都在保存这一刻挡下来。 ``db`` 不给就只判写法与结构(前端镜像那份拿不到库);``keys`` 是同一张表单里 已有的字段名,用来判候选入参里的 ``{form.x}`` 引用有没有掉在地上。 """ linkage = _linkage() kernel = _kernel() field_type = str(field.get("type") or "") if field_type not in linkage.OPTION_SOURCE_TYPES: return [] kinds = linkage.source_kinds_of(field_type) problems: list[str] = [] declared = str(field.get("optionSource") or "").strip() if declared and declared not in kinds: problems.append(f"这类字段挑不了「{declared}」这种候选来源,请重新选一个") kind = linkage.source_kind_of(field) if kind == linkage.SOURCE_DICT and not str(field.get("dictCode") or "").strip(): problems.append("还没选择要用的数据字典") source_code = str(field.get("dataSourceCode") or "").strip() args_at = "候选来源那张数据源" if kind == linkage.SOURCE_DATA_SOURCE and not source_code: problems.append("还没选择要用哪一张外部数据源") if kind == linkage.SOURCE_DATA_SOURCE and source_code: if db is not None: # 源被删 / 停用 / 是取一个值的 / 方向只在往外写:填单那一格只会是一个空下拉。 # 判据与「字段上的外部取数」「字典绑的外部来源」共用内核那一句(service/binding.py) reason = kernel.source_problem( source_code, data_source_row(db, source_code), want=kernel.WANT_SEARCH, want_noun="候选", ) if reason: problems.append(reason) problems.extend(kernel.arg_ref_problems( field.get(OPTION_ARGS_KEY), keys or set(), args_at, self_ref=str(field.get("key") or "").strip(), )) # 勾了「可以选好几个」之后这一格存的是一串值:额度与外部取数那两头都只认一笔 / 一个值 if linkage.holds_list_value(field) and isinstance(field.get("quota"), dict): problems.append( "这一格控一笔额度,只能挑一笔:勾了「可以选好几个」之后额度那一头认不出选中的是哪一笔,请取消多选" ) if linkage.holds_list_value(field) and kernel.entries(field.get("fetch")): problems.append( "这一格的值由外部取数写入,取的是一笔;勾了「可以选好几个」之后两边存的形状对不上,请取消多选" ) if linkage.holds_list_value(field) and isinstance(field.get("threshold"), dict): problems.append( "这一格的阈值条件比的是一个值;勾了「可以选好几个」之后这条条件多半永远不命中," "请取消多选或换个格子" ) # 手填那条路:每个选项自己填「显示文字」和「存的值」,存的值空着等于选了就存个空白 if kind == linkage.SOURCE_MANUAL: raw_options = field.get("options") blank = [ item for item in (raw_options if isinstance(raw_options, list) else []) if isinstance(item, dict) and not str(item.get("value") or "").strip() ] if blank: problems.append(f"有 {len(blank)} 个选项没填要存的值,填了会存成空白") problems.extend(linkage.option_map_problems(field)) problems.extend(linkage.picker_display_problems(field)) if kernel.entries(field.get("fetch")) and linkage.constrains_values(field): # 这一格的值是提交那一刻外部取数写进来的,而候选是判越界的那两种来源: # 两边各自都配得对,凑一起必定在 selection_problems 上炸给填单的人看 problems.append( f"这一格的值由外部取数写入,候选又来自{'手填选项' if kind == linkage.SOURCE_MANUAL else '数据字典'}" ":取回来的编码必须在那份清单里,否则提交时会被判「取值已不在可选范围内」。" "请把取数带回的值补进这份清单,或把候选来源改成外部数据源 / 流程单据" ) # 一串值配下拉不再是问题:那只下拉带勾选框,挑中的几条挂在框里(前端 ``Select`` 的 multiple) style = str(field.get("pickerStyle") or "").strip() if style and style not in linkage.PICKER_STYLES: problems.append(f"挑选方式不认识:{style}") elif style == "inline" and kind in linkage.SEARCHED_SOURCES: problems.append("这一格的候选是搜出来的,铺不成一排,请改成下拉选项或弹出框") return problems def validate_schema(fields: Iterable[dict], db=None) -> list[str]: """表单定义本身的问题:明细表没有可用列、公式为空、联动引用悬空等。 ``db`` 给了才判得动「引用的数据源还在不在」那一类,设计器保存那条路要传。 """ rows = [item for item in fields if isinstance(item, dict)] field_keys = {str(item.get("key") or "").strip() for item in rows} problems: list[str] = linkage_problems(rows) # 「一张表单只有一个标签页」要数出现次数;记下第一个的位置,好跟前端说同一句话 tabs_at = 0 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() # 明细列的候选入参只能引用同一张表里的列名 column_keys = {str(item.get("key") or "").strip() for item in columns} # 「选台账」那一列的选项由额度台账供,不要求表单自己配字典或静态选项 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(str(column.get("dataSourceCode") 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}」既没写选项也没选字典") for reason in option_source_problems(column, db, column_keys): problems.append(f"「{label}」的列「{column_label}」{reason}") if column_type in UNIT_COLUMN_TYPES: reason = unit_problem(column.get("unit")) if reason: problems.append(f"「{label}」的列「{column_label}」的单位{reason}") if column_type == MONTHS_TYPE: for reason in months_config_problems(column): 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}") if column_type in TEXT_LIMIT_TYPES: problems.extend( f"「{label}」的列「{column_label}」{reason}" for reason in text_config_problems(column) ) if column_type in FILE_LIMIT_TYPES: problems.extend( f"「{label}」的列「{column_label}」{reason}" for reason in file_config_problems(column) ) 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}」还没选择要用的层级字典") for reason in option_source_problems(field, db, field_keys): problems.append(f"「{label}」{reason}") 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}") # 字数上限 / 校验正则 / 附件三个限制 / 空白格高度:配歪了当场说。 # 编译不过的正则在提交时会被判成「永远不匹配」,那一格从此谁都填不对, # 比少配一项严重得多,不能留到运行时。 if kind in TEXT_LIMIT_TYPES: problems.extend(f"「{label}」{reason}" for reason in text_config_problems(field)) if kind in FILE_LIMIT_TYPES: problems.extend(f"「{label}」{reason}" for reason in file_config_problems(field)) if kind == MONTHS_TYPE: problems.extend(f"「{label}」{reason}" for reason in months_config_problems(field)) if kind == "spacer" and field.get("height") not in (None, ""): height = _number(field.get("height")) if height is None or height < SPACER_MIN_HEIGHT or height > SPACER_MAX_HEIGHT: problems.append( f"「{label}」的空白高度要在 {SPACER_MIN_HEIGHT}-{SPACER_MAX_HEIGHT}px 之间" ) if kind == "embed": # 局部导入:embed 那层要问注册表,模块级互相引用会绕成圈(与上面 quota 同一处理) from . import embed as embed_service problems.extend(embed_service.problems(field, db, at=f"「{label}」", field_keys=field_keys, targets=rows)) if kind == "tabs": # 标签页那一格只判"这几页配得对不对";页里那些格子还是按它们自己的类型各判各的, # 归属这件事不参与任何校验——这正是把字段平铺而不是嵌进来的好处。 from . import tabpages problems.extend(tabpages.problems(field, db, at=f"「{label}」", field_keys=field_keys, targets=rows)) if tabs_at: # 两个页签各切一屏,第二个切的是谁?与前端 formLayout.validateFields 同一句 problems.append(f"标签页字段只能有一个(第 {tabs_at} 个与第 {index} 个)") else: tabs_at = index return problems