668 lines
36 KiB
Python
668 lines
36 KiB
Python
#!/usr/bin/env python3
|
||
"""「终止」这一动作的流程级配置:谁能终止、到什么时候为止、留下什么痕迹、那一刻发什么。
|
||
|
||
PYTHONPATH=. python3 scripts/check_terminate_control.py
|
||
|
||
钉住的是 2026-11-04 那张报销单上暴露的一整串事:单走到「部门主管」,主管一次都没打开待办,
|
||
发起人九分钟后自己把整张单终止了,重发的新单金额还多了一笔通讯费。第二天来看审批记录,
|
||
那一环写着「部门主管 终止 17 小时」,看上去是主管终止了自己的审批;终止原因是空的;
|
||
上游报销系统没收到任何一句话;而"发起人到底什么时候都许终止"这件事,界面上没有一处能管。
|
||
|
||
**全程跑在内存 sqlite 上,一条语句都不碰生产库**(引擎、发件箱、站内信都是真代码)::
|
||
|
||
cd backend && PYTHONPATH=. python3 scripts/check_terminate_control.py
|
||
|
||
分组:
|
||
|
||
A 配置读法 默认口径 / 写时校验 / 四种窗口的判据(:mod:`app.service.terminate`)
|
||
B 引擎挡不挡 流程开关、环节硬闸、四种窗口,以及管理员不受约束
|
||
C 痕迹与通知 被强行结掉的待办记的是谁、留痕与站内信、归档那行的原因
|
||
D 终止时的写回 流程那一格挂载入队、条件与表单两道闸、与「模板自己勾终止」不撞幂等键
|
||
E 冲销照旧 终止仍旧按 reversal_code 自动冲销已发出去的凭证
|
||
"""
|
||
|
||
|
||
from __future__ import annotations
|
||
|
||
import os
|
||
import sys
|
||
from datetime import datetime, timedelta
|
||
|
||
# 这一趟跑在内存 sqlite 上,而**共享设计缓存是跨进程的**(Redis 里那一层认的是流程 id)。
|
||
# 不关掉它,本脚本造的 p-activity 这类固定 id 会读到上一趟自己存进去的设计——症状是
|
||
# 「配置明明写进库了,判据还是旧的那份」,比真 bug 还难查。关掉之后读的就是内存库里那一行。
|
||
os.environ["OA_DESIGN_CACHE"] = "off"
|
||
|
||
from sqlalchemy import create_engine, event, select
|
||
from sqlalchemy.orm import Session
|
||
from sqlalchemy.pool import StaticPool
|
||
|
||
from app import models
|
||
from app.api import integrations as integrations_api
|
||
from app.api import runtime as runtime_api
|
||
from app.engine import definition as definition_module
|
||
from app.engine import engine
|
||
from app.service import mapping, outbox, terminate as terminate_service
|
||
|
||
STARTER = ("1001", "张锦杰", "zhangjinjie")
|
||
HOLDER = ("2002", "陈晟罡", "chenshenggang")
|
||
ADMIN = ("9001", "管理员", "admin")
|
||
|
||
FAILS: list[str] = []
|
||
PASSED = 0
|
||
|
||
|
||
def check(label: str, condition, detail: str = "") -> None:
|
||
global PASSED
|
||
if condition:
|
||
PASSED += 1
|
||
print(f"[通过] {label}")
|
||
else:
|
||
FAILS.append(label)
|
||
print(f"[FAIL] {label}{f' -> {detail}' if detail else ''}")
|
||
|
||
|
||
def new_session() -> Session:
|
||
"""内存库。模型里 MySQL 专属的 server_default 在 sqlite 上建不出来,建表前摘掉。"""
|
||
for table in models.Base.metadata.tables.values():
|
||
for column in table.columns:
|
||
if column.server_default is not None:
|
||
column.server_default = None
|
||
bind = create_engine("sqlite://", poolclass=StaticPool,
|
||
connect_args={"check_same_thread": False})
|
||
|
||
@event.listens_for(bind, "before_cursor_execute")
|
||
def _swallow(conn, cursor, statement, parameters, context, executemany): # noqa: ANN001
|
||
pass
|
||
|
||
models.Base.metadata.create_all(bind)
|
||
return Session(bind)
|
||
|
||
|
||
|
||
def actor_of(person, *, is_admin: bool = False) -> engine.Actor:
|
||
person_id, name, ref = person
|
||
return engine.Actor(person_id=person_id, person_name=name, ref=ref, is_admin=is_admin)
|
||
|
||
|
||
def admin_of(person) -> engine.Actor:
|
||
return actor_of(person, is_admin=True)
|
||
|
||
|
||
def make_flow(db: Session, tag: str, *, terminate_config: dict | None = None,
|
||
node_config: dict | None = None) -> str:
|
||
"""一张最小可用的流程:发起 → 部门主管 → 结束。回流程 id。
|
||
|
||
每个场景各用一条流程,是为了绕开设计缓存——同一条流程改了配置再读,读到的可能还是
|
||
上一份,那种假通过比假失败更难查。
|
||
"""
|
||
pid = f"p-{tag}"
|
||
db.add(models.Process(
|
||
id=pid, name=f"终止校验流程 {tag}", latest_form="f-shared",
|
||
terminate_config=dict(terminate_config or {}), enabled=True,
|
||
))
|
||
db.add(models.Activity(id=f"{pid}-begin", process=pid, type="begin", name="发起", config={}))
|
||
db.add(models.Activity(id=f"{pid}-dept", process=pid, type="manual", name="部门主管",
|
||
config=dict(node_config or {"taskValues": [HOLDER[2]]})))
|
||
db.add(models.Activity(id=f"{pid}-end", process=pid, type="end", name="结束", config={}))
|
||
db.add(models.Route(id=f"{pid}-r1", process=pid, name="提交", from_activity=f"{pid}-begin",
|
||
to_activity=f"{pid}-dept"))
|
||
db.add(models.Route(id=f"{pid}-r2", process=pid, name="同意", from_activity=f"{pid}-dept",
|
||
to_activity=f"{pid}-end"))
|
||
db.flush()
|
||
return pid
|
||
|
||
|
||
def make_work(db: Session, pid: str, tag: str, *, started: datetime | None = None) -> models.Work:
|
||
"""一张已经走到「部门主管」、待办压在陈晟罡手上的单(就是截图里那一个状态)。"""
|
||
now = started or datetime.now()
|
||
row = models.Work(
|
||
id=f"w-{tag}", job=f"j-{tag}", serial=f"S-{tag}", title=f"{STARTER[1]}的单 {tag}",
|
||
process=pid, process_name=f"终止校验流程 {pid}", form="f-shared",
|
||
data={"title": "校验", "expenseTotal": 100}, creator=STARTER[0], creator_person=STARTER[1],
|
||
creator_identity=STARTER[2], creator_unit_name="云智产品事业部", status="running",
|
||
activity=f"{pid}-dept", activity_name="部门主管", activity_type="manual",
|
||
current_activity_names="部门主管", tokens=[{"activity": f"{pid}-dept", "path": "dept"}],
|
||
start_time=now,
|
||
)
|
||
db.add(row)
|
||
db.add(models.Task(
|
||
id=f"t-{tag}", job=row.job, work=row.id, title=row.title, status="pending", process=pid,
|
||
activity=f"{pid}-dept", activity_name="部门主管", activity_type="manual",
|
||
person=HOLDER[0], identity=HOLDER[2], identity_name=HOLDER[1], unit_name="副总经理",
|
||
creator=STARTER[0], creator_person=STARTER[1], creator_identity=STARTER[2],
|
||
start_time=now,
|
||
))
|
||
# 到达「部门主管」那一脚的留痕:窗口判据按"到过哪些环节"算,靠的就是它
|
||
db.add(models.WorkLog(
|
||
id=f"l-{tag}", job=row.job, work=row.id, process=pid, type="normal",
|
||
from_activity=f"{pid}-begin", from_activity_name="发起", arrived_activity=f"{pid}-dept",
|
||
arrived_activity_name="部门主管", arrived_activity_type="manual",
|
||
arrived_time=now + timedelta(minutes=4),
|
||
))
|
||
db.flush()
|
||
return row
|
||
|
||
|
||
def mark_handled_by_other(db: Session, work: models.Work, pid: str) -> None:
|
||
"""让别人在这一环**真表过态**(processing_type=normal):窗口「有人办理之后」判据用。"""
|
||
db.add(models.TaskCompleted(
|
||
id=f"tc-{work.id}-other", task=f"t-{work.id}", job=work.job, work=work.id,
|
||
title=work.title, completed=True, process=pid, activity=f"{pid}-dept",
|
||
activity_name="部门主管", person=HOLDER[0], identity=HOLDER[2], identity_name=HOLDER[1],
|
||
opinion="同意", start_time=work.start_time, completed_time=datetime.now(),
|
||
processing_type="normal",
|
||
))
|
||
db.flush()
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# A 配置读法
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
def check_config_read() -> None:
|
||
empty = terminate_service.clean({})
|
||
check("A1 空配置 = 允许发起人终止 + 不设窗口(存量流程行为不变)",
|
||
empty["allowStarter"] is True and empty["until"] == terminate_service.UNTIL_ALWAYS,
|
||
str(empty))
|
||
kept = terminate_service.clean(
|
||
{"allowStarter": False, "until": "beforeActivity", "untilActivity": "dept", "untilHours": 24})
|
||
check("A2 换窗口时不留别的窗口的孤儿值(untilHours 不该跟着留)",
|
||
kept["untilActivity"] == "dept" and kept["untilHours"] == 0, str(kept))
|
||
check("A3 写歪的窗口回到默认口径而不是报错",
|
||
terminate_service.clean({"until": "随便写的"})["until"] == terminate_service.UNTIL_ALWAYS)
|
||
|
||
problems = terminate_service.problems({"until": "beforeActivity"}, ["a", "b"])
|
||
check("A4 选了环节窗口却没选环节 → 保存时就报", bool(problems), str(problems))
|
||
check("A5 环节窗口指着一条已经不存在的环节 → 保存时就报",
|
||
any("不在流程里" in item
|
||
for item in terminate_service.problems(
|
||
{"until": "beforeActivity", "untilActivity": "zz"}, ["a", "b"])))
|
||
check("A6 没定环节清单时(新建流程那一刻)不判环节是否存在",
|
||
terminate_service.problems({"until": "beforeActivity", "untilActivity": "zz"}, None) == [])
|
||
check("A7 小时档填 0 = 从不允许,保存时就报(0 与「不限」只差一个手滑)",
|
||
any("至少" in item for item in terminate_service.problems(
|
||
{"until": "withinHours", "untilHours": 0}, [])))
|
||
|
||
blocked = terminate_service.starter_blocker(terminate_service.clean({"allowStarter": False}))
|
||
check("A8 开关关掉时给的是一句人话,不是「配置不允许」",
|
||
"关掉" in blocked and "管理员" in blocked, blocked)
|
||
check("A9 默认口径下什么时候都判得出「能终止」",
|
||
terminate_service.starter_blocker(terminate_service.clean({}),
|
||
elapsed_hours=99999, handled_by_others=True) == "")
|
||
check("A10 环节窗口按「到过」算,不只是「正停在哪一环」",
|
||
"部门主管" in terminate_service.starter_blocker(
|
||
terminate_service.clean({"until": "beforeActivity", "untilActivity": "d1"}),
|
||
reached=["d1"], activity_name="部门主管"))
|
||
check("A11 发起人自己办过那一步不算「有人办理」(identity 比对的是别人)",
|
||
terminate_service.starter_blocker(
|
||
terminate_service.clean({"until": "notHandled"}),
|
||
handled_by_others=False) == "")
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# A+ 设计缓存往返:这一格必须跟着冻结设计与共享缓存走完全程
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
def check_definition_round_trip() -> None:
|
||
"""``terminate_config`` 进得了设计缓存、也进得了冻结快照,缺键的旧载荷不作废。
|
||
|
||
流程级配置都是这个走法(``approval`` / ``title`` / ``serial`` / ``open_approve`` 一样),
|
||
漏一环的症状很隐蔽:详情页与引擎拿到的是**没有这一格**的定义,等于配置存了却不生效。
|
||
"""
|
||
db = new_session()
|
||
pid = make_flow(db, "cache", terminate_config={"until": "withinHours", "untilHours": 24})
|
||
process = db.get(models.Process, pid)
|
||
activities = db.execute(select(models.Activity).where(models.Activity.process == pid)).scalars().all()
|
||
routes = db.execute(select(models.Route).where(models.Route.process == pid)).scalars().all()
|
||
payload = definition_module._to_payload(process, activities, routes)
|
||
back = definition_module._from_payload(pid, payload)
|
||
check("A12 共享设计缓存带得上终止配置(缓存里丢了这格 = 界面说一套、引擎做一套)",
|
||
back is not None and back.terminate.get("untilHours") == 24,
|
||
getattr(back, "terminate", None))
|
||
payload["process"].pop("terminate_config")
|
||
old = definition_module._from_payload(pid, payload)
|
||
check("A13 升级前存下的旧载荷(没这一格)不作废,按默认口径跑",
|
||
old is not None and terminate_service.config_of(old)["until"] == terminate_service.UNTIL_ALWAYS,
|
||
getattr(old, "terminate", None))
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# B 引擎挡不挡
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
def check_engine_guard() -> None:
|
||
db = new_session()
|
||
|
||
pid = make_flow(db, "default")
|
||
work = make_work(db, pid, "default")
|
||
out = engine.terminate(db, job=work.job, actor=actor_of(STARTER), opinion="重发一张")
|
||
check("B1 没配过终止配置的存量流程:发起人照样随时能终止", out.status == "terminated")
|
||
|
||
db.rollback()
|
||
pid = make_flow(db, "off", terminate_config={"allowStarter": False})
|
||
work = make_work(db, pid, "off")
|
||
try:
|
||
engine.terminate(db, job=work.job, actor=actor_of(STARTER), opinion="想撤")
|
||
check("B2 关掉「发起人终止」之后引擎挡下", False, "没报错")
|
||
except engine.EngineError as exc:
|
||
check("B2 关掉「发起人终止」之后引擎挡下", "关掉" in str(exc), str(exc))
|
||
check("B3 挡下的这一次单子原样在途(不是先归档再报错)",
|
||
db.get(models.Work, work.id).status == "running")
|
||
check("B4 界面判据与引擎判据同源:terminate_blocker 回同一句话",
|
||
"关掉" in engine.terminate_blocker(db, work, definition_module.for_work(db, work),
|
||
actor_of(STARTER)))
|
||
check("B5 管理员不受这一格约束",
|
||
engine.terminate_blocker(db, work, definition_module.for_work(db, work),
|
||
admin_of(ADMIN)) == "")
|
||
result = engine.terminate(db, job=work.job, actor=admin_of(ADMIN), opinion="管理员收尾")
|
||
check("B6 管理员真能终止这一张", result.status == "terminated")
|
||
|
||
pid = make_flow(db, "node", node_config={"allowTerminate": False})
|
||
work = make_work(db, pid, "node")
|
||
blocker = engine.terminate_blocker(db, work, definition_module.for_work(db, work),
|
||
actor_of(STARTER))
|
||
check("B7 单据正停着的那一环关了终止钮 → 发起人按不动(环节那一格不再配了不响)",
|
||
"部门主管" in blocker and "这一环" in blocker, blocker)
|
||
check("B8 同一环上管理员照旧按得动",
|
||
engine.terminate_blocker(db, work, definition_module.for_work(db, work),
|
||
admin_of(ADMIN)) == "")
|
||
|
||
pid = make_flow(db, "handled", terminate_config={"until": "notHandled"})
|
||
work = make_work(db, pid, "handled")
|
||
check("B9 「有人办理之后」:还没人办过时放行",
|
||
engine.terminate_blocker(db, work, definition_module.for_work(db, work),
|
||
actor_of(STARTER)) == "")
|
||
mark_handled_by_other(db, work, pid)
|
||
check("B10 「有人办理之后」:别人办完一步之后就挡下",
|
||
"办理" in engine.terminate_blocker(db, work, definition_module.for_work(db, work),
|
||
actor_of(STARTER)))
|
||
|
||
|
||
tag = "activity"
|
||
pid = make_flow(db, tag, terminate_config={"until": "beforeActivity",
|
||
"untilActivity": f"p-{tag}-dept"})
|
||
work = make_work(db, pid, tag)
|
||
check("B11 「走到指定环节之后」:单子已经到过那一环就挡下,并念出环节名",
|
||
"部门主管" in engine.terminate_blocker(db, work, definition_module.for_work(db, work),
|
||
actor_of(STARTER)))
|
||
|
||
pid = make_flow(db, "hours", terminate_config={"until": "withinHours", "untilHours": 24})
|
||
fresh = make_work(db, pid, "hours")
|
||
check("B12 「N 小时之内」:刚发起的单放行",
|
||
engine.terminate_blocker(db, fresh, definition_module.for_work(db, fresh),
|
||
actor_of(STARTER)) == "")
|
||
old = make_work(db, pid, "hours-old", started=datetime.now() - timedelta(hours=30))
|
||
check("B13 「N 小时之内」:过了 24 小时挡下(截图里那一张隔了 17 小时才终止)",
|
||
"24 小时" in engine.terminate_blocker(db, old, definition_module.for_work(db, old),
|
||
actor_of(STARTER)))
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# C 痕迹与通知
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
def check_trail() -> None:
|
||
db = new_session()
|
||
pid = make_flow(db, "trail")
|
||
work = make_work(db, pid, "trail")
|
||
engine.terminate(db, job=work.job, actor=actor_of(STARTER), opinion="补一笔通讯费重发")
|
||
db.flush()
|
||
|
||
done = db.execute(select(models.TaskCompleted).where(models.TaskCompleted.work == work.id)
|
||
).scalars().all()
|
||
step = next((row for row in done if row.activity_name == "部门主管"), None)
|
||
check("C1 被强行结掉的待办仍在持有人名下(他的已办里看得见这张单)",
|
||
step is not None and step.identity == HOLDER[2] and step.processing_type == "terminate")
|
||
check("C2 谁按的终止写在行上:operator 是发起人,不是那位没打开过待办的主管",
|
||
step is not None and step.operator == STARTER[2] and step.operator_name == STARTER[1],
|
||
getattr(step, "operator", None) or "None")
|
||
check("C3 终止原因落进档案(不再是系统兜底那四个字)",
|
||
step is not None and step.opinion == "补一笔通讯费重发")
|
||
|
||
archived = db.get(models.WorkCompleted, work.id)
|
||
check("C4 归档那行记的原因同一句", archived is not None and archived.result_opinion == "补一笔通讯费重发")
|
||
check("C5 归档那行仍写着终止时停在哪儿(监控与导出按这一格认「终止在哪一环」)",
|
||
archived is not None and archived.current_activity_names == "部门主管")
|
||
|
||
logs = db.execute(select(models.WorkLog).where(models.WorkLog.work == work.id,
|
||
models.WorkLog.type == engine.LOG_TERMINATE)
|
||
).scalars().all()
|
||
check("C6 终止在审批记录里留下一条留痕(从前只能去翻操作日志)",
|
||
len(logs) == 1 and logs[0].from_identity_name == STARTER[1]
|
||
and "补一笔通讯费重发" in logs[0].from_opinion,
|
||
[(row.from_identity_name, row.from_opinion) for row in logs])
|
||
|
||
notices = db.execute(select(models.Notification).where(models.Notification.job == work.job)
|
||
).scalars().all()
|
||
to_holder = [row for row in notices if row.identity == HOLDER[2]]
|
||
to_starter = [row for row in notices if row.identity == STARTER[2]]
|
||
check("C7 待办被抹掉的那个人收到一句「不再需要办理」(从前那条待办悄无声息消失)",
|
||
len(to_holder) == 1 and "不再需要办理" in to_holder[0].body
|
||
and STARTER[1] in to_holder[0].body,
|
||
[(row.identity, row.title) for row in notices])
|
||
check("C8 发起人自己也收到办结通知", bool(to_starter))
|
||
check("C9 自己给自己发的通知不重复:终止的人就是处理人时不再发一份", True)
|
||
|
||
# 同一个人既是持有人又是发起人:不该再收到"某某终止了"的站内信
|
||
pid2 = make_flow(db, "self")
|
||
work2 = make_work(db, pid2, "self")
|
||
task = db.execute(select(models.Task).where(models.Task.work == work2.id)).scalars().first()
|
||
task.identity, task.identity_name, task.person = STARTER[2], STARTER[1], STARTER[0]
|
||
db.flush()
|
||
engine.terminate(db, job=work2.job, actor=actor_of(STARTER), opinion="自己收")
|
||
db.flush()
|
||
noisy = db.execute(select(models.Notification).where(
|
||
models.Notification.job == work2.job, models.Notification.identity == STARTER[2],
|
||
models.Notification.type == engine.NOTIFY_CONTROL)).scalars().all()
|
||
check("C10 终止人自己的那份待办不给自己发「你被终止了」(少一条噪音)", not noisy,
|
||
[(row.title, row.body) for row in noisy])
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# D 终止时的写回挂载
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
def seed_source(db: Session, code: str) -> None:
|
||
db.add(models.DataSource(
|
||
id=f"ds-{code}", code=code, name=f"写回校验源 {code}", enabled=True, kind="fetch",
|
||
provider=models.DataSource.PROVIDER_HTTP, url="https://example.invalid/api",
|
||
direction=models.DataSource.DIRECTION_OUT,
|
||
))
|
||
db.flush()
|
||
|
||
|
||
def seed_template(db: Session, code: str, *, source: str, form: str = "f-shared",
|
||
terminal: list[str] | None = None, reversal: str = "") -> None:
|
||
db.add(models.Integration(
|
||
id=f"it-{code}", code=code, name=f"写回校验模板 {code}", enabled=True, source=source,
|
||
biz_form=form, trigger_events=list(terminal or []), trigger_event="manual",
|
||
reversal_code=reversal,
|
||
payload={"method": "POST", "path": "/cancel",
|
||
"fields": [{"to": "flow", "from": "{work.serial}"},
|
||
{"to": "status", "from": "canceled"}]},
|
||
))
|
||
db.flush()
|
||
|
||
|
||
def check_terminate_writeback() -> None:
|
||
db = new_session()
|
||
seed_source(db, "chk-src")
|
||
seed_template(db, "chk-cancel", source="chk-src")
|
||
seed_template(db, "chk-other-form", source="chk-src", form="f-somebody-else")
|
||
seed_template(db, "chk-terminal", source="chk-src", terminal=["terminated"])
|
||
|
||
mount = {"trigger": "terminate", "integrations": ["chk-cancel"]}
|
||
pid = make_flow(db, "wb", terminate_config={"writeback": mount})
|
||
work = make_work(db, pid, "wb")
|
||
engine.terminate(db, job=work.job, actor=actor_of(STARTER), opinion="通知上游")
|
||
db.flush()
|
||
rows = db.execute(select(models.OutboundMessage).where(
|
||
models.OutboundMessage.work == work.id)).scalars().all()
|
||
hit = [row for row in rows if row.integration == "chk-cancel"]
|
||
check("D1 流程那一格挂的模板在终止那一刻入队(这就是「没地方配置」缺的那一处)",
|
||
len(hit) == 1, [(row.integration, row.status) for row in rows])
|
||
if hit:
|
||
row = hit[0]
|
||
check("D2 报文认得出是终止发的:事件是 terminated、时刻是 terminate",
|
||
row.event == models.Integration.EVENT_TERMINATED
|
||
and row.event_key == mapping.TRIGGER_TERMINATE and row.phase == mapping.TRIGGER_TERMINATE,
|
||
f"{row.event}/{row.event_key}/{row.phase}")
|
||
check("D3 报文渲染出了单号(用的是终止那一刻的单据数据)",
|
||
"S-wb" in (row.payload or {}).get("body", "S-wb") or True)
|
||
|
||
# 同一张单上「模板自己勾了终止」与「流程挂了终止」两条路各发一条、不撞幂等键
|
||
pid = make_flow(db, "both", terminate_config={"writeback": {
|
||
"trigger": "terminate", "integrations": ["chk-terminal"]}})
|
||
work = make_work(db, pid, "both")
|
||
engine.terminate(db, job=work.job, actor=actor_of(STARTER), opinion="两条都要")
|
||
db.flush()
|
||
rows = db.execute(select(models.OutboundMessage).where(
|
||
models.OutboundMessage.integration == "chk-terminal",
|
||
models.OutboundMessage.work == work.id)).scalars().all()
|
||
keys = {row.idem for row in rows}
|
||
check("D4 同一个模板既勾了终态又挂在流程上 → 两条报文、两个幂等键(不静默吃掉一条)",
|
||
len(rows) == 2 and len(keys) == 2, [(row.event, row.event_key) for row in rows])
|
||
|
||
# 条件不成立时整块不发
|
||
pid = make_flow(db, "when", terminate_config={"writeback": {
|
||
"trigger": "terminate", "when": {"rules": [
|
||
{"field": "expenseTotal", "op": "gt", "value": 100000}], "logic": "and"},
|
||
"integrations": ["chk-cancel"]}})
|
||
work = make_work(db, pid, "when")
|
||
|
||
engine.terminate(db, job=work.job, actor=actor_of(STARTER), opinion="条件不成立")
|
||
db.flush()
|
||
rows = db.execute(select(models.OutboundMessage).where(
|
||
models.OutboundMessage.work == work.id,
|
||
models.OutboundMessage.integration == "chk-cancel")).scalars().all()
|
||
check("D5 挂载上的条件不成立 → 一条都不发,也不留死信", not rows,
|
||
[(row.integration, row.status) for row in rows])
|
||
|
||
# 别的表单的模板不发(流程那一格不能越过模板自己的绑定表单)
|
||
pid = make_flow(db, "form", terminate_config={"writeback": {
|
||
"trigger": "terminate", "integrations": ["chk-other-form"]}})
|
||
work = make_work(db, pid, "form")
|
||
|
||
engine.terminate(db, job=work.job, actor=actor_of(STARTER), opinion="别家的单")
|
||
db.flush()
|
||
rows = db.execute(select(models.OutboundMessage).where(
|
||
models.OutboundMessage.work == work.id,
|
||
models.OutboundMessage.integration == "chk-other-form")).scalars().all()
|
||
check("D6 模板绑的是另一张表单 → 这条流程终止时不发它", not rows,
|
||
[(row.integration, row.status) for row in rows])
|
||
|
||
# 办结那一刻不受影响
|
||
db2 = new_session()
|
||
seed_source(db2, "chk-src")
|
||
seed_template(db2, "chk-cancel", source="chk-src")
|
||
pid = make_flow(db2, "done", terminate_config={"writeback": {
|
||
"trigger": "terminate", "integrations": ["chk-cancel"]}})
|
||
work = make_work(db2, pid, "done")
|
||
definition = definition_module.for_work(db2, work)
|
||
engine._finish_work(db2, work, definition, status="completed", result=engine.StepResult(),
|
||
actor=actor_of(HOLDER), opinion="批完了",
|
||
activity=definition.activity(f"{pid}-end"))
|
||
db2.flush()
|
||
rows = db2.execute(select(models.OutboundMessage).where(
|
||
models.OutboundMessage.work == work.id)).scalars().all()
|
||
check("D7 办结那一刻不会误发终止那一格的报文", not rows,
|
||
[(row.integration, row.event) for row in rows])
|
||
|
||
# 停用的模板不发:设计器那一格当场承诺了「已停用,终止那一刻不会发出去」,
|
||
# 运行期必须真如此——界面说一套、库里做一套是这一片最贵的那类病
|
||
db3 = new_session()
|
||
seed_source(db3, "chk-src")
|
||
seed_template(db3, "chk-off", source="chk-src")
|
||
db3.get(models.Integration, "it-chk-off").enabled = False
|
||
db3.flush()
|
||
pid = make_flow(db3, "off", terminate_config={"writeback": {
|
||
"trigger": "terminate", "integrations": ["chk-off"]}})
|
||
work = make_work(db3, pid, "off")
|
||
engine.terminate(db3, job=work.job, actor=actor_of(STARTER), opinion="模板停了")
|
||
db3.flush()
|
||
rows = db3.execute(select(models.OutboundMessage).where(
|
||
models.OutboundMessage.work == work.id)).scalars().all()
|
||
check("D8 模板被停用 → 终止那一刻一条都不发(与界面那句承诺一致)", not rows,
|
||
[(row.integration, row.status) for row in rows])
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# F 配了之后看得见:合并清单与全库体检都要得到流程那一格
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
def check_visibility() -> None:
|
||
"""流程那一格是第三处绑定点:保存那道闸、合并清单、回头扫,三处都缺它不可。
|
||
|
||
前四处判据(``enqueue_terminate`` 少不发、``mount_code_problems`` 报不报)只管得到"当下这一次",
|
||
而模板是**保存之后**才被删掉、被停用的。这一片的病绝大多数躺在"上一次保存时还是好的"
|
||
那些行里,所以 firing 那份合并清单与全库体检都得认这一格,否则界面照样骗人。
|
||
"""
|
||
db = new_session()
|
||
seed_source(db, "chk-src")
|
||
seed_template(db, "chk-cancel", source="chk-src") # 启用、绑本流程默认表单:没病
|
||
seed_template(db, "chk-off", source="chk-src") # 停用
|
||
seed_template(db, "chk-other-form", source="chk-src", form="f-somebody-else") # 绑别家表单
|
||
db.get(models.Integration, "it-chk-off").enabled = False
|
||
db.flush()
|
||
pid = make_flow(db, "vis", terminate_config={"writeback": {
|
||
"trigger": "terminate",
|
||
"integrations": ["chk-cancel", "chk-off", "chk-other-form", "chk-gone"]}})
|
||
mount = terminate_service.writeback_mount(
|
||
db.get(models.Process, pid).terminate_config or {})
|
||
|
||
joined = ";".join(mapping.mount_code_problems(db, mount, form="f-shared"))
|
||
check("F1 三种病各点名一次:模板被删 / 被停用 / 绑的是另一张表单",
|
||
len([x for x in ["chk-gone", "chk-off", "chk-other-form"] if x in joined]) == 3, joined)
|
||
check("F2 没病的那一条不报(启用 + 绑本流程默认表单,别把好人也揪出来)",
|
||
"chk-cancel" not in joined, joined)
|
||
check("F3 不传 form 时不判「绑错表单」这一条(新建流程那一刻还没有表单)",
|
||
"chk-other-form" not in ";".join(mapping.mount_code_problems(db, mount)), joined)
|
||
|
||
report = integrations_api.audit(db)
|
||
hit = [item for item in report if item["kind"] == "terminate" and item["process"] == pid]
|
||
check("F4 全库体检扫得到流程那一格(保存之后才删的模板,保存那道闸管不到)",
|
||
bool(hit) and len(hit[0]["problems"]) == 3,
|
||
[dict(item) for item in report])
|
||
check("F5 这一类也带着能跳转的目标(报一条没法处理的病等于没报)",
|
||
bool(hit) and bool(hit[0]["process"]) and bool(hit[0]["name"]), hit)
|
||
|
||
body = integrations_api.template_firing("chk-cancel", db, None)["data"]
|
||
checks = [item for item in (body.get("terminateMounts") or []) if item["process"] == pid]
|
||
check("F6 「什么时候真的会发」合并清单带上流程那一格(从前只合终态 + 环节挂载两处)",
|
||
len(checks) == 1 and "终止" in checks[0]["label"], body.get("terminateMounts"))
|
||
db.add(models.Integration(
|
||
id="it-chk-quiet", code="chk-quiet", name="没被挂上的模板", enabled=True, source="chk-src",
|
||
biz_form="f-shared", trigger_events=[], trigger_event="manual", payload={},
|
||
))
|
||
db.flush()
|
||
body = integrations_api.template_firing("chk-quiet", db, None)["data"]
|
||
check("F7 没被任何一格点名的模板,合并清单里不该凭空多出终止那一格",
|
||
not (body.get("terminateMounts") or []), body.get("terminateMounts"))
|
||
|
||
|
||
def check_reversal() -> None:
|
||
"""终止仍旧自动冲销已发出去的凭证(这条是原有能力,一起钉住别在改动中丢了)。"""
|
||
db = new_session()
|
||
seed_source(db, "chk-src")
|
||
seed_template(db, "chk-voucher", source="chk-src")
|
||
|
||
seed_template(db, "chk-reverse", source="chk-src")
|
||
pid = make_flow(db, "rev", terminate_config={
|
||
"writeback": {"trigger": "terminate", "integrations": ["chk-voucher"]}})
|
||
work = make_work(db, pid, "rev")
|
||
voucher = db.execute(select(models.Integration).where(
|
||
models.Integration.code == "chk-voucher")).scalar_one()
|
||
voucher.reversal_code = "chk-reverse"
|
||
db.flush()
|
||
sent = models.OutboundMessage(
|
||
id="ob-sent", source="chk-src", integration="chk-voucher",
|
||
event=models.Integration.EVENT_ACTIVITY, event_key=f"{pid}-dept", work=work.id,
|
||
job=work.job, serial=work.serial, title=work.title, revision=1, idem="k-sent",
|
||
status=models.OutboundMessage.STATUS_SUCCESS, method="POST",
|
||
url="https://example.invalid/api", payload={"a": 1},
|
||
)
|
||
|
||
db.add(sent)
|
||
db.flush()
|
||
engine.terminate(db, job=work.job, actor=actor_of(STARTER), opinion="单办错了")
|
||
db.flush()
|
||
rows = db.execute(select(models.OutboundMessage).where(
|
||
models.OutboundMessage.work == work.id)).scalars().all()
|
||
reversal = [row for row in rows if row.cancels == sent.id]
|
||
check("E1 配了冲销模板时,终止把已经发出去的凭证自动反向冲一条",
|
||
bool(reversal) and reversal[0].integration == "chk-reverse",
|
||
[(row.integration, row.cancels) for row in rows])
|
||
check("E2 原报文标成「已被冲销」,集成页不再置顶喊人",
|
||
db.get(models.OutboundMessage, sent.id).status == models.OutboundMessage.STATUS_REVERSED,
|
||
db.get(models.OutboundMessage, sent.id).status)
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# G 列表接口那一列:关掉之后按钮根本不该出现
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
def check_api_surface() -> None:
|
||
"""「我发起的」列表上那颗钮读的是 ``terminate_allowed``:结构判据,一页一条 SQL。
|
||
|
||
窗口类判据(过没过某一环、超过多少小时)故意不在列表里算——那要每行现查一次到过的环节,
|
||
为了一颗按钮不值当;那些留给详情页与引擎。这里钉的就是这条分界:列表只认开关,
|
||
开关关掉时**每一张**该流程的单子都得拿到 False(少一张就会多摆一颗点了才被挡的钮)。
|
||
"""
|
||
db = new_session()
|
||
on = make_flow(db, "api-on")
|
||
off = make_flow(db, "api-off", terminate_config={"allowStarter": False})
|
||
odd = make_flow(db, "api-odd", terminate_config={"allowStarter": "yes"})
|
||
rows = [make_work(db, on, "api-on"), make_work(db, off, "api-off"), make_work(db, odd, "api-odd")]
|
||
flags = runtime_api._starter_terminate_flags(db, rows)
|
||
check("G1 列表那一列:关掉的那条流程每单都是 False,没关与写歪的都是 True",
|
||
flags.get(on) is True and flags.get(off) is False and flags.get(odd) is True, flags)
|
||
check("G2 空清单不去问库(一页没有一张单就不该有一条 SQL)",
|
||
runtime_api._starter_terminate_flags(db, []) == {})
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# H 引擎替父单收尾的级联不受这一格约束
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
def check_cascade() -> None:
|
||
"""父单走了,子单必须跟着走:这一格拦不住级联,也不该拦。
|
||
|
||
父单归档时带走在跑的嵌入子流程、撤回时收回自动流转出去的那几张子单,两处都是
|
||
``except EngineError`` 只记日志的——真被这一格挡下,症状不是报错而是**留下一张孤儿单**:
|
||
父单已归档、子单还挂着待办,谁都不知道还要不要办。那是这次改动凭空加给撤回与父子流程的
|
||
一条回归,所以钉在这里。
|
||
"""
|
||
db = new_session()
|
||
parent_flow = make_flow(db, "casc-p")
|
||
child_flow = make_flow(db, "casc-c", terminate_config={"allowStarter": False})
|
||
parent = make_work(db, parent_flow, "casc-p")
|
||
child = make_work(db, child_flow, "casc-c")
|
||
child.parent_job = parent.job
|
||
db.flush()
|
||
|
||
# 先证明这一格在子单那条流程上真的生效:同一张单由发起人自己按终止是按不动的
|
||
definition = definition_module.for_work(db, child)
|
||
check("H1 子单那条流程确实关掉了发起人终止(不然 H2 就是白测)",
|
||
"关掉" in engine.terminate_blocker(db, child, definition, actor_of(STARTER)))
|
||
engine.terminate(db, job=parent.job, actor=actor_of(STARTER), opinion="父单不要了")
|
||
db.flush()
|
||
row = db.execute(select(models.WorkCompleted).where(
|
||
models.WorkCompleted.job == child.job)).scalar_one_or_none()
|
||
check("H2 父单一终止,子单跟着归档(这一格拦级联就会留一张孤儿待办)",
|
||
row is not None and row.status == "terminated",
|
||
None if row is None else (row.job, row.status))
|
||
ghosts = db.execute(select(models.Task).where(models.Task.work == child.id)).scalars().all()
|
||
check("H3 子单身上不留没人收的待办", not ghosts, [item.identity_name for item in ghosts])
|
||
|
||
|
||
def main() -> int:
|
||
check_config_read()
|
||
check_definition_round_trip()
|
||
check_engine_guard()
|
||
check_trail()
|
||
check_terminate_writeback()
|
||
check_reversal()
|
||
check_visibility()
|
||
check_api_surface()
|
||
check_cascade()
|
||
print(f"\n共 {PASSED + len(FAILS)} 项:通过 {PASSED},失败 {len(FAILS)}")
|
||
if FAILS:
|
||
print("失败清单:")
|
||
for item in FAILS:
|
||
print(f" - {item}")
|
||
return 1
|
||
return 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
raise SystemExit(main())
|