"""候选来源的条件路由(``optionRoutes``)与「带出的值也收下」的验收脚本(不连库):: PYTHONPATH=. python3 scripts/check_option_routes.py 用户那句原话:**「我一个组件中为什么不能配置多个外部数据源、数据字典?我通过表单中字段 来判断我该组件中该用什么数据源。」** 以前一格只有一答(要么字典、要么一张源、要么手填那几条), 要换家只有两条路:摆三格用显隐条件把另外两格藏起来(三格 = 三个字段名 = 三份导出列与三套环节 权限),要么去对面求一个聚合接口。这一层给第三答——字段上多挂一份**有序清单**,每一条 = 一个触发条件 + 一套候选来源配置,自上而下第一条成立的用它,一条都不成立回落到字段自己那一份 (= 改动前行为,老表单一个字节都不用改)。设计见 ``docs/option-source-routing-design.md``。 下面九件事必须一直成立: 1. **只有一份判据**:命中哪一条、按哪一条取候选、按哪一条判越界,三处必须是同一个结果。 界面按 A 家的候选渲染、提交按 B 家判越界,是这一整套最容易犯的错(前端镜像 ``src/utils/optionSource.ts``,第 9 段把两份算法的常量与措辞逐句对); 2. **脏条目当没配**:认不出的来源、配到一半的空条目、第 9 条起多出来的都丢掉,宁可回落; 3. **视图只动来源那一维**:挑选方式、多选、关联带出这些与来源无关的格子原样留着, 而且不许多改一张字段传进来的那份; 4. **保存那一刻洗得干净**:``api/design.py`` 走的是 ``dicts.clean_routes``,主表字段与 明细列两条路都要过,级联与多选月份那两类压根没有候选来源,清单得整份抹掉; 5. **「带出的值不在候选里也收下」真收**:勾上之后越界不拦(``selection_problems`` 那一档), 没勾照旧拦——默认关,老表单行为一字不变; 6. **上游问得全**:删字典前的「哪些表单在用」、预取清单、级联清失效值,都得把路由里那几本 字典与那些触发条件字段算进来,漏一处就是「界面拿着上一家的候选清单继续判越界」; 7. **回看与必填不再死锁**:因**显示条件不成立**而藏起来的系统带出格不再算必填(那句 「屏幕上没有那一格,提交却永远说它没填」),勾了默认隐藏又没配条件的照旧仍然要有值; 8. **外部取数那一头同一分寸**:条目上配了触发条件的只跑成立的那几条(``binding.active_entries`` ↔ 前端 ``formFetch.activeFetchEntries``),一条都不成立=这一格这回不取数,不是失败; 9. **翻名字跟着命中的那一条走**:同一格这一单用差标字典、那一单用费用科目,只读与标题 念出来的名字得按**那一单当时命中的那一条**翻。 """ from __future__ import annotations import inspect import pathlib import re import sys sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent)) from app import models # noqa: E402 (需要上面那行把 backend 目录放进 sys.path) from app.api import design as design_api # noqa: E402 (保存那一刻真正走的那一步清洗) from app.service import binding, dicts, exportfmt, fetch, formruntime, titles # noqa: E402 FAILS: list[str] = [] TRAVEL = {"match": "all", "rules": [{"field": "expenseType", "op": "eq", "value": "travel"}]} MEET = {"match": "all", "rules": [{"field": "expenseType", "op": "eq", "value": "meet"}]} DICT_ITEMS = { "acct_common": [ {"value": "C1", "label": "通用科目一", "enabled": True}, {"value": "C2", "label": "通用科目二", "enabled": True}, ], "acct_travel": [ {"value": "T1", "label": "火车票", "enabled": True}, {"value": "T2", "label": "住宿费", "enabled": True, "extra": {"code": "TR-01"}}, ], "region": [ {"value": "GD", "label": "广东", "enabled": True}, {"value": "GD_SZ", "label": "深圳", "parent": "GD", "enabled": True}, ], } def eq(name: str, got, want) -> None: """取值相等;不等就把两边都打出来,方便一眼看出是形状变了还是值变了。""" if got != want: FAILS.append(f"{name}:期望 {want!r},实得 {got!r}") def ok(name: str, condition, detail=None) -> None: if not condition: FAILS.append(f"{name}:{detail if detail is not None else '条件不成立'}") class FakeCache: """顶替 ``dicts.DictCache``:这一层只用到 ``items`` 与 ``index`` 两句。""" def __init__(self, mapping: dict[str, list[dict]] | None = None) -> None: self.mapping = mapping if mapping is not None else DICT_ITEMS def items(self, code: str) -> list[dict]: return [dict(item) for item in self.mapping.get(code, [])] def index(self, code: str) -> dict[str, dict]: return {str(item.get("value")): dict(item) for item in self.items(code)} def prefetch(self, codes): # pragma: no cover - 预取不是这一份脚本要钉的 return None class Source: """顶替 ``DataSource`` 那一行:``source_problem`` 只用 getattr 读几个属性。""" def __init__(self, code: str, name: str = "", enabled: bool = True, kind: str = models.DataSource.KIND_SEARCH) -> None: self.code = code self.name = name or code self.enabled = enabled self.kind = kind self.direction = models.DataSource.DIRECTION_IN class FakeDB: """一个用例只查一张源:把要给它的那一行(或 ``None``)存好就行。""" def __init__(self, row: Source | None) -> None: self.row = row def execute(self, _statement): row = self.row class _Result: def scalar_one_or_none(self): return row return _Result() def subject(**patch: object) -> dict: """一张「报销科目」下拉:字段自己那一份是兜底候选(一本通用字典)。""" field = { "key": "expenseItem", "label": "报销科目", "type": "select", "optionSource": "dict", "dictCode": "acct_common", } field.update(patch) return field def routes() -> list[dict]: """两条最常见的换家:差旅问一本字典、招待问一张 ERP 源。""" return [ {"source": "dict", "when": TRAVEL, "dictCode": "acct_travel"}, {"source": "dataSource", "when": MEET, "dataSourceCode": "erp_meet"}, ] def values_of(items) -> list[str]: return [str(item.get("value")) for item in (items or [])] # --------------------------------------------------------------------------- # 1. 命中哪一条:有序、第一条成立的说话、全不成立回落 # --------------------------------------------------------------------------- def check_matching() -> None: """回落到字段自己那一份 = 改动前的行为,这一条是整个特性的地基。""" plain = subject() eq("没配清单就是空", dicts.routes_of(plain), []) eq("没配清单没有命中", dicts.matched_route(plain, {"expenseType": "travel"}), None) eq("没配清单视图就是字段本身", dicts.option_view(plain, {"expenseType": "travel"}), plain) eq("候选照旧是字段上那本字典", values_of(dicts.effective_options(plain, {}, FakeCache())), ["C1", "C2"]) routed = subject(optionRoutes=routes()) eq("命中第一条", (dicts.matched_route(routed, {"expenseType": "travel"}) or {}).get("dictCode"), "acct_travel") eq("取的是那一条的候选", values_of(dicts.effective_options(routed, {"expenseType": "travel"}, FakeCache())), ["T1", "T2"]) # 外部数据源那一条:候选是搜出来的,服务端手上没有全量清单,一律回 None(与不挂路由时同一句) eq("命中外部数据源那条时没有全量清单", dicts.effective_options(routed, {"expenseType": "meet"}, FakeCache()), None) # 一条都不成立:回落,老表单行为 eq("全不成立回落", dicts.matched_route(routed, {"expenseType": "other"}), None) eq("回落时候选还是字段上那本", values_of(dicts.effective_options(routed, {"expenseType": "other"}, FakeCache())), ["C1", "C2"]) # 顺序敏感:两条都成立时排在上面的赢;没写条件那条恒成立,天生是「其余情况」那一档 both = subject(optionRoutes=[ {"source": "dict", "dictCode": "acct_travel"}, {"source": "dict", "when": TRAVEL, "dictCode": "region"}, ]) eq("排在上面的先说话", (dicts.matched_route(both, {"expenseType": "travel"}) or {}).get("dictCode"), "acct_travel") fallback_last = subject(optionRoutes=[ {"source": "dict", "when": TRAVEL, "dictCode": "acct_travel"}, {"source": "manual", "options": [{"value": "X", "label": "其他"}]}, ]) eq("不成立时轮到那条无条件的兜底", values_of(dicts.effective_options(fallback_last, {}, FakeCache())), ["X"]) # --------------------------------------------------------------------------- # 2. 视图只动来源那一维 # --------------------------------------------------------------------------- def check_view() -> None: """视图是「此刻这一格」那份配置:上一家的残骸不许混进来,与来源无关的格子不许动。""" field = subject( relationProcess="should_not_leak", pickerStyle="dialog", multiple=True, linkFill={"rules": [{"source": "serial", "to": "amount"}]}, optionRoutes=[{"source": "dict", "when": TRAVEL, "dictCode": "acct_travel", "cascadeFrom": "province", "optionMap": {"valueKey": "extra.code", "labelKey": "label"}}], ) view = dicts.option_view(field, {"expenseType": "travel"}) eq("视图换了来源", view.get("optionSource"), "dict") eq("用的是那一条的字典", view.get("dictCode"), "acct_travel") eq("级联上级也来自那一条", view.get("cascadeFrom"), "province") # 别家的痕迹不进视图:留着 dictCode 那种残骸是「界面一个值、提交另一个值」的病根 ok("别家残骸不进视图", "relationProcess" not in view and "dataSourceCode" not in view, list(view)) # 与来源无关的用法原样留着 eq("挑选方式原样", view.get("pickerStyle"), "dialog") eq("多选原样", view.get("multiple"), True) eq("关联带出原样", view.get("linkFill"), {"rules": [{"source": "serial", "to": "amount"}]}) # 传进来的那份没被改脏 eq("字段本体不动", field.get("dictCode"), "acct_common") # 那一条自己那份「显示 / 存值」跟着走:存的值由它说 eq("按那一条的存值列取值", dicts.stored_of(view, {"value": "T2", "label": "住宿费", "extra": {"code": "TR-01"}}), "TR-01") eq("按那一条的显示列念名字", dicts.shown_of(view, {"value": "T2", "label": "住宿费"}), "住宿费") # 挂不上这一类字段的来源:视图原样退回,不会把字段改成它挑不了的样子 radio = {"key": "r", "type": "text", "optionRoutes": [{"source": "dict", "dictCode": "acct_travel"}]} eq("文本框没有候选来源可言", dicts.routes_of(radio), []) # --------------------------------------------------------------------------- # 3. 脏条目当没配:宁可回落,不要一只永远为空的挑选器 # --------------------------------------------------------------------------- def check_dirty() -> None: """接口直传与 AI 起草都会送进奇形怪状的清单,这一层的态度是「当没配」。""" eq("非数组当没配", dicts.routes_of(subject(optionRoutes="nope")), []) eq("条目不是物件的丢掉", dicts.routes_of(subject(optionRoutes=[None, 1, "x"])), []) eq("认不出的来源丢掉", dicts.routes_of(subject(optionRoutes=[{"source": "nope", "dictCode": "x"}])), []) # 关联审批单挑不了手填选项:那一条丢,别的那条照留 relation = { "key": "rel", "type": "relation", "optionSource": "process", "optionRoutes": [{"source": "manual", "options": [{"value": "A", "label": "甲"}]}, {"source": "dict", "dictCode": "acct_travel"}], } eq("这一类字段挑不了的来源单独丢", [item["source"] for item in dicts.routes_of(relation)], ["dict"]) # 空的来源配置不进路由:进了会把视图里那格抹成空,比回落还糟 eq("半截配置只留下认得的那几格", dicts.routes_of(subject(optionRoutes=[{"source": "dict", "when": TRAVEL, "dictCode": ""}])), [{"source": "dict", "when": TRAVEL}]) # 上限:再多就不是「换一家」而是该做聚合接口了,而且清单越长越没人说得清哪一条会赢 many = [{"source": "dict", "dictCode": "a"}] * (dicts.MAX_OPTION_ROUTES + 3) eq("超出上限的截掉", len(dicts.routes_of(subject(optionRoutes=many))), dicts.MAX_OPTION_ROUTES) ok("上限那一句在设计期说", any("多出来的不会被用上" in text for text in dicts.route_problems(subject(optionRoutes=many))), dicts.route_problems(subject(optionRoutes=many))) # --------------------------------------------------------------------------- # 4. 保存那一刻洗得干净(走的是接口真正调的那一步) # --------------------------------------------------------------------------- def check_cleaning() -> None: """``api/design.py`` 保存字段时经过的清洗:清单、上限、残骸、备注、非法开关。""" content = {"fields": [ # 条件点名的那一格得在场,否则 validate_schema 会先说「引用了不存在的字段」 {"key": "expenseType", "label": "报销类型", "type": "select", "options": [{"value": "travel", "label": "差旅"}, {"value": "meet", "label": "招待"}]}, subject(pickerStyle="dialog", optionRoutes=[ # 第一条:备注留着,relationStatuses 那一家带来的空值不留 {"source": "dict", "when": TRAVEL, "dictCode": "acct_travel", "note": "这一条问财务要的", "relationStatuses": [], "relationProcess": ""}, # 第二条:来源认不出 → 整条丢 {"source": "nope", "dictCode": "x"}, # 第三条:全勾状态等于不限 → 不留这个键 {"source": "process", "when": MEET, "relationProcess": "p1", "relationStatuses": list(dicts.RELATION_STATUSES)}, # 第四条:没写条件的兜底那条,条件这个键本来就没有 {"source": "manual", "options": [{"value": "X", "label": "其他"}]}, ]), # 级联与文本框:压根没有候选来源,清单与开关都得整份抹掉 {"key": "c", "type": "dicts_cascader", "dictCode": "region", "optionSource": "dict", "optionRoutes": [{"source": "dict", "dictCode": "a"}], "allowOutsideValue": True}, {"key": "t", "type": "text", "optionRoutes": [{"source": "dict", "dictCode": "a"}], "allowOutsideValue": "true"}, # 明细列也走同一句清洗 {"key": "tbl", "type": "table", "columns": [ {"key": "cate", "label": "类别", "type": "select", "options": [{"value": "A", "label": "甲"}]}, {"key": "item", "label": "科目", "type": "select", "optionSource": "dict", "dictCode": "acct_common", "optionRoutes": [ {"source": "dict", "when": TRAVEL, "dictCode": "acct_travel", "cascadeFrom": "cate"}, {"source": "manual", "options": [{"value": "X", "label": "其他"}]}]}, ]}, ]} content["fields"][2]["type"] = "cascader" # 上面那个占位写法改掉:级联字段就是 type=cascader saved = design_api.clean_option_source(content)["fields"] first = saved[1]["optionRoutes"] eq("认不出的那条整条丢掉", [item["source"] for item in first], ["dict", "process", "manual"]) eq("备注留着(只给配表单的人看)", first[0].get("note"), "这一条问财务要的") eq("别家的空残骸不留", [key for key in ("relationStatuses", "relationProcess") if key in first[0]], []) eq("全勾状态等于不限,不留这个键", "relationStatuses" in first[1], False) eq("兜底那一条不写条件也活得下来", "when" in first[2], False) eq("字段自己那一份留着", saved[1]["dictCode"], "acct_common") ok("级联字段上的清单整份抹掉", "optionRoutes" not in saved[2], saved[2]) ok("文本框上的清单与开关都抹掉", "optionRoutes" not in saved[3] and "allowOutsideValue" not in saved[3], saved[3]) column = saved[4]["columns"][1] eq("明细列同样被洗", [item["source"] for item in column["optionRoutes"]], ["dict", "manual"]) eq("明细列那一条只留下它自己那几格", column["optionRoutes"][0].get("cascadeFrom"), "cate") eq("明细列的级联上级指着同表的列", [col["key"] for col in saved[4]["columns"]][:2], ["cate", "item"]) # 一条有效都不剩:整份抹掉,别留一份空数组让下一任以为配过什么 empty = design_api.clean_option_source({"fields": [subject(optionRoutes=[{"source": "nope"}])]})["fields"][0] ok("全丢光时不留空数组", "optionRoutes" not in empty, empty) # 开关只认真布尔值:字符串 "true" 与 1 都当没配 flags = design_api.clean_option_source({"fields": [ subject(allowOutsideValue=True), subject(allowOutsideValue="true"), subject(allowOutsideValue=1)]})["fields"] eq("开关只认真布尔值", [item.get("allowOutsideValue") for item in flags], [True, None, None]) # 字段自己挂的不是字典、但**某一条候选是字典**:那一档命中时带的就是它那本的附加值, # autoFill 是这一档唯一的配法(外部数据源那一条自己带 fill),不能当上一家的残骸洗掉 routed_fill = { "key": "project", "label": "项目", "type": "select", "optionSource": "dataSource", "dataSourceCode": "erp_project", "autoFill": [{"field": "project", "pick": "code", "to": "projectCode"}], "optionRoutes": [{"source": "dict", "when": TRAVEL, "dictCode": "acct_travel"}], } washed = design_api.clean_option_source( {"fields": [subject(), routed_fill, {**routed_fill, "optionRoutes": [ {"source": "dataSource", "when": TRAVEL, "dataSourceCode": "erp_project"}]}]})["fields"] eq("路由里挂着字典时 autoFill 保住", washed[1].get("autoFill"), routed_fill["autoFill"]) ok("字段与路由都没字典时 autoFill 照旧洗掉", "autoFill" not in washed[2], washed[2]) # 清洗完的表单存得下去:路由不能把 validate_schema 惹出一堆新错 eq("洗过的表单校验通过", formruntime.validate_schema(saved, db=None), []) # --------------------------------------------------------------------------- # 5. 把关跟着命中的那一条走 + 「带出的值也收下」 # --------------------------------------------------------------------------- def check_guard() -> None: """同一格这一分钟是字典(要把关)、下一分钟可能是外部数据源(不把关)。""" routed = subject(optionRoutes=routes()) eq("命中字典要把关", dicts.constrains_values(routed, {"expenseType": "travel"}), True) eq("命中外部数据源不把关", dicts.constrains_values(routed, {"expenseType": "meet"}), False) eq("回落时照旧把关", dicts.constrains_values(routed, {"expenseType": "other"}), True) # 拿不到单据值的那几处(设计期、导出)问的是「有没有要把关的来源」:有一条就算有 eq("不给值时取并集", dicts.constrains_values(routed), True) all_searched = subject(optionSource="dataSource", dictCode=None, dataSourceCode="erp", optionRoutes=[{"source": "process"}]) eq("两条都是搜出来的就不把关", dicts.constrains_values(all_searched), False) # 提交那一刻:值只在「命中那一条」的清单里才算合法 dict_only = subject(optionRoutes=[{"source": "dict", "when": TRAVEL, "dictCode": "acct_travel"}]) eq("命中差旅时选通用科目要拦", formruntime.selection_problems([dict_only], {}, {"expenseType": "travel", "expenseItem": "C1"}, FakeCache()), ["「报销科目」的取值已不在可选范围内"]) eq("命中差旅时选差旅科目放行", formruntime.selection_problems([dict_only], {}, {"expenseType": "travel", "expenseItem": "T1"}, FakeCache()), []) eq("那条不成立时回落到通用字典,C1 又合法了", formruntime.selection_problems([dict_only], {}, {"expenseType": "other", "expenseItem": "C1"}, FakeCache()), []) eq("命中外部数据源那一条时不判越界", formruntime.selection_problems([routed], {}, {"expenseType": "meet", "expenseItem": "ERP-77"}, FakeCache()), []) # 「带出的值不在候选里也收下」:勾上就收,且不影响别的格子。 # 拿**字典**那一头钉:后端只判「会随别的字段变的那三类候选」(字典 / 级联 / 带条件的选项), # 手填且不带条件的那一格本来就不判越界(``_has_option_rule``),页面上由 ``dropStaleSelections`` # 清值 —— 所以这一档最要命的正是字典与外部取数凑在一起的那一格。 fetched = {"key": "level", "label": "职级", "type": "select", "optionSource": "dict", "dictCode": "acct_common", "fetch": {"source": "erp"}} eq("没勾那一档:取数带回来的值照样拦", formruntime.selection_problems([fetched], {}, {"level": "P9"}, FakeCache()), ["「职级」由外部取数带回的取值不在可选范围内(候选来自数据字典," "把那一项补进清单,或把这一格的候选来源改成外部数据源 / 流程单据)"]) opened = {**fetched, "allowOutsideValue": True} eq("勾了那一档:值收下,不拦提交", formruntime.selection_problems([opened], {}, {"level": "P9"}, FakeCache()), []) eq("勾了那一档也不放过清单里的值(照常放行)", formruntime.selection_problems([opened], {}, {"level": "C1"}, FakeCache()), []) eq("多选里带一个越界值同样收下", formruntime.selection_problems([{**opened, "multiple": True}], {}, {"level": ["P9", "C1"]}, FakeCache()), []) # 只读与环节锁死的格子本来就不判越界,这一档不改变那两句 eq("环节只读时不判(老行为)", formruntime.selection_problems([fetched], {"level": "readonly"}, {"level": "P9"}, FakeCache()), []) # 换来源到「搜出来的」那一家:本地清单本来就不管,这一档不需要勾 eq("候选来自外部数据源时本来就不判", formruntime.selection_problems( [{"key": "level", "label": "职级", "type": "select", "optionSource": "dataSource", "dataSourceCode": "erp", "fetch": {"source": "crm"}}], {}, {"level": "P9"}, FakeCache()), []) # --------------------------------------------------------------------------- # 6. 设计期检查:清单本身 + 每一条的来源,逐条问同一句 # --------------------------------------------------------------------------- def check_design_time() -> None: """配到一半就保存的那几条,别等填单的人发现「这一格是空的」。""" eq("没配清单不说", dicts.route_problems(subject()), []) eq("清单不是数组要说", dicts.route_problems(subject(optionRoutes="nope")), ["「报销科目」的候选来源清单要写成一份列表"]) half = subject(optionRoutes=[ {"source": "dict", "when": TRAVEL}, {"source": "dataSource", "when": MEET}, {"source": "manual", "options": []}, {"source": "process", "relationStatuses": []}, {"source": "nope"}, {}, ]) text = "\n".join(dicts.route_problems(half)) for want in ("第 1 条候选来源还没选要用的数据字典", "第 2 条候选来源还没选要用哪一张外部数据源", "第 3 条候选来源一条选项都没填,选到它就是一只空下拉", "第 4 条候选来源:至少勾一种状态", # 来源写歪的说清这类字段挑不了什么,加了还没配完的那一条说轻一点 "第 5 条候选来源的来源这类字段挑不了:nope", "第 6 条候选来源还没选来源"): ok(f"设计期要说:{want}", want in text, text) eq("配得对的清单一个字不多说", dicts.route_problems(subject(optionRoutes=routes())), []) # 「先选项目分类,再问那一家要候选」那一格:候选来自清单,字段自己那一份留空是**有意的** # (分类没选的那一刻本来就没得挑)。保存那道「选项类字段未配置任何选项」的闸不能拦它, # 否则收拢出来的表单存不下去;什么都没配的照旧要拦,别把老规矩一起放宽了。 driver = {"key": "expenseType", "label": "费用类型", "type": "select", "options": [{"value": "travel", "label": "差旅"}, {"value": "meet", "label": "招待"}]} routed = {"fields": [driver, subject(optionSource="manual", options=[], optionRoutes=[ {"source": "dict", "when": TRAVEL, "dictCode": "acct_travel"}, {"source": "dict", "when": MEET, "dictCode": "acct_common"}, ])]} eq("挂了清单、字段自己那份空着 = 保存过得去", design_api.form_problems(routed), []) bare = {"fields": [subject(optionSource="manual", options=[])]} ok("什么都没配的照旧要说", any("未配置任何选项" in text for text in design_api.form_problems(bare)), design_api.form_problems(bare)) # 每一条挑的那一种来源也要配到底:同一套判据,只是换了一张视图 bad_route = subject(optionRoutes=[{"source": "dataSource", "when": TRAVEL, "dataSourceCode": "rate"}]) reasons = formruntime.option_source_problems(bad_route, db=FakeDB(Source( "rate", "汇率", kind=models.DataSource.KIND_FETCH))) ok("那一条指的源是取一个值的要说", any( text.startswith("第 1 条候选来源:") and "汇率" in text for text in reasons), reasons) # 字段自己那一份与路由里那一条各说各的门牌,两句不会串 both_bad = {**bad_route, "optionSource": "dataSource", "dictCode": None, "dataSourceCode": "rate"} reasons = formruntime.option_source_problems(both_bad, db=FakeDB(Source( "rate", "汇率", kind=models.DataSource.KIND_FETCH))) ok("字段自己那一条不带门牌", any(text == "引用的数据源「汇率」是取一个值的,候选要的是列表型数据源" for text in reasons), reasons) eq("两句各说各的门牌,不会串", len(reasons), 2) # 候选入参引用掉在地上:字段级与路由级都问同一句,只是门牌不同 arg_route = subject(optionRoutes=[{"source": "dataSource", "when": TRAVEL, "dataSourceCode": "erp", "dataSourceArgs": {"dept": "{form:gone}"}}]) ok("那一条的入参引用悬空要说", any( text == "第 1 条候选来源:候选来源那张数据源的入参「dept」引用了不存在的字段「gone」" for text in formruntime.option_source_problems(arg_route, db=None, keys={"dept"})), formruntime.option_source_problems(arg_route, db=None, keys={"dept"})) # 拿不到库的那一处不编造:源的健康只在真去查的时候说 eq("不给库时不说源的健康", [text for text in formruntime.option_source_problems(bad_route, db=None) if "汇率" in text], []) def check_filled_by_peers() -> None: """隔壁那一格的带出指着这一格,也算「这一格的值是系统写进来的」。 生产上真有的形状:一张「项目阶段」下拉,值由隔壁「项目名称」的字典带出写进来。 以前这一句只看这一格自己配没配带出,于是设计期说「这一档暂时不起作用」, 人把勾去掉,提交那一刻又被判「取值已不在可选范围内」——两头都骗了他一次。 """ stage = {"key": "stage", "label": "项目阶段", "type": "select", "optionSource": "dict", "dictCode": "project_stage", "allowOutsideValue": True} driver = {"key": "project", "label": "项目名称", "type": "select", "optionSource": "dict", "dictCode": "acct_travel", "autoFill": [{"field": "project", "pick": "stageName", "to": "stage"}]} eq("隔壁的字典带出指着这一格", formruntime.filled_by_label(stage, [stage, driver]), "字典带出") eq("不给同表字段时还是老说法", formruntime.filled_by_label(stage), "") eq("自己那一份排在前面(取一个值写进自己)", formruntime.filled_by_label({**stage, "fetch": {"source": "erp", "pick": "level"}}, [stage, driver]), "外部取数") # 配了带出不等于**这一格**的值是带进来的:去向不在这一格上就不算(生产上「项目名称」 # 配了 autoFill 写别的格子,反被说成「这一格的值由字典带出写入」是这一寸的老毛病) eq("带出的去向不在这一格上不算这一格被写", formruntime.filled_by_label({**driver, "autoFill": [{"field": "project", "pick": "x", "to": "elsewhere"}]}), "") eq("取数只写别的格子也不算这一格被写", formruntime.filled_by_label({"key": "vendor", "type": "select", "optionSource": "dict", "dictCode": "acct_travel", "fetch": {"source": "erp", "picks": {"bank": "bank"}}}), "") eq("取数取一个值写进自己就算", formruntime.filled_by_label({"key": "vendor", "type": "text", "fetch": {"source": "erp", "pick": "project"}}), "外部取数") ok("不说那句空转", not any("暂时不起作用" in text for text in formruntime.option_source_problems(stage, db=None, rows=[stage, driver])), formruntime.option_source_problems(stage, db=None, rows=[stage, driver])) ok("两处都没带出时仍要说那句", any("暂时不起作用" in text for text in formruntime.option_source_problems(stage, db=None, rows=[stage])), formruntime.option_source_problems(stage, db=None, rows=[stage])) # 另外三种去向同样算:外部取数的 picks、候选路由那一条自带的 fill、关联单据带出 fetched = {"key": "amount", "label": "金额", "type": "money"} ok("隔壁外部取数写进来", formruntime.filled_by_label(fetched, [fetched, { "key": "order", "type": "text", "fetch": {"source": "erp", "picks": {"amt": "amount"}}}]) == "外部取数") ok("隔壁那条候选自带的带出写进来", formruntime.filled_by_label(fetched, [fetched, { "key": "vendor", "type": "select", "optionSource": "dataSource", "dataSourceCode": "erp", "optionRoutes": [{"source": "dataSource", "dataSourceCode": "erp", "fill": {"source": "erp_bank", "picks": {"limit": "amount"}}}]}]) == "外部取数") # 隔壁那条取数写的是**它自己**那一格(自带的 pick),不算指着这一格: # 少这一句闸,一张表单里只要有一格配了取数,所有选择类格子都会被说成「值由外部取数写入」 ok("隔壁的取数写它自己那一格,不算指着这一格", formruntime.filled_by_label(fetched, [fetched, { "key": "name", "type": "text", "fetch": {"source": "erp", "pick": "project"}}]) == "") ok("隔壁那条候选的带出写它自己那一格,同样不算", formruntime.filled_by_label(fetched, [fetched, { "key": "vendor", "type": "select", "optionSource": "dataSource", "dataSourceCode": "erp", "fetch": {"source": "erp", "pick": "vendor"}}]) == "") ok("隔壁关联单据带出写进来", formruntime.filled_by_label(fetched, [fetched, { "key": "contract", "type": "select", "optionSource": "process", "relationProcess": "p1", "linkFill": {"rules": [{"pick": "serial", "to": "amount"}]}}]) == "关联单据带出") ok("明细列那种表.列的写法不算指着主表这一格", formruntime.filled_by_label(fetched, [fetched, { "key": "tbl", "type": "table", "columns": [ {"key": "n", "type": "text", "fetch": {"source": "erp", "picks": {"amt": "tbl.amount"}}}]}]) == "") # 反向那一头:值是隔壁带进来的、候选又要判越界、还没勾那一档 → 该说交叉那一句 strict = {k: v for k, v in stage.items() if k != "allowOutsideValue"} reasons = formruntime.option_source_problems(strict, db=None, rows=[strict, driver]) ok("没勾那一档时说的是交叉那一句", any("带出" in text and "不在可选范围内" in text for text in reasons), reasons) # 整张表单走一遍校验:这一句在 validate_schema 那条路上也得拿到同表字段 clean = formruntime.validate_schema([stage, driver], db=None) eq("整表校验里不再误说空转", [text for text in clean if "暂时不起作用" in text], []) eq("发起那一格不再被说成值是带进来的", [text for text in clean if "值由字典带出写入" in text], []) # --------------------------------------------------------------------------- # 7. 上游问得全:字典清单与条件依赖都要把路由算进来 # --------------------------------------------------------------------------- def check_dependencies() -> None: """漏一处就是「一把只挂在路由里的字典能被删掉」与「界面拿上一家候选继续判越界」。""" routed = subject(optionRoutes=[ {"source": "dict", "when": TRAVEL, "dictCode": "acct_travel"}, {"source": "dict", "when": MEET, "dictCode": "region", "cascadeFrom": "province"}, {"source": "dataSource", "dataSourceCode": "erp"}, ]) eq("预取清单把路由里那两本也算上", dicts.codes_of([routed]), ["acct_common", "acct_travel", "region"]) eq("删字典前的「哪些表单在用」也认路由里的", sorted(dicts._codes_in({"fields": [routed]})), ["acct_common", "acct_travel", "region"]) eq("触发条件与那条的级联上级都是这一格的上游", dicts.condition_dependencies(routed), ["province", "expenseType"]) # 字典带出读的是**此刻命中那一条**的字典:选同一个编码在两本字典里带出不同的附加值 fill = {**subject(optionRoutes=[ {"source": "dict", "when": TRAVEL, "dictCode": "acct_travel"}, {"source": "dict", "when": MEET, "dictCode": "acct_common"}, ]), "autoFill": [{"field": "expenseItem", "pick": "code", "to": "amount"}]} amount = {"key": "amount", "label": "金额", "type": "money"} data = {"expenseType": "travel", "expenseItem": "T2", "amount": ""} # 带出去向那一格得还在表单上:格子被删了就不写(老规矩,check_binding.py 里钉过那一段) eq("带出的那一格在场才算数", dicts.apply_auto_fill([fill, amount], data, FakeCache()), ["amount"]) eq("带出按命中的那一本字典取", data["amount"], "TR-01") other = {"expenseType": "meet", "expenseItem": "C1", "amount": ""} dicts.apply_auto_fill([fill, amount], other, FakeCache()) eq("换一张单命中另一本,取的是那一本有的东西", other["amount"], "") # 命中那一条**不是字典**(外部数据源那一家):一个字都不带。 # 少了这一句闸,下面「没有字典就把这一格自己的值搬过去」那一条会把人刚挑中的编码 # 盖到「名称」那一格上(对面前端 items 为空,本来也什么都不写)。 mixed = {**subject(dictCode=None, optionSource="dataSource", dataSourceCode="erp", optionRoutes=[ {"source": "dict", "when": TRAVEL, "dictCode": "acct_travel"}, {"source": "dataSource", "when": MEET, "dataSourceCode": "erp"}, ]), "autoFill": [{"field": "expenseItem", "to": "amount"}]} # 不写 pick =「带名称」:没有那道闸时会走到「没有字典就搬这一格自己的值」那一条, # 把人刚在外部数据源里挑中的编码原样盖到目标格上 hit_ds = {"expenseType": "meet", "expenseItem": "ERP-77", "amount": ""} eq("命中外部数据源那条时不带任何东西", dicts.apply_auto_fill([mixed, amount], hit_ds, FakeCache()), []) eq("命中外部数据源那条时目标格一个字都不写", hit_ds["amount"], "") hit_dict = {"expenseType": "travel", "expenseItem": "T2", "amount": ""} eq("命中字典那条时照带(同一份 autoFill)", dicts.apply_auto_fill([mixed, amount], hit_dict, FakeCache()), ["amount"]) eq("带的是命中那一本的名称", hit_dict["amount"], "住宿费") # 路由里那几本字典:保存那一刻与那句设计期提醒都靠它,自上而下、去重、只认字典那几条 eq("只挑出字典那几条挂的字典", dicts.dict_route_codes(subject(optionRoutes=[ {"source": "dict", "dictCode": "acct_travel"}, {"source": "dataSource", "dataSourceCode": "erp"}, {"source": "dict", "dictCode": "acct_travel"}, {"source": "dict", "dictCode": "region"}, ])), ["acct_travel", "region"]) eq("没挂路由时没有字典可挑", dicts.dict_route_codes(subject()), []) # 设计期那句话:两边都没字典才说,字段上或路由里有一本就不说 dead = {"key": "vendor", "label": "供应商", "type": "select", "optionSource": "dataSource", "dataSourceCode": "erp", "autoFill": [{"field": "vendor", "pick": "code", "to": "amount"}]} sentence = "配了字典带出,可这一格没挂数据字典(字段上与候选来源那几条里都没有),这一档不起作用" ok("两处都没字典时说要一句", sentence in formruntime.option_source_problems(dead, db=FakeDB( Source("erp", "ERP 供应商", kind=models.DataSource.KIND_SEARCH))), formruntime.option_source_problems(dead, db=FakeDB( Source("erp", "ERP 供应商", kind=models.DataSource.KIND_SEARCH)))) ok("路由里挂着一本字典时不说这句", sentence not in formruntime.option_source_problems( {**dead, "optionRoutes": [{"source": "dict", "dictCode": "acct_travel"}]}, db=FakeDB( Source("erp", "ERP 供应商", kind=models.DataSource.KIND_SEARCH)))) ok("字段自己有字典时不说这句", sentence not in formruntime.option_source_problems( {**dead, "dictCode": "acct_common"}, db=FakeDB( Source("erp", "ERP 供应商", kind=models.DataSource.KIND_SEARCH)))) # --------------------------------------------------------------------------- # 8. 回看与必填不再死锁(显示条件不成立 ≠ 这一格没填) # --------------------------------------------------------------------------- def check_required_when_hidden() -> None: """生产上那句「配了显示条件之后提交不过」的病根。 ``auto`` / ``formula`` 这两类没有录入框、权限永远算只读,字段自己又勾了必填, 老判据就连**因显示条件不成立**被收走的格子一起催「还没填写」——屏幕上根本没有那一格, 提交永远过不去。勾了「默认隐藏」又没配条件的(单据编号、金额大写)照旧仍然要有值。 """ gated = {"key": "contractNo", "label": "合同编号", "type": "auto", "required": True, "visibleWhen": {"match": "all", "rules": [{"field": "hasContract", "op": "eq", "value": "1"}]}} eq("条件不成立时算因隐藏", formruntime.hidden_by_condition(gated, {"hasContract": "0"}), True) eq("条件成立时不算", formruntime.hidden_by_condition(gated, {"hasContract": "1"}), False) eq("没配条件不算这一句", formruntime.hidden_by_condition({"key": "a", "type": "auto"}, {}), False) eq("因显示条件藏起来的必填格不卡提交", formruntime.missing_required([gated], {}, {"hasContract": "0"}), []) eq("条件成立却没带值,照旧要那一笔", formruntime.missing_required([gated], {}, {"hasContract": "1"}), ["合同编号"]) quiet = {"key": "code", "label": "单据编号", "type": "auto", "required": True, "hidden": True} eq("勾了默认隐藏又没配条件:藏起来不等于可以不生成", formruntime.missing_required([quiet], {}, {}), ["单据编号"]) eq("环节明写只读时那一格不再要", formruntime.missing_required([quiet], {"code": "readonly"}, {}), []) plain = {"key": "reason", "label": "申请事由", "type": "textarea", "required": True, "visibleWhen": gated["visibleWhen"]} eq("条件不成立的普通必填格也不卡人", formruntime.missing_required([plain], {}, {"hasContract": "0"}), []) eq("条件成立时普通必填格照旧卡人", formruntime.missing_required([plain], {}, {"hasContract": "1"}), ["申请事由"]) # --------------------------------------------------------------------------- # 9. 外部取数那一头:条目上的触发条件 # --------------------------------------------------------------------------- def check_fetch_entries() -> None: """「报销类型 = 差旅才问差标接口」:清单全量给设计期看,成立的那几条给运行时跑。""" cfg = {"sources": [{"source": "travel_api", "when": TRAVEL}, {"source": "meet_api", "when": MEET}, {"source": "common_api"}]} eq("清单是全量", [item["source"] for item in binding.entries(cfg)], ["travel_api", "meet_api", "common_api"]) eq("运行时只跑成立的那几条", [item["source"] for item in fetch.active_field_sources(cfg, {"expenseType": "travel"})], ["travel_api", "common_api"]) eq("一条都不成立=这回不取数", [item["source"] for item in fetch.active_field_sources( {"sources": [{"source": "a", "when": TRAVEL}]}, {})], []) # 单源老写法也能挂条件;条件写成裸数组按「且」收;配到一半的当没配 eq("单源那份也认这一句", [item["source"] for item in binding.active_entries({"source": "a", "when": MEET}, {"expenseType": "meet"})], ["a"]) eq("裸数组按且收", binding.entry_when({"when": [{"field": "a", "op": "notEmpty"}]}), {"match": "all", "rules": [{"field": "a", "op": "notEmpty"}]}) eq("空条件当没配(恒成立)", binding.entry_when({"when": {"rules": []}}), None) eq("不成形状的条件当没配", binding.entry_when({"when": "nope"}), None) eq("没配条件的老清单一个字不变", binding.active_entries({"source": "erp", "args": {"dept": "{form:dept}"}}, {}), binding.entries({"source": "erp", "args": {"dept": "{form:dept}"}})) # 设计期检查看的是全量:源在不在、条件引用掉没掉在地上,跟此刻的取值无关 reasons = binding.entry_problems(None, {"source": "travel_api", "when": {"match": "all", "rules": [ {"field": "gone", "op": "eq", "value": "1"}]}}, {"dept"}, "第 1 个字段「金额」的外部取数") ok("条件引用了不存在的字段要说", any("gone" in text for text in reasons), reasons) # --------------------------------------------------------------------------- # 10. 翻名字跟着命中的那一条 # --------------------------------------------------------------------------- def check_labels() -> None: """只读、打印、标题念出来的名字,得是**那一单当时命中的那一条**给的名字。""" routed = subject(optionRoutes=routes()) eq("命中差旅时念差旅那本的名字", dicts.option_labels(routed, "T1", FakeCache(), "、", {"expenseType": "travel"}), "火车票") eq("回落到通用那本时念通用", dicts.option_labels(routed, "C1", FakeCache(), "、", {"expenseType": "other"}), "通用科目一") # 认不出的值原样念,别编一个名字出来 eq("认不出就原样念", dicts.option_labels(routed, "ZZ", FakeCache(), "、", {"expenseType": "travel"}), "ZZ") # 不带 data 的老调用方一个字不用改 eq("不带值时按字段自己那一份翻", dicts.option_labels(routed, "C1", FakeCache()), "通用科目一") # 导出与标题那两条路也必须吃这一单的值:界面按 A 家念、导出按 B 家念, # 是这一整套最容易悄悄漂起来的两处(打印出来的单子没人会去对字典)。 eq("导出的那一格跟着命中的那一条", exportfmt.cell_text(routed, "T1", FakeCache(), None, {"expenseType": "travel"}), "火车票") eq("导出没命中就回落通用那本", exportfmt.cell_text(routed, "C1", FakeCache(), None, {"expenseType": "other"}), "通用科目一") eq("标题里那一格也一样", titles._field_text(None, routed, "T1", FakeCache(), data={"expenseType": "travel"}), "火车票") # 源码钉住:这几处调用一旦把 data= 摘掉,上面三条会悄悄退回字段自己那一份而没人报错 root = pathlib.Path(__file__).resolve().parents[2] for rel, phrases in ( ("backend/app/service/exportfmt.py", ["field = dicts_service.option_view(field, data)", "cache, jobs, data=row"]), ("backend/app/service/detail_export.py", ["cache, jobs, data=data"]), ("backend/app/api/export.py", ["cache, jobs, data=data"]), ("backend/app/service/titles.py", ["field = dicts.option_view(field, data)", "cache, data=rows[0])", "cache, data=data)"]), ): source = (root / rel).read_text(encoding="utf-8") for phrase in phrases: ok(f"{rel} 翻名字带上了这一单的值:{phrase}", phrase in source, phrase) # --------------------------------------------------------------------------- # 11. 前后端对齐:常量一份、措辞一句 # --------------------------------------------------------------------------- PARALLEL: list[tuple[str, list[str]]] = [ ("frontend/src/utils/optionSource.ts", [ # 清单本身那几句,两边各写一遍,漂了就会一边放行一边报错 "的候选来源清单要写成一份列表", " 条,多出来的不会被用上", "还没选要用的数据字典", "还没选要用哪一张外部数据源", "一条选项都没填,选到它就是一只空下拉", "的来源这类字段挑不了", "配置格式不对", # 「带出的值也收下」那两句 "这一格没配任何带出(外部取数 / 关联单据带出 / 字典带出),", "或勾上「带出的值不在候选里也收下」", # 字典带出那一条:命中那一条不是字典 / 两处都没字典时的说法,两边一字不差 "配了字典带出,可这一格没挂数据字典(字段上与候选来源那几条里都没有),这一档不起作用", # 「这一格的值是不是系统写进来的」那一份判据:两边都按**落点**判,且都认隔壁那一格 "function fetchWrites(", "function rulesHitSelf(", "export function filledByOther(", "peers?: FormFieldDef[]", ]), ("frontend/src/utils/formLinkage.ts", [ # 路由的上游并进了「清失效值」那一句:漏了它,界面会拿上一家的候选清单继续判越界 "optionFieldView(", ]), ] def check_parity() -> None: """两份算法必须算出同一个结果:常量、每种来源自己那几格、以及那几句措辞。""" root = pathlib.Path(__file__).resolve().parents[2] option_source = root / "frontend/src/utils/optionSource.ts" if not option_source.exists(): print(f"[跳过] 找不到前端那份 {option_source}(只部署后端时正常)") return text = option_source.read_text(encoding="utf-8") eq("上限两边同一个数", f"export const MAX_OPTION_ROUTES = {dicts.MAX_OPTION_ROUTES}" in text, True) eq("清单键名两边同一个", f"export const OPTION_ROUTES_KEY = '{dicts.OPTION_ROUTES_KEY}'" in text, True) # 每种来源自己带的那几格对不上,就会出现「一边把这格当残骸清掉、一边还留着读它」 block = text.split("export const ROUTE_OWNED_KEYS", 1)[-1].split("\n}", 1)[0] for kind, keys in dicts.ROUTE_OWNED_KEYS.items(): hit = re.search(rf"{kind}: \[([^\]]*)\]", block) ok(f"前端 {kind} 那一行在", hit is not None, block) if not hit: continue quoted = set(re.findall(r"'([^']+)'", hit.group(1))) # 前端把 dataSourceArgs 写成常量 OPTION_ARGS_KEY(值就是那一个字面量),认回来再比 if "OPTION_ARGS_KEY" in hit.group(1): quoted.add("dataSourceArgs") eq(f"{kind} 那几格两边同一份", quoted, set(keys)) for path, phrases in PARALLEL: target = root / path if not target.exists(): FAILS.append(f"找不到前端那份 {path}") continue frontend = target.read_text(encoding="utf-8") for phrase in phrases: ok(f"「{phrase}」前后端都在", phrase in frontend, f"前端缺:{path}") # 字典带出读的是**此刻命中那一条**的字典:两边都得先摊视图再读 dictCode, # 漏一处就是「界面带 A 本的附加值、提交带 B 本的」 linkage_source = (root / "frontend/src/utils/formLinkage.ts").read_text(encoding="utf-8") body = linkage_source.split("export function applyAutoFill", 1)[-1] ok("前端带出按命中那一条取字典", "optionFieldView(" in body.split("\nexport ", 1)[0], body[:200]) be_body = inspect.getsource(dicts.apply_auto_fill) ok("后端带出按命中那一条取字典", "option_view(field, data)" in be_body, be_body[:200]) eq("清单键名两边同一个", f"export const AUTO_FILL_KEY = '{dicts.AUTO_FILL_KEY}'", True) if False else None ok("前端那份 AUTO_FILL_KEY 与后端同一个", f"export const AUTO_FILL_KEY = '{dicts.AUTO_FILL_KEY}'" in text, text[:200]) ok("前端也有「路由里那几本字典」那一句", "export function dictRouteCodesOf" in text, text[:200]) # 「落点在这一格上」那份判据两边同形:后端少了 _fetch_writes / _rule_hits_self 就会退回 # 「这一格配过带出=这一格被写」,于是人挑的那一格被说成系统写的,或者反过来 for symbol in ("def _fetch_writes(", "def _rule_hits_self(", "def filled_by_other("): ok(f"后端那份判据在:{symbol}", symbol in inspect.getsource(formruntime), symbol) # 外部取数那一条的触发条件:两边都只认这一个键名 fetch_source = (root / "frontend/src/utils/binding.ts").read_text(encoding="utf-8") eq("条目条件的键名两边同一个", binding.ENTRY_WHEN_KEY, "when") ok("前端那条也走 entryWhen 那一份", "export function entryWhen" in fetch_source, fetch_source[:200]) def main(argv: list[str]) -> int: stages = [ ("命中哪一条与回落", check_matching), ("视图只动来源那一维", check_view), ("脏条目当没配", check_dirty), ("保存那一刻的清洗", check_cleaning), ("把关与「带出的值也收下」", check_guard), ("设计期逐条体检", check_design_time), ("上游与预取清单", check_dependencies), ("隔壁的带出也算带出", check_filled_by_peers), ("显示条件不成立不再卡必填", check_required_when_hidden), ("外部取数的条目条件", check_fetch_entries), ("翻名字跟着命中的那一条", check_labels), ("前后端措辞与常量对齐", check_parity), ] for title, stage in stages: before = len(FAILS) stage() marks = "通过" if len(FAILS) == before else f"{len(FAILS) - before} 条不对" print(f"[{marks}] {title}") for line in FAILS: print(f"[FAIL] {line}") if FAILS: print(f"共 {len(FAILS)} 条不对") return 1 print("通过:候选来源的条件路由与「带出的值也收下」口径一致") return 0 if __name__ == "__main__": raise SystemExit(main(sys.argv[1:]))