#!/usr/bin/env python3 """守「办结之后发起人还能把这张单转给别人看」这一条通道,库里不留东西。 用户口径(2026-11 提的):办结的流程,发起人要能转发。翻成代码是三句话: 1. **这条通道只服务归档件**:办结那一刻待办全被收走,cc_task(要一张还在手上的待办)就此 走不通;而 share_work 虽然也认归档件,它**没有一道身份闸**——任何登录用户拿到 work_id 都能把别人的单分享出去。forward_completed 补的就是这两块:在途件挡回「请到待办里抄送」 (否则等于开一条绕过环节「允许抄送」配置的后门),且只有发起人本人或管理员按得动。 2. **转出去的是待阅,不是别的**:来源仍写 read_type="cc",不新增枚举——待阅列表、导出、筛选、 i18n 认的是 cc / share / comment 那三种,「转发」与「抄送」在待阅里本就是同一种东西。默认 不要求处理(点开单据即转已阅,见 mark_reads_for_work);勾了要求处理的那条点开不算完, 必须本人带处理意见走 handle。 3. **旗标与闸同进退**:详情报文里的 can_forward 比的是 row.creator == person_id(users 表行 id),引擎那道闸比的是 creator_identity == ref(登录账号)。两列在正常发起的单上同源, 但账号那一列会被人/组织同步改写(migrate_identity_refs.py --runtime 那一档)。闸比旗标 严一分,造出来的是「按钮摆出来、一点就 ENGINE_ERROR」——所以那道闸认两套列、宁宽勿严, 而第 4 段那条跨层断言(三个角色各走一遍:先读旗标、立刻照旗标去转)钉的就是这件事。 发起人、收件人、旁观者都用库里现成的真人账号,不往别人的流程上挂规则、不改任何流程设计。 校验单是真发的(借那张已发布的备用金流程),收尾按 job 与标题清干净。库里没有这条流程、 或凑不出足够的真人账号时逐项报「跳过」,不硬闯。:: PYTHONPATH=. python3 scripts/check_forward_completed.py """ from __future__ import annotations import os import pathlib import sys from datetime import datetime sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent)) # TestClient 会跑一遍应用启动:不关掉调度线程,超时标记与写回投递会在断言中间自己动 os.environ.setdefault("OA_SCHEDULER", "off") from sqlalchemy import select # noqa: E402 from starlette.testclient import TestClient # noqa: E402 from app import models # noqa: E402 from app.db import SessionLocal # noqa: E402 from app.main import app # noqa: E402 from app.security import create_access_token # noqa: E402 from app.service import personref # noqa: E402 from check_write_payload import purge # noqa: E402 from app.engine import engine as engine_module # noqa: E402 PROCESS_NAME = "备用金申请流程" DATA = { "loanType": "personalLoan", "loanReason": "转发通道校验", "loanItems": [{"loanNote": "校验", "loanType": "personalLoan", "loanTypeName": "校验", "loanAmount": 1000, "returnDate": "2099-12-31"}], "loanAmountTotal": 1000, "payItems": [{"payee": "康文靖", "bankName": "校验银行", "bankAccount": "6222020200009999", "payAmount": 1000, "payWay": "bank"}], } STAMP = datetime.now().strftime("%m%d%H%M%S") FAILS: list[str] = [] PASSED = 0 def check(label: str, passed: bool, detail: str = "") -> bool: """报一条结果;passed 为假就记进失败清单。返回它本身,好让调用方就此收尾。""" global PASSED if passed: PASSED += 1 print(f"[通过] {label}") else: FAILS.append(label) print(f"[FAIL] {label}" + (f" -> {detail}" if detail else "")) return passed class Api: """薄壳:把一次接口调用折成 (status, data, message)。""" def __init__(self) -> None: self._client = TestClient(app, raise_server_exceptions=False) @staticmethod def token(person: models.User) -> str: return create_access_token(str(person.id))[0] def call(self, method: str, path: str, *, token: str, json: dict | None = None): response = self._client.request( method, f"/api/v1{path}", headers={"Authorization": f"Bearer {token}"}, json=json) try: body = response.json() except ValueError: body = {} body = body if isinstance(body, dict) else {} return response.status_code, body.get("data"), str(body.get("message") or "") def post(self, path: str, *, token: str, json: dict | None = None): return self.call("POST", path, token=token, json=json) def get(self, path: str, *, token: str): return self.call("GET", path, token=token) def reads_of(db, work_id: str, identity: str) -> list[models.Read]: db.rollback() # 接口用的是另一个 Session,快照不换就看不见刚才写的 return list(db.execute( select(models.Read).where(models.Read.work == work_id, models.Read.identity == identity) ).scalars().all()) def dones_of(db, work_id: str, identity: str) -> list[models.ReadCompleted]: db.rollback() return list(db.execute( select(models.ReadCompleted).where(models.ReadCompleted.work == work_id, models.ReadCompleted.identity == identity) ).scalars().all()) def open_tasks(payload: dict) -> list[dict]: return [row for row in ((payload or {}).get("tasks") or []) if not row.get("finish_time")] def first_route(task: dict) -> str: names = task.get("route_name_list") or task.get("route_list") or [] return str(names[0]) if names else "submit" def main() -> int: # noqa: C901 - 一条直线跑完七组断言,拆开反而要把 id 传来传去 db = SessionLocal() process = db.execute( select(models.Process).where(models.Process.name == PROCESS_NAME, models.Process.enabled.is_(True)) ).scalars().first() if process is None: print(f"[跳过] 没有已发布的「{PROCESS_NAME}」,这一项校不了") db.close() return 0 people = db.execute( select(models.User).where(models.User.status == models.UserStatus.ACTIVE).order_by(models.User.id) ).scalars().all() starter = next((row for row in people if row.role == models.ROLE_ADMIN), None) if starter is None: print("[跳过] 库里没有在职的管理员账号,发起与办结这一路校不了") db.close() return 0 others = [row for row in people if row.id != starter.id and personref.ref_of(row)] if len(others) < 4: print(f"[跳过] 除发起人之外只凑出 {len(others)} 个真人账号,转发的几种角色分不开") db.close() return 0 api = Api() admin = api.token(starter) # 一人一格:一个人、一张单、一类待阅只留一条(再转是更新已有那条),几个角色若共用 # 一个人,后一条会把前一条盖掉,谁也证不了谁。 p_plain, p_action, p_outsider, p_second = others[:4] ref = personref.ref_of tokens = {row.id: api.token(row) for row in others} jobs: list[str] = [] titles: list[str] = [] def start(label: str) -> tuple[str, str, dict]: """发起一张校验单,回 (job, work_id, 报文);没发起来就是空手。""" title = f"转发通道门-{label}-{STAMP}" titles.append(title) status, data, message = api.post( "/job", token=admin, json={"process": process.id, "data": DATA, "title": title}) if status >= 400 or not data: check(f"发起「{label}」这张校验单", False, f"{status} {message}") return "", "", {} jobs.append(str(data.get("job") or "")) return str(data.get("job") or ""), str(data.get("work") or ""), data # 这张备用金流程的环节上真挂着 ccRules(到达/办完/办结三档都抄发起人)。不换成空探针, # 发起人自己名下就会多出流程顺手抄的那几条 cc 待阅:第 3 段「转给两个人各一条」与第 6 段 # 「count == 1」数的就不再是转发那一条了,绿得靠运气(挑中的账号刚好没被抄到)。 real_cc_rules = engine_module.cc_rules engine_module.cc_rules = lambda activity, when: [] try: # ---------------- 1) 通道只认归档件:在途件挡回待办那条路 ---------------- job1, work1, created1 = start("在途与归档") if not check("这张校验单发得起来", bool(work1), "发起没成功"): return 1 tasks = open_tasks(created1) if not check("拿得到在途待办(办结要用它推)", bool(tasks), str(created1)[:120]): return 1 task_id = str(tasks[0].get("id") or "") route = first_route(tasks[0]) status, data, message = api.post(f"/work/{work1}/forward", token=admin, json={"identities": [ref(p_plain)], "opinion": "还没办结就想转"}) check("在途件走这条通道被挡回(请到待办里抄送)", status >= 400 and "待办" in message, f"{status} {message} {data}") check("被挡这一趟一条待阅都没落", not reads_of(db, work1, ref(p_plain))) # 旗标同样不给在途件:按钮不该摆出来再让人吃一个错 _, detail_live, _ = api.get(f"/job/{job1}", token=admin) flag_live = (detail_live or {}).get("can_forward") check("在途件的详情报文里 can_forward 为假", flag_live in (False, None), f"can_forward={flag_live}") # ---------------- 2) 办结:归档件才按得动 ---------------- status, _, message = api.post(f"/task/{task_id}/execute", token=admin, json={"route_name": route, "opinion": "校验同意"}) if not check("这张单推得动(推到办结)", status < 400, f"{status} {message}"): return 1 db.rollback() # 接口用的是另一个 Session,本会话不换快照就看不见刚归档的那一行 archived = db.get(models.WorkCompleted, work1) if not check("单据已归档(这条通道认的主体是归档件)", archived is not None, f"work_id={work1}"): return 1 _, detail_done, _ = api.get(f"/job/{job1}", token=admin) flag_done = (detail_done or {}).get("can_forward") check("办结之后发起人这侧 can_forward 为真", flag_done is True, f"can_forward={flag_done}") # ---------------- 3) 转给两个人:两条待阅都停在待阅里 ---------------- status, data, message = api.post( f"/work/{work1}/forward", token=admin, json={"identities": [ref(p_plain), ref(p_action)], "opinion": "结果请看一下", "requiresAction": False}) rows_plain = reads_of(db, work1, ref(p_plain)) rows_action = reads_of(db, work1, ref(p_action)) got = int((data or {}).get("count") or 0) check("转发打得通,回的是那一沓待阅(与分享同形状)", status < 400 and got == 2 and len((data or {}).get("reads") or []) == 2, f"{status} {message} {data}") check("转给两个人 → 两个人各一条待阅", len(rows_plain) == 1 and len(rows_action) == 1, f"甲 {len(rows_plain)} / 乙 {len(rows_action)}") check("都没有一落地就算已阅(转发只是让人看,不是替人看)", not dones_of(db, work1, ref(p_plain)) and not dones_of(db, work1, ref(p_action))) first = rows_plain[0] if rows_plain else None kind = getattr(first, "read_type", "") needs = getattr(first, "requires_action", None) check("来源仍是 cc(界面上归在「抄送」那一类,不另立枚举),且默认不要求处理", first is not None and kind == "cc" and needs is False, f"read_type={kind} requires_action={needs}") # 通知要点名是转发:借 READ_TITLES 里 cc 那句「抄送给您」,人只当是流程里顺手 # 抄来的,看不出是谁在办结之后又递了一次(来源那一格仍写「抄送」,是刻意的) notified = db.execute( select(models.Notification).where(models.Notification.work == work1, models.Notification.identity == ref(p_plain)) ).scalars().all() titles_seen = [str(row.title or '') for row in notified] check('站内信标题点名是转发(不是那句通用的「抄送给您」)', any('转发了这张已办结的单据' in one for one in titles_seen), f'通知标题 {titles_seen}') note = getattr(first, "opinion", None) check("随附那句转发的话落在这条待阅上", note == "结果请看一下", f"opinion={note!r}") # 流程步骤上「这是转发不是抄送」的唯一证据就是这一列:来源那一格仍是 cc, # 没有它,轨迹图只能把一次办结后的转发念成「这一环抄给了李强」。 check("落库时带着 forwarded 标记(流程步骤分辨抄送与转发只认这一列)", first is not None and bool(getattr(first, "forwarded", False)) is True, f"forwarded={getattr(first, 'forwarded', None)}") # 这一单真的走通了一次转发,就该当场验一遍界面读到什么:详情报文里那本 # 转发账(flow.forwards)必须有这两个人,且他们不被算进任何环节的抄送名单。 _, detail_fwd, _ = api.get(f"/job/{job1}", token=admin) block = ((detail_fwd or {}).get("flow") or {}).get("forwards") or {} names = sorted(str(item.get("name") or "") for item in block.get("items") or []) wanted = sorted({str(getattr(first, "identity_name", "") or ""), str((rows_action[0].identity_name if rows_action else "") or "")}) check("详情报文里那本转发账数得出这两个人(不是靠前端猜)", block.get("count") == 2 and names == wanted, f"count={block.get('count')} {names} vs {wanted}") check("转发标着未阅:他们还没点开这张单", block.get("unread") == 2, str(block)) stamped = bool(getattr(first, "completed", False)) and getattr(first, "work_completed", "") == work1 check("归档件没有环节可判:这条待阅带着归档标记落着", first is not None and stamped, f"completed={getattr(first, 'completed', None)} work_completed={getattr(first, 'work_completed', None)}") # 转发照样是要留痕的一步:界面上「审批记录」那条时间线读的就是这一行。 # 只断「接口成功」证不了留痕落下了——detail 里那句人数还得对得上转出去的行数。 logs = db.execute( select(models.OperationLog).where(models.OperationLog.action == "forward_work", models.OperationLog.target == work1) ).scalars().all() seen = [str(row.detail or "") for row in logs] check("转发留下操作日志:动作、对象是单据主键、detail 报出转给几人", any("转发 2 人" in one for one in seen), f"日志 detail {seen}") # ---------------- 4) 跨层同进退:旗标说什么,转发动作就给什么 ---------------- # 三个角色各走一遍。这条比单点断言值钱:旗标(person_id 那一列)与那道闸(账号那一 # 列)一旦漂移,红的就是这一条,而不是等到用户在界面上按出一个错。 _, detail_other, _ = api.get(f"/job/{job1}", token=tokens[p_outsider.id]) flag_other = (detail_other or {}).get("can_forward") status, _, message = api.post( f"/work/{work1}/forward", token=tokens[p_outsider.id], json={"identities": [ref(p_second)], "opinion": "旁观者来转"}) blocked = status >= 400 and "发起人" in message check("非发起人:旗标为假、转发也确实被挡(按钮与闸同一句话)", flag_other in (False, None) and blocked, f"flag={flag_other} {status} {message}") check("被挡这一趟没给别人落待阅", not reads_of(db, work1, ref(p_second))) status, _, _ = api.post(f"/work/{work1}/forward", token=admin, json={"identities": [ref(p_second)], "opinion": "管理员替发起人转"}) check("管理员:旗标为真(上面那条已验),转发也确实打得通", status < 400 and bool(reads_of(db, work1, ref(p_second))), f"status={status}") # ---------------- 4.5) 漂移那一支:旗标认 person_id,那道闸两套列任一命中即放行 ---------------- # 上面那位发起人恰好是管理员,is_admin 先把闸挡了,两套身份列其实一次都没走到。 # 而漂移会发生的正是别人发起的单:旗标比的是 creator(users 行 id),闸先比的是 # creator_identity(登录账号)——账号会被人/组织同步改写,两列就有对不上的一天。 # 这里把归档件的两列各摆一种样子,钉住「旗标说能转,转就得成」这个方向: # 浅一档(只认账号)会让旗标为真的人按下去吃一个 ENGINE_ERROR,那正是本次改掉的毛病。 owner = p_plain owner_person, owner_ref = str(archived.creator), str(archived.creator_identity) archived.creator, archived.creator_identity = str(owner.id), ref(owner) db.commit() try: _, detail_owner, _ = api.get(f"/job/{job1}", token=tokens[owner.id]) flag_owner = (detail_owner or {}).get("can_forward") status, _, message = api.post(f"/work/{work1}/forward", token=tokens[owner.id], json={"identities": [ref(p_second)], "opinion": "我自己发起的单我转"}) check("非管理员的发起人:旗标为真,转发也确实打得通(两套列命中)", flag_owner is True and status < 400, f"flag={flag_owner} {status} {message}") # 账号那一列漂了(行 id 还在),旗标照旧为真、转发也照旧得成——放宽那道闸要的就是这个 archived.creator_identity = f"漂移账号-{STAMP}" db.commit() _, detail_drift, _ = api.get(f"/job/{job1}", token=tokens[owner.id]) status, _, message = api.post(f"/work/{work1}/forward", token=tokens[owner.id], json={"identities": [ref(p_second)], "opinion": "账号漂了也要转得动"}) check("账号那一列漂移后:旗标仍为真且照样转得动(闸认两套列,不造死按钮)", (detail_drift or {}).get("can_forward") is True and status < 400, f"flag={(detail_drift or {}).get('can_forward')} {status} {message}") # 两列都不认的旁观者照样挡:放宽那一支不等于放开这道闸 status, _, message = api.post(f"/work/{work1}/forward", token=tokens[p_outsider.id], json={"identities": [ref(p_second)], "opinion": "漂移时旁观者来转"}) check("两列都不认的人仍挡得住(放宽那一支没把闸门放开)", status >= 400 and "发起人" in message, f"{status} {message}") finally: archived.creator, archived.creator_identity = owner_person, owner_ref db.commit() # ---------------- 5) 重复转发同一人:更新已有那条,不堆出第二条 ---------------- before = reads_of(db, work1, ref(p_plain)) status, _, message = api.post(f"/work/{work1}/forward", token=admin, json={"identities": [ref(p_plain)], "opinion": "再转一次"}) after = reads_of(db, work1, ref(p_plain)) same = bool(before) and bool(after) and before[0].id == after[0].id check("同一个人再转一次只留一条(界面上不会长出两条一模一样的待阅)", status < 400 and len(before) == 1 and len(after) == 1 and same, f"{status} {message} 之前 {len(before)} 之后 {len(after)}") # ---------------- 6) 要求处理的那条:点开单据不算完,写意见才算完 ---------------- status, _, message = api.post( f"/work/{work1}/forward", token=admin, json={"identities": [ref(p_action)], "opinion": "这句只是转发的来意", "requiresAction": True}) action_row = next((row for row in reads_of(db, work1, ref(p_action)) if row.requires_action), None) if check("要求处理的那条转得出去,落库时带着 requires_action", status < 400 and action_row is not None, f"{status} {message}"): action_id = str(action_row.id) # 点开单据页顺手登记的那一趟只清「不要求处理」的,这条必须原样留着 api.post("/read/view", token=tokens[p_action.id], json={"job": job1}) still = next((row for row in reads_of(db, work1, ref(p_action)) if str(row.id) == action_id), None) moved_early = len(dones_of(db, work1, ref(p_action))) check("要求处理那条:点开单据不算看完,仍停在待阅里", still is not None and moved_early == 0, f"还在待阅 {still is not None} 已阅 {moved_early} 条") status, _, message = api.post(f"/read/{action_id}/view", token=tokens[p_action.id], json={"opinion": ""}) check("要求处理那条:空处理意见也处理不掉", status >= 400, f"{status} {message}") status, _, message = api.post(f"/read/{action_id}/handle", token=tokens[p_action.id], json={"opinion": "已核对,无问题"}) moved = [row for row in dones_of(db, work1, ref(p_action)) if str(row.read) == action_id] stored = moved[0].opinion if moved else None handled = moved[0].handle_time if moved else None check("要求处理那条:写了处理意见才转已阅;档案里是本人那句、不是转发的来意" "(顺带验这两句没互相顶包)", status < 400 and len(moved) == 1 and stored == "已核对,无问题" and handled is not None, f"{status} {message} opinion={stored!r} handle_time={handled}") # ---------------- 7) 闸门收尾:空人选与超上限各挡一句 ---------------- status, _, message = api.post(f"/work/{work1}/forward", token=admin, json={"identities": []}) check("一个人都没挑:挡下来,不静悄悄成功", status >= 400, f"{status} {message}") # 超上限宁挡不切:这批人是他自己挑着点下的,静悄悄少发几个,界面上照样回「成功」。 # 这台库上凑不出 51 个真人,就把上限临时压到 2、传 3 个真人——要钉的是那条"挡", # 与上限具体是几无关(真超了才报得出那一句,未被截断的行为由上面几条覆盖)。 limit_real = engine_module.FORWARD_LIMIT engine_module.FORWARD_LIMIT = 2 try: crowd = [ref(p_plain), ref(p_action), ref(p_second)] status, _, message = api.post(f"/work/{work1}/forward", token=admin, json={"identities": crowd, "opinion": "人多"}) check("挑的人超过单次上限:整批挡下并说清上限,而不是悄悄少发", status >= 400 and "2" in message, f"{status} {message}") finally: engine_module.FORWARD_LIMIT = limit_real finally: engine_module.cc_rules = real_cc_rules # 探针换回去,别影响同目录别的守卫 db.rollback() purge(db, jobs, titles) db.close() print(f"\n合计 {PASSED + len(FAILS)} 项:通过 {PASSED} / 失败 {len(FAILS)}") return 1 if FAILS else 0 if __name__ == "__main__": raise SystemExit(main())