unis-oa/backend/scripts/check_cc_action_files.py

362 lines
23 KiB
Python
Raw 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
"""守"归档件也能说话"这一整条路:处理意见带图片/文件 + 办结之后的单子能补批注。
改造前这两件事都缺一块。``POST /read/{id}/handle`` 的请求体只有 ``opinion`` 一段文本,
``oa_read`` / ``oa_read_completed`` 也没有随附附件的落脚处;批注入口只开在待办页
(``TaskDetailView`` 的 ``canComment`` 要求 ``canProcess``),而一张**已经办结**的单子
永远不会有待办——于是"办结后抄送给某人、勾了需处理"的那个人,手上既没有待办、
打开单据页也只能看,一句带截图的补充都留不下。引擎侧 ``add_comment`` 其实认归档件
(``subject = work or db.get(WorkCompleted, ...)``),是接口与界面没把这条路递到人手上。
**这条门不往库里留东西**:全程跑在一个存档点(``begin_nested``)里,收尾整体回滚;
待阅、批注、通知、附件行都是就地造的(附件行 ``storage`` 留空,一个字节都不进 MinIO),
一条真单据都不发起——跑完再数一遍探针留下的名字,必须一条不剩。最后那几条断言
就是在钉这件事:校验本身不许变成测试数据的来源。
钉住的行为:
1. **处理意见带附件**:需处理那条待阅,本人带意见 + 附件处理确认,附件跟着这条记录
进已阅;随附的附件行 ``type=read``、``business_id`` 认到这条已阅记录,并按在途 /
归档两种情况回填 ``work`` / ``job`` / ``process`` / ``completed`` / ``work_completed``。
2. **普通登记不收附件**:不要求处理的那条待阅只是"我看过了",带附件必须被挡——
否则附件挂在一个连意见栏都没有的记录上,事后没人看得出它是谁、为什么传的。
3. **只能附本人上传的文件**:``claim_attachments`` 那条硬规则在归档件上照样管用。
4. **归档件上能补批注**:被抄送人照样能发批注、能带图、能 @ 人;批注行与附件行都
标成已归档,归属认到 ``oa_work_completed`` 那一张单上。
5. **"这一单与他有关"算得准**:``_received_reads`` 认待阅也认已阅,无关的人为假。
6. **环节那一格「允许批注」在归档件上照样管用**:``_comment_blocker`` 三档
(认不出环节 / 开关缺省 / 开关关掉),``comment_activity`` 认的是这一单
**自己落脚那一环**,不是流程当前设计;在途与归档同一条判据。
7. **接口与界面真的把这条路递到人手上**:请求体认 ``attachments``(含驼峰写法)、
``handle`` 那两条路由真把附件交给引擎、单据详情报得出 ``can_comment``、
待阅弹窗与单据详情页真的挂了能传图的编辑器。前后端各写一半、对不上的口径最容易漂。
跑在 backend 目录下::
PYTHONPATH=. python3 scripts/check_cc_action_files.py
"""
from __future__ import annotations
import inspect
import pathlib
import sys
from datetime import datetime
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent))
from sqlalchemy import func, select # noqa: E402
from app import models, schemas # noqa: E402
from app.api import runtime as runtime_module # noqa: E402
from app.db import SessionLocal # noqa: E402
from app.engine import definition as definition_module # noqa: E402
from app.engine import engine as engine_module # noqa: E402
REPO = pathlib.Path(__file__).resolve().parent.parent.parent
#: 只认得出来的探针名字:收尾按这些前缀数一遍,证明这条门自己不留数据
PROBE = f"零残留门-{datetime.now():%m%d%H%M%S}"
PROBE_IDENTITY = f"probe_{datetime.now():%m%d%H%M%S}_reader"
STRANGER_IDENTITY = f"probe_{datetime.now():%m%d%H%M%S}_stranger"
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
def _actor(user: models.User | None, *, ref: str = "", is_admin: bool = False) -> engine_module.Actor:
"""就地搭一个办事的人。人是库里真有的(只读),但这一趟不落任何一行关于他的账。"""
return engine_module.Actor(
person_id=str(user.id) if user is not None else "probe-person",
person_name=(user.display_name if user is not None else "校验的人"),
ref=ref or (user.account if user is not None else "probe"),
unit="",
unit_name="",
is_admin=is_admin,
)
def _attachment(db, *, owner: str, name: str) -> str:
"""造一条"前端已经传好、还没人认领"的附件行。
``storage`` 故意留空:这条门只验归属与快照,不搬字节,一个对象都不必进 MinIO。
"""
row = models.Attachment(name=name, extension=".png", storage="", length=8,
type="attachment", person=owner)
db.add(row)
db.flush()
return row.id
def _reads_of(db, work_id: str, identity: str) -> list[models.Read]:
return list(db.execute(
select(models.Read).where(models.Read.work == work_id, models.Read.identity == identity)
).scalars().all())
def main() -> int: # noqa: C901 - 一条直线跑完六组断言,拆开反而要把状态传来传去
db = SessionLocal()
# 驱动用的单据从库里现成的拿,只读不改:归档件一张、在途件一张,缺一样就少验一半
archived = db.execute(
select(models.WorkCompleted).order_by(models.WorkCompleted.finish_time.desc()).limit(1)
).scalars().first()
live = db.execute(select(models.Work).order_by(models.Work.id.desc()).limit(1)).scalars().first()
if archived is None and live is None:
print("[跳过] 库里一张单据都没有,这一项校不了")
db.close()
return 0
# 发批注的人与被 @ 的人必须是两个真人:``create_reads`` 对批注这一类会跳过发件人
# 自己(自己 @ 自己不算一条待阅),拿同一个人当两边,那条断言测的就不是"提醒到了谁"
people = db.execute(
select(models.User).where(models.User.status == models.UserStatus.ACTIVE).order_by(models.User.id).limit(2)
).scalars().all()
mention = people[1] if len(people) > 1 else None
actor = _actor(people[0] if people else None)
# 处理待阅的是"收件人"本人:待阅只认得了他的登录账号(``get_read`` 那条归属校验),
# 这里借同一个真人当壳、把 ref 换成探针身份,既过归属校验又不碰任何人的账。
reader = _actor(people[0] if people else None, ref=PROBE_IDENTITY)
def tally() -> dict[str, int]:
"""这几张表的行数:跑之前跑之后各数一次,两次必须一样。
只数行数的合计,不数某一张单——这条门不发起单据,任何一张表多出来的行
都是它自己弄脏的。
"""
return {
"oa_work": db.execute(select(func.count(models.Work.id))).scalar(),
"oa_work_completed": db.execute(select(func.count(models.WorkCompleted.id))).scalar(),
"oa_read": db.execute(select(func.count(models.Read.id))).scalar(),
"oa_read_completed": db.execute(select(func.count(models.ReadCompleted.id))).scalar(),
"oa_work_comment": db.execute(select(func.count(models.WorkComment.id))).scalar(),
"oa_attachment": db.execute(select(func.count(models.Attachment.id))).scalar(),
"oa_notification": db.execute(select(func.count(models.Notification.id))).scalar(),
}
before = tally()
savepoint = db.begin_nested()
failed_here = False
try:
# --------- 1) 归档件:处理意见带附件 + 批注带附件 ---------
if archived is not None:
created = engine_module.create_reads(
db, archived, actor=actor, identities=[PROBE_IDENTITY], kind="cc",
requires_action=True, opinion="办结了,补一句处理意见")
read = next((row for row in created if row.identity == PROBE_IDENTITY), None)
failed_here |= not check("归档件上建得出「需处理」那条待阅",
read is not None and bool(read.requires_action)
and read.completed is True
and read.work_completed == archived.id,
"" if read is None else
f"requires_action={read.requires_action} completed={read.completed}")
check("归档件上这条待阅一开始还没有随附附件",
read is not None and list(read.attachments or []) == [],
repr(getattr(read, "attachments", None)))
png = _attachment(db, owner=reader.person_id, name=f"{PROBE}-处理意见.png")
try:
engine_module.mark_read(db, read_id=read.id, actor=reader, opinion="看过了",
handling=False, attachments=[png])
check("不要求处理的登记不许挂附件", False, "引擎没挡:附件挂到了一条没有意见栏的记录上")
except engine_module.EngineError as exc:
# 附件只跟着「处理」那一趟走:那句意见可以留空,这一颗钮不能少按
check("不要求处理的登记带附件被挡住,并说清为什么",
"「处理」" in str(exc), str(exc))
done = engine_module.mark_read(
db, read_id=read.id, actor=reader, opinion="发票已重开,见附件",
handling=True, attachments=[png])
check("处理意见带附件提交成功,这条办完了(界面上归已办)",
done.handle_time is not None and bool(done.opinion), repr(done.opinion)[:120])
check("附件跟着这条记录进已阅(引用快照含名字与图片标记)",
[str(item.get("id")) for item in (done.attachments or [])] == [png],
repr(done.attachments)[:160])
row = db.get(models.Attachment, png)
check("归档件上的随附附件认到这条已阅记录与这一单,并直接标成已归档(type=read)",
row is not None and row.type == models.Attachment.KIND_READ
and row.business_id == done.id and row.work == archived.id
and row.job == archived.job and row.process == archived.process
and row.completed is True and row.work_completed == archived.id,
"" if row is None else f"type={row.type} business={row.business_id} work={row.work} "
f"job={row.job} process={row.process} completed={row.completed} "
f"work_completed={row.work_completed}")
check("处理过的这条已阅报得出附件(已阅列表要靠它显示)",
"attachments" in runtime_module.serializers.read_row(done),
sorted(runtime_module.serializers.read_row(done))[:60])
comment = engine_module.add_comment(
db, work_id=archived.id, actor=actor, content="归档之后再补一句:发票已重开",
mentions=[mention.account] if mention is not None else [],
mention_action=True, attachments=[])
check("归档件上发一条纯文字批注成功,且这条批注知道自己挂在归档件上",
comment.completed is True and comment.work_completed == archived.id
and str(comment.work) == archived.id,
f"completed={comment.completed} work_completed={comment.work_completed}")
png2 = _attachment(db, owner=actor.person_id, name=f"{PROBE}-批注.png")
second = engine_module.add_comment(
db, work_id=archived.id, actor=actor, content="贴图说明", mentions=[],
mention_action=False, attachments=[png2])
att2 = db.get(models.Attachment, png2)
check("归档件上的批注附件回填了这一单的归属并标成已归档",
[str(item.get("id")) for item in (second.attachments or [])] == [png2]
and att2 is not None and att2.work == archived.id
and att2.completed is True and att2.work_completed == archived.id
and att2.type == models.Attachment.KIND_COMMENT,
"" if att2 is None else f"type={att2.type} work={att2.work} completed={att2.completed}")
reminded = [item for item in _reads_of(db, archived.id, mention.account)
if item.read_type == "comment"] if mention is not None else []
check("在归档件上 @ 人照样生成待阅,且要求处理、认得自己是挂在归档件上的",
mention is not None and bool(reminded)
and all(item.requires_action and item.completed for item in reminded),
f"{len(reminded)} 条 / 被 @ 的人 {'有' if mention is not None else '没有'}")
other = _attachment(db, owner="probe-someone-else", name=f"{PROBE}-别人的.png")
try:
engine_module.add_comment(db, work_id=archived.id, actor=actor, content="想拿别人的文件顶上",
mentions=[], mention_action=False, attachments=[other])
check("只能附上本人上传的文件——归档件上这条硬规则不失效", False,
"引擎没挡:把别人传的文件认领到了自己的批注上")
except engine_module.EngineError as exc:
check("只能附上本人上传的文件——归档件上这条硬规则不失效", "本人上传" in str(exc), str(exc))
check("被抄送人算得出「这一单与他有关」",
runtime_module._received_reads(db, archived.id, PROBE_IDENTITY) is True, "为假")
check("没在这张单上收过待阅的人算不出「与他有关」",
runtime_module._received_reads(db, archived.id, STRANGER_IDENTITY) is False, "为真")
# --------- 6) 环节那一格「允许批注」:在途与归档同一条判据 ---------
node_on = definition_module.ActivityNode(id="probe1", type="manual", name="校验环节甲",
config={"allowComment": True})
node_off = definition_module.ActivityNode(id="probe2", type="manual", name="校验环节乙",
config={"allowComment": False})
check("开关缺省时放行(老设计没有这一格,不能凭空关掉批注)",
engine_module._comment_blocker(None) == "", repr(engine_module._comment_blocker(None)))
check("开关开着时放行", engine_module._comment_blocker(node_on) == "",
repr(engine_module._comment_blocker(node_on)))
check("开关关掉时报的是环节名那句原话",
engine_module._comment_blocker(node_off) == "环节 校验环节乙 不允许批注",
repr(engine_module._comment_blocker(node_off)))
resolved = engine_module.comment_activity(db, archived)
check("归档件没有「当前环节」这一格可判:认不出环节就是默认放行,不是漏判",
not hasattr(archived, "activity") and resolved is None
and engine_module.comment_blocker(db, archived) == "",
f"resolved={resolved!r} blocker={engine_module.comment_blocker(db, archived)!r}")
check("在途与归档走同一条判据(都从 comment_activity 出)",
engine_module.comment_blocker(db, archived)
== engine_module._comment_blocker(resolved),
repr(engine_module.comment_blocker(db, archived)))
if live is not None:
live_node = engine_module.comment_activity(db, live)
check("在途件认的是它当前压着的那一环,开关关掉就挡得住",
live_node is None
or engine_module.comment_blocker(db, live)
== engine_module._comment_blocker(live_node),
repr(engine_module.comment_blocker(db, live)))
else:
print("[提示] 库里没有已归档的单据,归档件那几条本轮没校到")
# --------- 2) 在途件:同一条处理链,归属落在 oa_work 那一张单上 ---------
if live is not None:
created = engine_module.create_reads(
db, live, actor=actor, identities=[PROBE_IDENTITY], kind="cc",
requires_action=True, opinion="补一句处理意见")
read = next((row for row in created if row.identity == PROBE_IDENTITY), None)
if check("在途件上也建得出那条待阅", read is not None and read.completed is False,
"" if read is None else f"completed={read.completed}"):
png = _attachment(db, owner=reader.person_id, name=f"{PROBE}-在途处理.png")
done = engine_module.mark_read(
db, read_id=read.id, actor=reader, opinion="已核对,见附件",
handling=True, attachments=[png])
row = db.get(models.Attachment, png)
check("在途件上的随附附件认到这条已阅记录与这一单,且不冒充已归档",
[str(item.get("id")) for item in (done.attachments or [])] == [png]
and row is not None and row.work == live.id and row.job == live.job
and row.process == live.process
and row.completed is False and row.work_completed == "",
"" if row is None else f"work={row.work} completed={row.completed} "
f"work_completed={row.work_completed}")
else:
print("[提示] 库里没有在途单据,在途那一半本轮没校到")
# --------- 7) 接口与界面真的把这条路递到人手上(前后端口径对账) ---------
body = schemas.ReadViewBody.model_validate({"opinion": "x", "attachments": ["a1", "a2"]})
check("处理意见的请求体认 attachments(驼峰写法同一条路)",
body.attachments == ["a1", "a2"], repr(body.attachments))
handle_src = inspect.getsource(runtime_module.handle_read)
view_src = inspect.getsource(runtime_module.view_read)
check("处理确认那条路由真把附件交给引擎", "attachments=body.attachments" in handle_src,
handle_src.strip()[:160])
check("登记已阅那条路由也认这一栏(挂错了才会被引擎挡下来)",
"attachments=body.attachments" in view_src, view_src.strip()[:160])
job_src = inspect.getsource(runtime_module._job_response)
check("单据详情报文里报得出 can_comment(界面开不开批注框就认这一格)",
'"can_comment"' in job_src and "_received_reads(" in job_src,
"没在 _job_response 里找到 can_comment")
read_view = (REPO / "frontend/src/views/oa/ReadListView.vue").read_text(encoding="utf-8")
work_view = (REPO / "frontend/src/views/oa/WorkDetailView.vue").read_text(encoding="utf-8")
mobile_work = (REPO / "frontend/src/components/oa/mobile/MobileWorkView.vue").read_text(encoding="utf-8")
flow = (REPO / "frontend/src/components/oa/mobile/MobileFlow.vue").read_text(encoding="utf-8")
record = (REPO / "frontend/src/components/oa/ApprovalRecord.vue").read_text(encoding="utf-8")
# 写处理意见那一步的入口从待阅搬进了统一待办(2026-11):需处理的抄送就在待办里
# 办,已阅那一页只剩回看。判据跟着换到 TodoListView,控件与口径还是同一只。
todo_view = (REPO / "frontend/src/views/oa/TodoListView.vue").read_text(encoding="utf-8")
check("统一待办那个「填写处理意见」的弹窗换成了能贴图能传文件的编辑器",
'purpose="read"' in todo_view and "OpinionComposer" in todo_view
and "handleRead(row.id, opinion, files)" in todo_view,
"TodoListView 里没找到带附件的处理弹窗")
check("待阅列表里看得见这条记录随附的图片与文件",
"row.attachments" in read_view and "AttachmentGallery" in read_view,
"ReadListView 没有渲染 attachments")
check("单据详情页把批注框开出来了(桌面与手机都算,判据来自 can_comment)",
':can-comment="canComment"' in work_view and "detail.value?.can_comment" in work_view
and ':can-comment="canComment"' in mobile_work
and 'v-if="canComment"' in flow,
"WorkDetailView / MobileWorkView 的批注入口没接上")
# 整条链一次钉住:父页发完批注要清草稿 → 桌面那份真把 reset 交出来 →
# 手机整页往下转给 MobileFlow → MobileFlow 那句 defineExpose 落在 script 块里
# (掉到块外面等于没写,父页拿到的是 undefined,草稿就一直赖在面板里)
check("批注发出去之后草稿收得干净(桌面与手机共用一条收尾)",
"recordPanel.value?.reset?.()" in work_view
and "defineExpose({ reset, open" in record.split("</script>")[0]
and "defineExpose({ reset: () => flowPanel.value?.reset() })" in mobile_work.split("</script>")[0]
and "defineExpose({ reset: resetComposer })" in flow.split("</script>")[0],
"reset 这条链断了:父页调不到,或某一环的 defineExpose 掉在 script 块外面")
finally:
savepoint.rollback()
# --------- 收尾:这条门自己不许成为测试数据的来源 ---------
db.rollback()
after = tally()
probes = {
"attachment": db.execute(select(models.Attachment.id).where(
models.Attachment.name.like(f"{PROBE}-%"))).scalars().all(),
"read": db.execute(select(models.Read.id).where(
models.Read.identity.in_([PROBE_IDENTITY, STRANGER_IDENTITY]))).scalars().all(),
"read_completed": db.execute(select(models.ReadCompleted.id).where(
models.ReadCompleted.identity.in_([PROBE_IDENTITY, STRANGER_IDENTITY]))).scalars().all(),
}
check("跑完一条不剩:待阅 / 已阅 / 批注 / 附件 / 通知 / 单据的行数与跑之前一字不差",
before == after, f"跑前 {before} / 跑后 {after}")
check("探针名字与探针身份在库里都查不到了",
all(len(rows) == 0 for rows in probes.values()),
{key: len(rows) for key, rows in probes.items()})
print(f"\n合计 {PASSED + len(FAILS)} 项:通过 {PASSED} / 失败 {len(FAILS)}")
db.close()
return 1 if FAILS else 0
if __name__ == "__main__":
raise SystemExit(main())