unis-oa/backend/scripts/check_relation_scope.py

434 lines
24 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.

#!/usr/bin/env python3
"""守「关联流程」这两件事:候选只列**我发起的**,那一行能写**对方表单里的哪几格**。
用户提的原话是:**「关联流程的时候,展示字段我希望是可以选择到表单中的字段进行展示」**、
**「选择流程范围不应该是已办,而是只有我发起的流程,不应该把我所有已办的流程展示出来」**。
界面那一半在 ``frontend/src/components/oa/design/OptionSourcePanel.vue``(那一档下拉 +
「显示与存值 / 那一行小字」里多出来的一截清单),这一篇钉口径与数据那一半::
PYTHONPATH=. python3 scripts/check_relation_scope.py
**范围那一档(``relationScope``)**
1. **默认是「只给我发起的」**:``created`` 这一档落成 ``work.creator_identity == 我``;
以前只有「我发起 / 我办过 / 我被抄送」那一片并集(``related``),于是挑历史单时
一大半是别人发起、我只是顺手批过的单子。
2. **管理员也照收**:``_visible_work_filter`` 放过管理员说的是他**看得见**别人的单,
这一档问的是「这张单算不算你发起的」——一条事实,跟谁在查没关系。放过管理员会让
同一只挑选器在两人口中列出两批单子,配的人在自己账号下试出来的手感就骗人。
3. **只收候选,不收已存的值**:回显走 ``/work/summaries``,不跟着这一档收窄。改版前
挑上的、或别人代挑的那几张单,回显还得念得出名字,不能因为挑不进来了就念成一串 job。
4. **脏值退回默认那一档**,界面上另说一句;这一格跟着候选来源一起清(换成字典就没有
「谁的单」可问了)。
**显示那一档(``data.字段名``)**
5. **列名按前缀认,不写死清单**:单据本体只有标题 / 单号 / 流程名 / 发起人那几列,
对方表单里有哪些格要问那条流程的表单,所以 ``data.`` 那一头按前缀认。
6. **点了哪几列才读表单正文**:``/work/related`` 原本 ``with_data=False``,正文那一列
从头到尾没人读;点名了才把正文带回来,且**只回点名的那几列**(翻成人话之后)。
7. **翻成人话与导出同一把尺**:走 ``exportfmt.cell_text``——字典编码落「差旅费」而不是
「CL01」,附件落文件名,签名落「已签名」,不是 ``str(value)`` 糊上去的一坨。
8. **回的形状就是点路径**:后端嵌着放(``{"data": {"明细": {"金额": …}}}``),前端
``pickKeyOf`` 一段一段点下去就取得到,两边不另造一套写法。
9. **上限一处收**:一行候选最多读 8 列(``MAX_RELATION_DISPLAY_FIELDS``),接口上那句
``fields`` 与字段上配到的列都过同一份清洗。
**回显那一头认几个名字(``GET /work/summaries`` 的 ``by`` / ``process``)**
10. **「名字点得开那张单」与「存为」选哪一列无关**(原话:**「下拉选择组件我也希望可以实现选择
流程可以跳转,并且不需要考虑选择存的字段才对。关联审批流程组件也是一样」**):这一格的存值列
由 ``optionMap.valueKey`` 说了算——``job``(默认)/ ``serial``(单据编号)/ 限定流程之后的
``data.某列``(对方表单里那一格)。回显拿存着的值问摘要,接口就按**同一列**把它认回单据:
job 与单号走索引等值,``data.某列`` 只在**限定了流程**时认(范围收到 ``process`` 那一条索引上,
不在两张表上现扫 JSON 正文),且比的是那一格的**原文**——字典、附件那类「库里存码、界面念名」
的列认不到,就照旧少回一条:念得出存着的值、点不开,也比点进一张不相干的单强。
11. **归档表的 ``serial`` 上有索引**:已经挂上的关联单据九成套在归档表里,按单号认的那一句
没索引就是每次开单倒扫整张只长不删的表。
12. **认领的顺序 job 在前**(``{**by_form, **by_serial, **by_job}``):万一有人把单号起成了别张单的
job,认 job 的那一格不该翻到错的那张单上。
最后把前后端那几句共用的常量与措辞对一遍:两边各写一遍迟早会漂,漂了这里就红。
"""
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
from app.api import design as design_api, runtime as runtime_api # noqa: E402
from app.service import dicts, formruntime, processdata # noqa: E402
FAILS: list[str] = []
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 '条件不成立'}")
def sql(clause) -> str:
"""把一条 SQLAlchemy 条件摊成文本好比对;``None`` 当成空串(不能用 ``or``,条件本身不能判真假)。"""
return "" if clause is None else str(clause)
class Person:
"""顶替 ``models.User`` 那一行:``CurrentUser.person_id`` 只读 ``.id``。"""
def __init__(self, user_id: int = 1) -> None:
self.id = user_id
def user(ref: str = "zhangsan", is_admin: bool = False) -> runtime_api.CurrentUser:
return runtime_api.CurrentUser(person=Person(), ref=ref, is_admin=is_admin)
# ---------------------------------------------------------------------------
# 1. 范围那一档
# ---------------------------------------------------------------------------
def check_scope_reading() -> None:
relation = {"key": "rel", "type": "relation"}
eq("没配过就是只给自已发起的", dicts.relation_scope(relation), "created")
eq("默认值与档位清单同一条", dicts.RELATION_SCOPE_DEFAULT, dicts.RELATION_SCOPE_CREATED)
eq("明写与我相关才放开", dicts.relation_scope({**relation, "relationScope": "related"}), "related")
eq("认不出的值退回默认,不报错也不留", dicts.relation_scope({**relation, "relationScope": "handled"}), "created")
eq("写成非字符串也一样", dicts.relation_scope({**relation, "relationScope": 7}), "created")
# 设计期那一句:界面上挑不出歪值,歪值只从接口直传与 AI 起草进来
eq("没写这一格一个字都不说", formruntime.option_source_problems(relation, db=None), [])
eq("档位认不出要说", formruntime.option_source_problems(
{**relation, "relationScope": "handled"}, db=None), ["候选范围里有认不出的档位:handled"])
eq("空串是要人挑,不是不限", formruntime.option_source_problems(
{**relation, "relationScope": ""}, db=None), ["候选范围还没挑:只给自已发起的,还是与我相关的都算"])
# 候选来源的条件路由:那几条各带一份范围,措辞跟着这一条走
routed = {"key": "rel", "type": "relation", "optionSource": "process",
"optionRoutes": [{"source": "process", "relationScope": "handled"}]}
eq("路由里那一条也认这一档", dicts.route_problems(routed),
["「rel」的第 1 条候选来源:候选范围里有认不出的档位:handled"])
# 挂在某一条路由上的那一档要留得下来:漏在 ROUTE_OWNED_KEYS 里就是存进去即失效
per_route = {"key": "rel", "type": "relation", "optionSource": "process", "optionRoutes": [
{"source": "process", "relationProcess": "p1", "relationScope": "related"}]}
eq("路由自己那一档不被当残骸清掉",
[r.get("relationScope") for r in dicts.routes_of(per_route)], ["related"])
eq("按命中那条路由算范围", dicts.relation_scope(dicts.option_view(per_route, {})), "related")
# 换来源时这一档跟着清:留着下一任看不出它已经不起作用
saved = design_api.clean_option_source(design_api.clean_formats({"fields": [
{"key": "rel", "type": "relation", "optionSource": "process", "relationScope": "related"},
{"key": "rel2", "type": "relation", "optionSource": "dict", "dictCode": "x", "relationScope": "related"},
]}))["fields"]
eq("还在用流程单据时那一档留着", saved[0].get("relationScope"), "related")
eq("换成字典就抹掉,不留一份不起作用的配置", "relationScope" in saved[1], False)
def check_scope_sql() -> None:
"""两张表上那一条条件:默认只认发起人,放开才认「与我相关」那一片。"""
for model in (models.Work, models.WorkCompleted):
created = sql(runtime_api._related_clause(model, user(), "", "", None, "created"))
ok(f"{model.__tablename__}:默认那一条比的是发起人", "creator_identity" in created, created)
ok(f"{model.__tablename__}:默认那一条不查已办表", "oa_task_completed" not in created, created)
ok(f"{model.__tablename__}:默认那一条不查待阅表", "oa_read" not in created, created)
related = sql(runtime_api._related_clause(model, user(), "", "", None, "related"))
ok(f"{model.__tablename__}:放开之后查办过的", "oa_task_completed" in related, related)
ok(f"{model.__tablename__}:放开之后查抄送过的", "oa_read_completed" in related, related)
admin_created = sql(runtime_api._related_clause(model, user(is_admin=True), "", "", None, "created"))
# 条件就一句「发起人 = 我」:不因为换了管理员就多带一段 EXISTS 去捞别人的单
ok(f"{model.__tablename__}:管理员也只给自已发起的", admin_created.count("creator_identity =") == 1, admin_created)
ok(f"{model.__tablename__}:管理员那一条不放过整库", "EXISTS" not in admin_created.upper(), admin_created)
# 状态与范围各加各的条件,互不顶掉
both = sql(runtime_api._related_clause(models.Work, user(), "出差", "p1", ("completed",), "created"))
for needle in ("creator_identity", "status IN", "title LIKE", "serial LIKE", "process ="):
ok(f"条件里 {needle} 还在", needle in both, both)
# ---------------------------------------------------------------------------
# 2. 那一行读对方表单里的哪几格
# ---------------------------------------------------------------------------
def check_display_paths() -> None:
eq("带前缀的列名原样认", dicts.clean_relation_display_paths("data.金额"), ("金额",))
eq("去重、去空、去脏", dicts.clean_relation_display_paths("data.金额,金额, ,x..y,"), ("金额",))
eq("深层路径收", dicts.clean_relation_display_paths("明细.金额"), ("明细.金额",))
eq("上限一处收", len(dicts.clean_relation_display_paths(",".join(f"f{i}" for i in range(30)))),
dicts.MAX_RELATION_DISPLAY_FIELDS)
eq("超长那一条丢掉而不是截一半", dicts.clean_relation_display_paths("x" * 200), ())
eq("只有流程单据有表单可读", dicts.form_column_path(dicts.SOURCE_PROCESS, "data.金额"), "金额")
eq("字典挂这一列当配错", dicts.form_column_path(dicts.SOURCE_DICT, "data.金额"), "")
eq("没有前缀不算这一类", dicts.form_column_path(dicts.SOURCE_PROCESS, "金额"), "")
# 认不出的列不报错,退回默认列;认得出的表单列要一路认到底
field = {"key": "rel", "type": "relation", "optionMap": {"valueKey": "data.no", "labelKey": "data.金额"}}
eq("显示那一列认下 data.金额", dicts.option_map_of(field)["labelKey"], "data.金额")
eq("存值那一列也认(挂别的流程的单,存它的立项编号)", dicts.option_map_of(field)["valueKey"], "data.no")
eq("设计期不念黄字", dicts.option_map_problems(field), [])
eq("这一格点到的是哪几列", dicts.relation_display_paths({
"type": "relation",
"optionMap": {"labelKey": "data.金额"},
"picker": {"dialog": {"noteKeys": ["serial", "data.日期"], "badgeKey": "data.状态"}},
}), ("金额", "状态", "日期"))
eq("字典那一格读不出表单列", dicts.relation_display_paths({
"optionMap": {"labelKey": "data.金额"}, "type": "select",
}), ())
many = {"type": "relation", "optionMap": {"valueKey": "data.a", "labelKey": "data.b"},
"picker": {"dialog": {"noteKeys": [f"data.c{i}" for i in range(20)]}}}
eq("字段上配到 30 列也只剩 8 列的额度", len(dicts.relation_display_paths(many)),
dicts.MAX_RELATION_DISPLAY_FIELDS)
class Row:
"""顶替一张单据:``FormDisplay`` 只读 ``process`` 与 ``data`` 两个属性。"""
def __init__(self, process: str, data: dict) -> None:
self.process = process
self.data = data
def check_form_display() -> None:
"""取出来的那一份是**给人看的那句话**,不是 ``str(value)`` 糊上去的一坨。"""
defs = {
"amount": {"key": "amount", "type": "money", "label": "报销金额"},
"cate": {"key": "cate", "type": "select", "label": "费用类别",
"options": [{"value": "CL01", "label": "差旅费"}]},
"file": {"key": "file", "type": "attachment", "label": "发票"},
"items": {"key": "items", "type": "table", "label": "明细"},
}
original = processdata.field_defs_of_process
processdata.field_defs_of_process = lambda db, pid: defs if pid == "p1" else {}
try:
view = processdata.FormDisplay(None, ["amount", "cate", "file", "items", "gone"])
row = view.of(Row("p1", {
"amount": 12000,
"cate": "CL01",
"file": [{"name": "发票.pdf", "url": "http://x/1"}],
"items": [{"金额": 300}, {"金额": 400}],
}))
eq("钱按表单那一格的类型落成一句", row["amount"], "12000")
eq("字典编码翻成名称,与导出同一把尺", row["cate"], "差旅费")
eq("附件只留文件名", row["file"], "发票.pdf")
eq("明细表压成一行", row["items"], "金额=300 | 金额=400")
ok("取不到的列不放空串占位", "gone" not in row, str(row))
# 深层列名走 fetch.pick_path 那一套写法:明细表要点就得写下标
deep = processdata.FormDisplay(None, ["items.0.金额"]).of(
Row("p1", {"items": [{"金额": 300}, {"金额": 400}]})
)
eq("深层路径嵌回同一个形状给点路径读", deep, {"items": {"0": {"金额": "300"}}})
eq("不写下标就明说取不到,不悄悄拿头一行糊过去",
processdata.FormDisplay(None, ["items.金额"]).of(Row("p1", {"items": [{"金额": 300}]})), {})
eq("整表那句先到就留整表",
processdata.FormDisplay(None, ["items", "items.0.金额"]).of(Row("p1", {"items": [{"金额": 300}]})),
{"items": "金额=300"})
eq("那一格先到就留那一格",
processdata.FormDisplay(None, ["items.0.金额", "items"]).of(Row("p1", {"items": [{"金额": 300}]})),
{"items": {"0": {"金额": "300"}}})
# 「与导出同一把尺」不是嘴上说说:取文本的那一段确实只调 exportfmt
body = inspect.getsource(processdata.FormDisplay._text)
ok("翻文本走 exportfmt,不自带一套",
"exportfmt.cell_text" in body and "exportfmt.scalar_text" in body, body)
eq("一列都没配就一个字都不取", processdata.FormDisplay(None, []).active, False)
eq("没配列时取出来是空", processdata.FormDisplay(None, []).of(Row("p1", {"amount": 1})), {})
# 认不出字段定义(环节表单之外手敲的列名)也要落一句人话,不能摆一坨 Python 字面量
other = processdata.FormDisplay(None, ["tags"]).of(Row("p_other", {"tags": ["甲", "乙"]}))
eq("认不出的列按通用形状落", other["tags"], "甲、乙")
long_view = processdata.FormDisplay(None, ["remark"])
got = long_view.of(Row("p_other", {"remark": "一" * 400}))["remark"]
ok("长文本收在一行之内", len(got) <= processdata.DISPLAY_TEXT_MAX, f"{len(got)} 字")
finally:
processdata.field_defs_of_process = original
def check_endpoint_conditions() -> None:
"""两条接口各按哪一条条件筛:候选那一头收范围,回显那一头只问「看得见」。"""
for name in ("search_related_works", "work_summaries"):
body = inspect.getsource(getattr(runtime_api, name))
ok(f"{name} 认那句 fields", "clean_relation_display_paths" in body, name)
related = inspect.getsource(runtime_api.search_related_works)
ok("候选那一头按范围收", "_related_clause" in related and "wanted_scope" in related, related[:400])
# 回显那一头不能跟着范围走:改版前挑上的单还得念得出名字,不然念成一串 job
summaries = inspect.getsource(runtime_api.work_summaries)
ok("回显只问看不看得见,不问是谁发起的",
"_visible_work_filter" in summaries and "_related_clause" not in summaries, summaries[:600])
def check_summary_lookup() -> None:
"""回显那一头认几个名字:job、单号、以及限定流程之后对方表单里那一格。"""
# 「那一格的原文」这一句是真算的:筛行 / 聚合那种写法存不出值,MySQL 的 JSON 路径也点不动
eq("点路径拼成 JSON 路径", runtime_api._form_json_path("projectNo"), '$."projectNo"')
eq("明细里那一格也点得下去", runtime_api._form_json_path("明细.0.金额"), '$."明细"."0"."金额"')
for unreadable in ("明细[名称=甲].金额", "明细.sum(金额)", "", "a..b"):
eq(f"这种写法不认:{unreadable or '(空)'}", runtime_api._form_json_path(unreadable), "")
body = inspect.getsource(runtime_api.work_summaries)
ok("按 job 认", "model.job.in_(wanted)" in body, body[:600])
ok("按单号认", "model.serial.in_(wanted)" in body, body[:600])
ok("按对方表单那一格认", "form_column_path" in body and "json_extract" in body, body[:900])
# 表单那一格没有索引可依,只在限定了流程时认——范围收在 process 那条索引上
ok("按表单那一格认要先限定流程", "form_path and process.strip()" in body, body[:900])
ok("认的顺序 job 在前", "{**by_form, **by_serial, **by_job}" in body, body[:1200])
# 界面上那一头:把「存的是哪一列 + 限的哪条流程」一起报出去,不然接口无从按列去认
picker = _read(PARALLEL_FILES["frontend_picker"]).read_text(encoding="utf-8")
ok("界面把存值列与限定的流程一起报出去",
"by: keys.value.valueKey" in picker and "process: props.process" in picker, "")
api_ts = _read(PARALLEL_FILES["frontend_api"]).read_text(encoding="utf-8")
ok("接口那句带 by 与 process", "query.by" in api_ts and "query.process" in api_ts, "")
# 归档表那个单号索引:模型与建表脚本两份都得在,少一份就是「本地快、线上扫全表」
models_py = _read("backend/app/models.py").read_text(encoding="utf-8")
archived = models_py.split("class WorkCompleted(", 1)
declared = next(
(line.strip() for line in (archived[1].splitlines() if len(archived) == 2 else [])
if line.strip().startswith("serial:")),
"",
)
ok("归档表的 serial 声明了索引", "index=True" in declared, declared)
schema = _read("sql/schema.sql").read_text(encoding="utf-8")
ok("建表脚本里那条单号索引也在", "ix_oa_work_completed_serial" in schema, "")
def check_summary_payload() -> None:
"""没点列时摘要里压根不该出现 ``data``:那一句是「不多读一列正文」的凭据。"""
class Summary:
job = "J1"
serial = "S1"
title = "一张单"
process = "p1"
process_name = "流程"
status = "completed"
creator_person = "张三"
creator_unit_name = "行政部"
start_time = None
finish_time = None
current_activity_names = ""
eq("没点列不多带一个键", "data" in runtime_api._relation_summary(Summary()), False)
eq("点了才带上", runtime_api._relation_summary(Summary(), {"金额": "1"}),
{**runtime_api._relation_summary(Summary()), "data": {"金额": "1"}})
# ---------------------------------------------------------------------------
# 3. 前后端常量与措辞对齐
# ---------------------------------------------------------------------------
#: 两边各写一遍、必须一模一样的东西:一份在后端,一份镜像在前端
PARALLEL_FILES = {
"backend": "backend/app/service/dicts.py",
"frontend_scope": "frontend/src/utils/optionSource.ts",
"frontend_map": "frontend/src/utils/optionMap.ts",
"frontend_picker": "frontend/src/components/oa/OptionPicker.vue",
"frontend_api": "frontend/src/api/work.ts",
}
#: 脚本跑在 backend/ 下,仓库根要往上退一层
ROOT = pathlib.Path(__file__).resolve().parent.parent.parent
def _read(rel: str):
return ROOT / rel
PARALLEL_PHRASES = [
("backend", "frontend_scope", ["候选范围里有认不出的档位"]),
]
# (前端那一份在哪个文件, 后端写法, 前端写法)
PARALLEL_CONSTANTS = [
# 默认那一档两边必须同一句,否则界面按 A 档渲染、后端按 B 档查库
("frontend_scope", "RELATION_SCOPE_CREATED = \"created\"", "RELATION_SCOPE_CREATED: RelationScope = 'created'"),
("frontend_scope", "RELATION_SCOPE_RELATED = \"related\"", "RELATION_SCOPE_RELATED: RelationScope = 'related'"),
("frontend_scope", "RELATION_SCOPE_DEFAULT = RELATION_SCOPE_CREATED", "RELATION_SCOPE_DEFAULT: RelationScope = RELATION_SCOPE_CREATED"),
# 「读对方表单」的写法前缀与上限:一个决定怎么认列,一个决定最多问几列
("frontend_map", 'PROCESS_FORM_PREFIX = "data."', "export const PROCESS_FORM_PREFIX = 'data.'"),
("frontend_map", "MAX_RELATION_DISPLAY_FIELDS = 8", "export const MAX_RELATION_DISPLAY_FIELDS = 8"),
]
def check_wording_parity() -> None:
root = pathlib.Path(__file__).resolve().parents[2]
texts: dict[str, str] = {}
for key, rel in PARALLEL_FILES.items():
path = root / rel
if not path.exists():
print(f"[跳过] 找不到 {rel}(只部署后端时正常)")
continue
texts[key] = path.read_text(encoding="utf-8")
for side_a, side_b, phrases in PARALLEL_PHRASES:
if side_a not in texts or side_b not in texts:
continue
for phrase in phrases:
ok(f"「{phrase}」前后端都在",
phrase in texts[side_a] and phrase in texts[side_b],
f"{PARALLEL_FILES[side_a]} / {PARALLEL_FILES[side_b]}")
for side, backend_snippet, frontend_snippet in PARALLEL_CONSTANTS:
if "backend" not in texts or side not in texts:
continue
name = backend_snippet.split(" ")[0].split("=")[0]
ok(f"{name} 两边同一句",
backend_snippet in texts["backend"] and frontend_snippet in texts[side],
f"{PARALLEL_FILES['backend']}:{backend_snippet!r} / {PARALLEL_FILES[side]}:{frontend_snippet!r}")
# 界面文案两边都要有,缺一边就是切到英文给配的人看一串键名
locales = {}
for name in ("zh", "en"):
path = root / f"frontend/src/i18n/locales/{name}.ts"
if path.exists():
locales[name] = path.read_text(encoding="utf-8")
if locales:
for key in ("relationScope:", "relationScopeCreated:", "relationScopeRelated:",
"relationScopeOnlyNote:", "relationScopeAndStatusNote:"):
for name, text in locales.items():
ok(f"词条 {key} 在 {name} 里", bool(re.search(rf"^\s*{re.escape(key)}", text, re.M)))
# ---------------------------------------------------------------------------
def main(argv: list[str]) -> int:
stages = [
("候选范围那一档", check_scope_reading),
("那一条 SQL", check_scope_sql),
("读对方表单的哪几格", check_display_paths),
("取出来的那一份文本", check_form_display),
("两条接口各按哪一条筛", check_endpoint_conditions),
("摘要里那个 data 键", check_summary_payload),
("回显认哪几个名字", check_summary_lookup),
("前后端常量与措辞", check_wording_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:]))