unis-oa/backend/scripts/check_link_fill.py

424 lines
22 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

"""关联单据带出的验收脚本(不连库,跑在 backend 目录下)::
python3 scripts/check_link_fill.py
「关联审批流程之后,把那边单据里的值写进这一张单的明细表 / 主表字段,关联多张也要能带」
这件事(方案见 ``docs/relation-link-fill-design.md``)在下面几条上必须一直成立:
1. **配置的形状只有一份**:写歪的规则、认不出的合并档在保存那一刻就被 ``clean`` 收干净,
一条有效规则都不剩时整格抹掉;换了候选来源,那几格跟着上一家一起清;
2. **指向掉了当场说**:要写进的格子不在表单上了、合并档与那一格的形状对不上、
两条带出抢同一格,都是「存得下来、那一格永远是空的」,保存这一刻挡;
3. **主表那一路是「几个数变成一个」**:按配的那一档合(first / join / sum / min / max),
口径是 ``binding.merge`` 那一句,与外部取数同一把尺;
4. **明细那一路是「一单一行」**:新关联的补行、取消关联的删行、留下的行按来源刷新
配到的那几列,而人手工改过的其它列一个字都不动;**关联没变时一行都不重排**,
否则下一环提交会把人删掉的行复活;
5. **行整型不吃 ``_link``**:页面回传时那一格要留得住,否则下一次带出认不出旧行;
6. **两个关联字段带同一张明细表**:各带各的行,谁都不许把对方带来的那一行删掉或盖掉
(那一格存的可能是单号而不是 job,认行要绕一层)。
最后把前后端共用的那几句措辞对一遍。
"""
from __future__ import annotations
import pathlib
import sys
from datetime import datetime
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent))
from app.api import design as design_api # noqa: E402
from app.service import formruntime, linkfill # noqa: E402
FRONTEND = pathlib.Path(__file__).resolve().parent.parent.parent / "frontend" / "src"
FAILS: list[str] = []
class Work:
"""顶替 ``Work`` / ``WorkCompleted`` 那一行:带出只读 job / 单号 / 标题 / 表单数据。"""
def __init__(self, job: str, serial: str = "", title: str = "", data: dict | None = None,
status: str = "completed", creator: str = "张三", unit: str = "财务部",
start: datetime | None = None) -> None:
self.id = job
self.job = job
self.serial = serial or job
self.title = title or f"单据 {job}"
self.status = status
self.process_name = "费用报销"
self.creator_person = creator
self.creator_identity_name = creator
self.creator_unit_name = unit
self.start_time = start
self.finish_time = None
self.data = dict(data or {})
def loader_of(*works: Work):
index = {}
for row in works:
index[row.job] = row
index[row.serial] = row
return lambda values: {item: index[item] for item in values if item in index}
def fields() -> list[dict]:
return [
{"key": "orders", "type": "relation", "label": "关联报销单", "optionSource": "process",
"linkFill": {"rules": RULES}},
{"key": "src_serial", "type": "text", "label": "来源单号"},
{"key": "total", "type": "money", "label": "合计"},
{"key": "when", "type": "date", "label": "发起日期"},
{"key": "items", "type": "table", "label": "明细", "columns": [
{"key": "amount", "type": "money", "label": "金额"},
{"key": "note", "type": "text", "label": "备注"},
]},
]
RULES: list[dict] = []
def configured(rules: list[dict]) -> list[dict]:
rows = fields()
rows[0]["linkFill"] = {"rules": rules}
return rows
def eq(name: str, got, want) -> None:
if got != want:
FAILS.append(f"{name}:得到 {got!r},应为 {want!r}")
def has(name: str, text: str, needle: str) -> None:
if needle not in str(text):
FAILS.append(f"{name}:{text!r} 里没找到 {needle!r}")
# ---------------------------------------------------------------------------
# 1 配置形状与保存期清洗
# ---------------------------------------------------------------------------
def check_clean() -> None:
eq("整格没配", linkfill.clean(None), {})
eq("空规则等于没配", linkfill.clean({"rules": []}), {})
eq("没写取哪一列的规则丢掉", linkfill.clean({"rules": [{"to": "total"}]}), {})
eq("没写去向的规则丢掉", linkfill.clean({"rules": [{"pick": "work.serial"}]}), {})
eq("认不出的合并档退回默认", linkfill.clean({"rules": [{"pick": "a", "to": "b", "agg": "avg"}]}),
{"rules": [{"pick": "a", "to": "b"}]})
eq("跟默认一样的不留", linkfill.clean({"rules": [{"pick": "a", "to": "b", "agg": "first"}]}),
{"rules": [{"pick": "a", "to": "b"}]})
eq("分隔符照留", linkfill.clean({"rules": [{"pick": "a", "to": "b", "agg": "join", "separator": " / "}]}),
{"rules": [{"pick": "a", "to": "b", "agg": "join", "separator": " / "}]})
eq("默认分隔符不留", linkfill.clean({"rules": [{"pick": "a", "to": "b", "agg": "join", "separator": "、"}]}),
{"rules": [{"pick": "a", "to": "b", "agg": "join"}]})
eq("规则条数封顶", len(linkfill.clean({"rules": [{"pick": "a", "to": f"b{i}"} for i in range(99)]})["rules"]),
linkfill.MAX_RULES)
eq("设计器那份流程名留着", linkfill.clean({"process": "p1", "rules": []}), {})
def check_split_target() -> None:
rows = fields()
eq("整串认主表字段", linkfill.split_target("total", rows), ("total", ""))
eq("点分认明细列", linkfill.split_target("items.amount", rows), ("items", "amount"))
eq("列不在表上", linkfill.split_target("items.nope", rows), ("", ""))
eq("表不是明细表", linkfill.split_target("total.amount", rows), ("", ""))
eq("空写法", linkfill.split_target("", rows), ("", ""))
def check_problems() -> None:
rows = configured([{"pick": "work.serial", "to": "src_serial"}])
keys = {str(item["key"]) for item in rows}
eq("配得对的不说", linkfill.problems(rows[0], keys, rows), [])
# 来源不是流程单据:字典那一格挂着 linkFill 永远不带
dict_field = {"key": "x", "type": "select", "optionSource": "dict", "dictCode": "d",
"linkFill": {"rules": [{"pick": "work.serial", "to": "x"}]}}
has("来源不对", ";".join(linkfill.problems(dict_field, {"x"}, [dict_field])), "流程单据")
dangling = configured([{"pick": "work.serial", "to": "gone"}])
has("指向掉在地上", ";".join(linkfill.problems(dangling[0], {"orders"}, dangling)), "不存在的字段「gone」")
numeric = configured([{"pick": "data.amount", "to": "src_serial", "agg": "sum"}])
has("装不下数", ";".join(linkfill.problems(numeric[0], {"orders", "src_serial"}, numeric)), "装不下数")
both = configured([{"pick": "work.serial", "to": "src_serial"},
{"pick": "work.title", "to": "src_serial"}])
has("两条抢一格", ";".join(linkfill.problems(both[0], {"orders", "src_serial"}, both)), "都写进「src_serial」")
weird = configured([{"pick": "serial", "to": "src_serial"}])
has("写法看不出读哪儿", ";".join(linkfill.problems(weird[0], {"orders", "src_serial"}, weird)), "work.")
half = {"key": "orders", "type": "relation", "optionSource": "process",
"linkFill": {"rules": [{"to": "total"}]}}
has("半截配置", ";".join(linkfill.problems(half, {"orders", "total"}, [half])), "没写清")
# 明细列那一头:合并档也得认那一格的形状
column_agg = configured([{"pick": "data.amount", "to": "items.note", "agg": "sum"}])
has("明细列装不下数",
";".join(linkfill.problems(column_agg[0], {"orders"}, column_agg)), "明细表「明细」的列「备注」")
# 整张表单的校验把它带进保存那条路
reasons = formruntime.validate_schema(configured([{"pick": "work.serial", "to": "gone"}]))
has("validate_schema 认这一层", ";".join(reasons), "不存在的字段「gone」")
def check_design_clean() -> None:
content = {"fields": [
{"key": "a", "type": "relation", "label": "关联", "optionSource": "process",
"linkFill": {"rules": [{"pick": "work.serial", "to": "b"}, {"pick": "", "to": "b"}]}},
{"key": "b", "type": "text", "label": "B"},
]}
out = design_api.clean_option_source(content)
eq("换来源之前先收干净", out["fields"][0]["linkFill"], {"rules": [{"pick": "work.serial", "to": "b"}]})
swapped = design_api.clean_option_source({"fields": [
{"key": "a", "type": "select", "label": "A", "optionSource": "dict", "dictCode": "d",
"linkFill": {"rules": [{"pick": "work.serial", "to": "b"}]}},
{"key": "b", "type": "text", "label": "B"},
]})
eq("换走来源时一起清", "linkFill" in swapped["fields"][0], False)
nested = design_api.clean_option_source({"fields": [
{"key": "t", "type": "table", "label": "T", "columns": [
{"key": "c", "type": "relation", "label": "关联列", "optionSource": "process",
"linkFill": {"rules": [{"pick": "work.serial", "to": "x"}]}},
]},
]})
eq("明细列上的关联带出收掉", "linkFill" in nested["fields"][0]["columns"][0], False)
# ---------------------------------------------------------------------------
# 2 主表那一路:几个数变成一个
# ---------------------------------------------------------------------------
def check_main_targets() -> None:
one = Work("J1", "BX-001", data={"amount": 100, "day": "2026-03-01"})
two = Work("J2", "BX-002", data={"amount": "2,300.50", "day": "2026-03-05"})
rows = configured([{"pick": "work.serial", "to": "src_serial"}])
data = {"orders": ["J1"]}
touched = linkfill.apply(None, rows, data, loader=loader_of(one, two))
eq("关联一张时取它自己", data["src_serial"], "BX-001")
eq("报出改动的格子", touched, ["src_serial"])
rows = configured([{"pick": "work.serial", "to": "src_serial", "agg": "join", "separator": " / "}])
data = {"orders": ["J1", "J2"]}
linkfill.apply(None, rows, data, loader=loader_of(one, two))
eq("关联两张时按分隔符拼", data["src_serial"], "BX-001 / BX-002")
rows = configured([{"pick": "data.amount", "to": "total", "agg": "sum"}])
data = {"orders": ["J1", "J2"]}
linkfill.apply(None, rows, data, loader=loader_of(one, two))
eq("金额按分相加,带分隔符的文本也认", data["total"], 2400.5)
rows = configured([{"pick": "data.amount", "to": "total", "agg": "max"}])
data = {"orders": ["J1", "J2"]}
linkfill.apply(None, rows, data, loader=loader_of(one, two))
eq("取最大", data["total"], 2300.5)
rows = configured([{"pick": "work.serial", "to": "src_serial"}])
data = {"orders": ["J2", "J1"]}
linkfill.apply(None, rows, data, loader=loader_of(one, two))
eq("取第一个按关联顺序", data["src_serial"], "BX-002")
rows = configured([{"pick": "data.day", "to": "when"}])
data = {"orders": ["J1"]}
linkfill.apply(None, rows, data, loader=loader_of(one, two))
eq("日期格保持日期写法", data["when"], "2026-03-01")
stamp = Work("J3", "BX-003", start=datetime(2026, 3, 1, 9, 30, 0))
rows = configured([{"pick": "work.startTime", "to": "when"}])
data = {"orders": ["J3"]}
linkfill.apply(None, rows, data, loader=loader_of(stamp))
eq("单据本体的时间收成日期那一格认的写法", data["when"], "2026-03-01")
rows = configured([{"pick": "data.amount", "to": "total", "agg": "sum"}])
data = {"orders": []}
linkfill.apply(None, rows, data, loader=loader_of(one, two))
eq("取消全部关联时那一格清空", data["total"], "")
rows = configured([{"pick": "data.amount", "to": "total", "agg": "sum"}])
data = {"orders": ["J9"]}
linkfill.apply(None, rows, data, loader=loader_of(one, two))
eq("那张单被删了也一视同仁", data["total"], "")
rows = configured([{"pick": "work.serial", "to": "src_serial"}])
data = {"orders": "J1"}
linkfill.apply(None, rows, data, loader=loader_of(one))
eq("单选那一格(存的是单个值)照样带", data["src_serial"], "BX-001")
rows = configured([{"pick": "work.serial", "to": "src_serial"}])
data = {"orders": ["BX-001"]}
linkfill.apply(None, rows, data, loader=loader_of(one))
eq("配成存单号那一列也认得回单据", data["src_serial"], "BX-001")
# ---------------------------------------------------------------------------
# 3 明细那一路:一单一行
# ---------------------------------------------------------------------------
def check_detail_rows() -> None:
one = Work("J1", "BX-001", data={"amount": 100})
two = Work("J2", "BX-002", data={"amount": 200})
rules = [{"pick": "data.amount", "to": "items.amount"}]
data = {"orders": ["J1", "J2"]}
linkfill.apply(None, configured(rules), data, loader=loader_of(one, two))
eq("两张单补两行", [row.get("items") or row for row in data["items"]][0].get("_link"), "J1")
eq("按关联顺序排", [row["_link"] for row in data["items"]], ["J1", "J2"])
eq("带出来的值落进配的那一列", [row["amount"] for row in data["items"]], [100, 200])
# 人在下一行手工补了备注,又删掉了 J2 那一行
data["items"] = [{"_link": "J1", "amount": 100, "note": "自己写的"},
{"amount": 999, "note": "手工加的行"}]
trace_before = dict(data[linkfill.TRACE_KEY])
linkfill.apply(None, configured(rules), data, loader=loader_of(one, two))
eq("关联没变时不重排、不复活被删的行", [row.get("_link") for row in data["items"]], ["J1", None])
eq("手工加的行一个字不动", data["items"][1]["amount"], 999)
eq("留痕照原样", data[linkfill.TRACE_KEY], trace_before)
# 现在先把 J2 取消关联(这一轮关联变了,会重排一次),再把它挂回来
data["orders"] = ["J1"]
linkfill.apply(None, configured(rules), data, loader=loader_of(one, two))
data["orders"] = ["J1", "J2"]
linkfill.apply(None, configured(rules), data, loader=loader_of(one, two))
eq("重新关联才补回来,且加在末尾不打乱人排的序",
[row.get("_link") for row in data["items"]], ["J1", None, "J2"])
eq("人写的备注没被动", data["items"][0]["note"], "自己写的")
# 来源那侧金额改了(对方改单之后):关联没变这一轮不动,动一下关联才按来源刷新
linkfill.apply(None, configured(rules), data, loader=loader_of(Work("J1", "BX-001", data={"amount": 111}), two))
eq("关联没变时不刷来源", data["items"][0]["amount"], 100)
data["orders"] = ["J1", "J2", "JX"]
linkfill.apply(None, configured(rules), data, loader=loader_of(Work("J1", "BX-001", data={"amount": 111}), two))
eq("关联变化时按来源刷新配到的那一列", [row.get("amount") for row in data["items"]][0], 111)
eq("新关联的排在末尾,取消关联的那一行跟着删",
[row.get("_link") for row in data["items"]], ["J1", None, "J2"])
# 最多几行那一档
data = {"orders": ["J1", "J2"]}
rows = configured(rules)
rows[4]["maxRows"] = 1
linkfill.apply(None, rows, data, loader=loader_of(one, two))
eq("补行也认最多行数", len(data["items"]), 1)
# 两张明细表 / 两个关联字段各管自己那几行
data = {"orders": ["J1"]}
linkfill.apply(None, configured(rules), data, loader=loader_of(one))
eq("没配列去向时不凭空造行", len(data["items"]), 1)
data = {"orders": ["J1"]}
linkfill.apply(None, configured([{"pick": "work.title", "to": "items.note"}]), data, loader=loader_of(one))
eq("文本带进明细列", data["items"][0]["note"], "单据 J1")
eq("没配的列留空", data["items"][0]["amount"], "")
# 空来源也要留得下那一行:对方那一列没填,行还是那张单的
data = {"orders": ["J1"]}
linkfill.apply(None, configured([{"pick": "data.nope", "to": "items.amount"}]), data, loader=loader_of(one))
eq("取不到值落一个形状正确的空", data["items"][0]["amount"], "")
kept = formruntime.normalise_rows(data["items"], fields()[4])
eq("带出那行即使全空也不会被当成空行删掉", [row.get("_link") for row in kept], ["J1"])
eq("整型之后 _link 还在", linkfill.ROW_LINK_KEY in kept[0], True)
def check_two_relation_fields() -> None:
"""两个关联字段带进同一张明细表:各带各的行,谁也不许删对方带来的那一行。
「挂两类单子」在真实表单上就是两格(报销单一格、采购单一格,两格的字段名根本不
是一套),而明细表只有一张。不带这一道兜底,后处理的那一格会把前一格刚补的那几行
当成「自己这边取消关联了」删干净。
"""
order = Work("J1", "BX-001", data={"amount": 100})
buy = Work("J9", "CG-009", data={"cost": 500})
def pair() -> list[dict]:
return [
{"key": "orders", "type": "relation", "label": "关联报销单", "optionSource": "process",
"linkFill": {"rules": [{"pick": "data.amount", "to": "items.amount"}]}},
{"key": "buys", "type": "picker", "label": "关联采购单", "optionSource": "process",
"linkFill": {"rules": [{"pick": "data.cost", "to": "items.amount"}]}},
{"key": "items", "type": "table", "label": "明细", "columns": [
{"key": "amount", "type": "money", "label": "金额"},
{"key": "note", "type": "text", "label": "备注"},
]},
]
data = {"orders": ["J1"], "buys": ["J9"]}
linkfill.apply(None, pair(), data, loader=loader_of(order, buy))
eq("两个关联字段各带一行", [row["_link"] for row in data["items"]], ["J1", "J9"])
eq("各取各的列", [row["amount"] for row in data["items"]], [100, 500])
# 只动其中一格:另一格带来的那一行原样留着,值也不被对方盖掉
data["orders"] = []
linkfill.apply(None, pair(), data, loader=loader_of(order, buy))
eq("取消一格的关联只撤它自己那一行", [row["_link"] for row in data["items"]], ["J9"])
data["orders"] = ["J1"]
linkfill.apply(None, pair(), data, loader=loader_of(order, Work("J9", "CG-009", data={"cost": 999})))
eq("重排之后对方那两行都还在", [row["_link"] for row in data["items"]], ["J9", "J1"])
eq("别人带来的那一行不被这一格的列映射盖掉",
[row["amount"] for row in data["items"] if row["_link"] == "J9"], [500])
# 别的格子那一串值存的是单号而不是 job:认行要绕一层,绕不过去就会错删
data = {"orders": ["BX-001"], "buys": ["J9"]}
linkfill.apply(None, pair(), data, loader=loader_of(order, buy))
eq("对方存的是单号,也认得出那一行是谁带来的",
sorted(row["_link"] for row in data["items"]), ["J1", "J9"])
data["buys"] = []
linkfill.apply(None, pair(), data, loader=loader_of(order, buy))
eq("存单号那一格撤干净,另一格那几行照旧不动",
[row["_link"] for row in data["items"]], ["J1"])
# ---------------------------------------------------------------------------
# 4 预览接口那一份取值
# ---------------------------------------------------------------------------
def check_values_of() -> None:
one = Work("J1", "BX-001", data={"amount": 100})
items = linkfill.values_of(None, ["J1", "J2"], ["work.serial", "data.amount"], loader=loader_of(one))
eq("认不出的那张不在里面", len(items), 1)
eq("按 pick 原文回键", items[0]["values"], {"work.serial": "BX-001", "data.amount": 100})
eq("没写 pick 时什么都不取", linkfill.values_of(None, ["J1"], [], loader=loader_of(one)), [])
# 那一格可以配成存单号(optionMap.valueKey):问出去的是单号,回来的 value 必须是
# **问的那一句**,只回 job 会让预览那头一张都认领不到,明细表整个空着
asked = linkfill.values_of(None, ["BX-001", "不存在的单号"], ["data.amount"], loader=loader_of(one))
eq("按单号问也要认领得回来", [(item["job"], item["value"]) for item in asked], [("J1", "BX-001")])
def check_wording_parity() -> None:
"""前后端共用的那几句说法必须一字不差(漂了这里就红)。"""
right = FRONTEND / "utils" / "linkFill.ts"
if not right.exists():
print(f"[跳过] 找不到前端那份 {right}")
return
text = right.read_text(encoding="utf-8")
for needle in ("只有候选来源是「流程单据」的字段能配关联带出", "装不下数", "都写进"):
if needle not in text:
FAILS.append(f"前端那份缺了同款措辞:{needle}")
if f"'{formruntime.ROW_LINK_KEY}'" not in text:
FAILS.append("前端那份认的行标记与后端不是同一个")
STAGES = [
("配置形状", check_clean),
("指向怎么认", check_split_target),
("保存期校验", check_problems),
("候选来源清洗", check_design_clean),
("主表:几个数变成一个", check_main_targets),
("明细:一单一行", check_detail_rows),
("两个关联字段带同一张明细表", check_two_relation_fields),
("预览取值", check_values_of),
("前后端措辞对齐", check_wording_parity),
]
def main(argv: list[str]) -> int:
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:]))