unis-oa/backend/scripts/check_cc_entries_to_read.py

424 lines
24 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
"""守「抄送一律先进待阅」:六个入口 + 三档口径,逐条钉住,库里不留东西。
用户口径(2026-11 提的):抄送的消息都应该在待阅里;要操作的那条操作完才转已阅;
不要操作的那条点开就算已阅。翻成代码是三句话:
1. **六个入口只有一个出口**:环节到达 / 办完 / 办结三档自动抄送、审批人手工抄送、
分享、批注 @ ——全部经 :func:`engine.create_reads` 落 ``oa_read``。一条都不许直接
落 ``oa_read_completed``,也不许只发一句站内信就把人打发了(站内信是按「这一单上
还有没有我的待阅」收尾的,见 :mod:`app.service.notify_settle`;待阅没落地,提醒也挂不住)。
2. **办结那一档也留在待阅里**:单据归档那一刻现抄的抄送,与归档前没被人打开过的老待阅,
都只是补上 ``completed`` / ``work_completed`` 两个归档标记,行照旧停在 ``oa_read``。
``oa_read_completed.view_time`` 是 NOT NULL,搬进已阅档等于替人编一个「已阅时间」,
档案里从此分不出「看过」与「没打开」,勾了需处理的还会被悄悄勾掉。
3. **需处理不被「点开」顶掉**:``requires_action`` 的那几条,打开单据页(``POST /read/view``)
与单条标记已阅(``POST /read/{id}/view``)都不许把它登记掉,只有 ``POST /read/{id}/handle``
那一颗「处理」才办得掉(随附的那句处理意见**可留空**,2026-11 改的);不要求处理的那几条
点开即转。办完与看过都落在 ``oa_read_completed``,界面上分家:需处理算**已办**、
不需处理算**已阅**(读法见 :mod:`app.service.completed`,判据 ``check_done_cc_split.py``)。
顺带钉一条反向的:**加签与转办不产生待阅**——那两条给的是待办,往 ``oa_read`` 里
塞一条会让人在待阅里看到一条根本没有的抄送,往已阅里塞更糟(凭空多一次表态)。
自动抄送的规则挂在环节设计里,测试不往别人已有的流程上挂规则:这里临时把
:func:`engine.cc_rules` 换成探针(只认 ``when``,抄给谁写死),跑完照旧换回去。
单据是真发的,收尾按 job 与标题清干净(复用 ``check_write_payload.purge``)。
库里没有这条流程、或凑不出足够的真人账号时逐项报「跳过」,不硬闯。::
PYTHONPATH=. python3 scripts/check_cc_entries_to_read.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.engine import engine as engine_module # 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
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)
# ---------------------------------------------------------------- 自动抄送探针
#: 挂在探针上的那几条规则,按 ``when``(arrive / complete)分档;空着就是不打扰
PROBE: dict[str, dict] = {}
REAL_CC_RULES = engine_module.cc_rules
def probe(when: str, identities: list[str], *, action: bool = False, opinion: str = "") -> None:
"""把这一档自动抄送换成探针规则:抄给谁写死,不碰流程设计里那一条。"""
PROBE[when] = {
"when": when,
"taskValues": [{"type": "identity", "data": list(identities)}],
"taskScript": "",
"requiresAction": action,
"opinion": opinion,
}
def probe_cc_rules(activity, when: str) -> list[dict]:
"""探针认着的那一档回探针规则,其余照旧问真环节:没被探针管着的环节一律不受影响。"""
rule = PROBE.get(when)
return [rule] if rule else REAL_CC_RULES(activity, when)
# ---------------------------------------------------------------- 库里查账
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 read_of(db, work_id: str, identity: str, kind: str) -> models.Read | None:
"""按待阅类型取那一条(cc / share / comment 三个来源分开看,别互相顶包)。"""
rows = [row for row in reads_of(db, work_id, identity) if row.read_type == kind]
return rows[0] if rows else None
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 - 一条直线跑完六个入口,拆开反而要把 job / work 传来传去
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) < 5:
print(f"[跳过] 除发起人之外只凑出 {len(others)} 个真人账号,六个入口分不开")
db.close()
return 0
api = Api()
admin = api.token(starter)
# 一人一格:一个人、一张单、一类待阅只留一条(再抄是更新已有那条),六个入口若共用
# 一个人,后一条会把前一条盖掉,谁也证不了谁。批注与分享各自一张新单,才复用得上。
p_arrive, p_complete, p_finish, p_plain, p_action = others[:5]
p_comment, p_share = others[0], others[1]
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
engine_module.cc_rules = probe_cc_rules
try:
# ---------------- 1) 环节到达 / 办完 / 办结:三档自动抄送 ----------------
probe("arrive", [ref(p_arrive)])
job1, work1, created1 = start("三档自动抄送")
if check("三档自动抄送这一路拿得到单据", bool(work1), "发起没成功"):
row = read_of(db, work1, ref(p_arrive), "cc")
check("环节到达的自动抄送落在待阅里",
row is not None and row.requires_action is False,
f"待阅 {len(reads_of(db, work1, ref(p_arrive)))} 条")
check("到达那一档没有一落地就算已阅", not dones_of(db, work1, ref(p_arrive)))
PROBE.clear()
probe("complete", [ref(p_complete)])
probe("arrive", [ref(p_finish)])
tasks = open_tasks(created1)
status, done_payload, message = api.post(
f"/task/{tasks[0].get('id')}/execute", token=admin,
json={"route_name": first_route(tasks[0]), "opinion": "校验同意"})
if check("办完这一环推得动(往办结走)", status < 400, f"{status} {message}"):
check("环节办完的自动抄送落在待阅里",
read_of(db, work1, ref(p_complete), "cc") is not None,
f"待阅 {len(reads_of(db, work1, ref(p_complete)))} 条")
check("办完那一档没有一落地就算已阅", not dones_of(db, work1, ref(p_complete)))
archived = db.get(models.WorkCompleted, work1)
row = read_of(db, work1, ref(p_finish), "cc")
check("办结那一刻现抄的抄送落在待阅里",
row is not None and archived is not None,
f"归档 {archived is not None} / 待阅 {row is not None}")
check("办结那一档带着归档标记,且没有直接进已阅表",
row is not None and bool(row.completed) and row.work_completed == work1
and not dones_of(db, work1, ref(p_finish)),
"" if row is None else f"completed={row.completed} work_completed={row.work_completed}")
held = read_of(db, work1, ref(p_arrive), "cc")
check("归档前没打开过的老待阅也留在待阅里(只补归档标记,不替人编已阅时间)",
held is not None and bool(held.completed) and held.work_completed == work1
and not dones_of(db, work1, ref(p_arrive)),
"" if held is None else f"completed={held.completed} 已阅 {len(dones_of(db, work1, ref(p_arrive)))} 条")
# 归档件照样读得掉:本人点开单据,那条待阅才转已阅,归档标记跟着一起进档
status, data, message = api.post("/read/view", token=tokens[p_arrive.id],
json={"job": job1})
moved = dones_of(db, work1, ref(p_arrive))
check("归档件里的待阅:点开单据即登记已阅(不要求处理那一档)",
status < 400 and int((data or {}).get("count") or 0) == 1
and len(moved) == 1 and bool(moved[0].completed)
and moved[0].work_completed == work1
and not reads_of(db, work1, ref(p_arrive)),
f"{status} {message} count={(data or {}).get('count')} 已阅 {len(moved)} 条")
# ---------------- 2) 审批人手工抄送:两种口径 ----------------
PROBE.clear()
job2, work2, created2 = start("手工抄送")
tasks2 = open_tasks(created2)
if check("手工抄送这一路拿得到待办", bool(tasks2), "发起没给待办"):
task_id = str(tasks2[0].get("id") or "")
status, _, message = api.post(f"/task/{task_id}/cc", token=admin,
json={"identities": [ref(p_plain)], "opinion": "给你看一眼",
"requires_action": False})
check("抄送无需处理打得通", status < 400, f"{status} {message}")
status, _, message = api.post(f"/task/{task_id}/cc", token=admin,
json={"identities": [ref(p_action)], "opinion": "请你写句意见",
"requiresAction": True})
check("抄送需处理打得通(驼峰写法同样管用)", status < 400, f"{status} {message}")
plain = read_of(db, work2, ref(p_plain), "cc")
action = read_of(db, work2, ref(p_action), "cc")
check("两条手工抄送都落在待阅里,requires_action 各按各的",
plain is not None and action is not None
and plain.requires_action is False and action.requires_action is True,
f"无需处理 {plain is not None} / 需处理 {action is not None}")
check("两条都没被偷偷算成已阅",
not dones_of(db, work2, ref(p_plain)) and not dones_of(db, work2, ref(p_action)))
if check("需处理那条落在库里拿得到 id", action is not None, ""):
# c) 不要求处理的:打开单据页即转已阅
status, data, message = api.post("/read/view", token=tokens[p_plain.id],
json={"job": job2})
moved = dones_of(db, work2, ref(p_plain))
check("无需处理的抄送:打开单据页即转已阅",
status < 400 and int((data or {}).get("count") or 0) == 1
and len(moved) == 1 and not reads_of(db, work2, ref(p_plain)),
f"{status} {message} count={(data or {}).get('count')}")
# b) 要求处理的:打开单据页不算,标记已阅也挡,只有点「处理」才办得掉
status, data, message = api.post("/read/view", token=tokens[p_action.id],
json={"job": job2})
check("需处理的抄送:打开单据页不转已阅(还留在待阅里)",
status < 400 and int((data or {}).get("count") or 0) == 0
and read_of(db, work2, ref(p_action), "cc") is not None
and not dones_of(db, work2, ref(p_action)),
f"{status} {message} count={(data or {}).get('count')}")
status, _, message = api.post(f"/read/{action.id}/view", token=tokens[p_action.id],
json={"opinion": ""})
check("需处理的抄送:单条「标记已读」挡下来",
status >= 400 and "处理" in message, f"{status} {message}")
# 处理意见改成选填(2026-11 用户提的):那一句留空也办得掉,
# 要人亲自按的是「处理」这一颗钮,不是那几个字。
# id 先抄成字符串:办成功那一刻 oa_read 那行就没了,晚一步再碰 ORM 对象
# 是问库要一条已经不存在的记录(ObjectDeletedError)
action_id = str(action.id)
status, _, message = api.post(f"/read/{action_id}/handle", token=tokens[p_action.id],
json={"opinion": " "})
moved = dones_of(db, work2, ref(p_action))
check("需处理的抄送:空意见也处理得掉(空格子不算说过话,来意那句留着)",
status < 400 and len(moved) == 1
and read_of(db, work2, ref(p_action), "cc") is None
and bool(moved[0].requires_action) and moved[0].handle_time is not None
and moved[0].opinion == "请你写句意见",
f"{status} {message} 归档 {len(moved)} 条")
# 办完这一条界面上归**已办**、不进已阅;再抄一条走带意见那条路
status, body, message = api.get("/read/completed", token=tokens[p_action.id])
listed = {str(item.get("read") or "") for item in ((body or {}).get("items") or [])}
check("空意见办完的那条不在已阅里(已办另有一支判据:check_done_cc_split)",
status < 400 and action_id not in listed,
f"{status} {message} 已阅 {sorted(listed)}")
status, _, message = api.post(f"/task/{task_id}/cc", token=admin,
json={"identities": [ref(p_action)],
"opinion": "再请你写一句", "requires_action": True})
action2 = read_of(db, work2, ref(p_action), "cc")
check("办掉之后还能再抄一次需处理(新的一行落在待阅里)",
status < 400 and action2 is not None and bool(action2.requires_action)
and str(action2.id) != action_id,
f"{status} {message}")
if action2 is not None:
action2_id = str(action2.id)
status, data, message = api.post(f"/read/{action2_id}/handle",
token=tokens[p_action.id],
json={"opinion": "已核对,无问题"})
rows = {str(row.read): row for row in dones_of(db, work2, ref(p_action))}
check("需处理的抄送:填了处理意见照样办得掉,那句以本人写的为准",
status < 400 and action2_id in rows
and read_of(db, work2, ref(p_action), "cc") is None
and bool(rows[action2_id].requires_action)
and rows[action2_id].handle_time is not None
and rows[action2_id].opinion == "已核对,无问题",
f"{status} {message} 归档 {len(rows)} 条")
# ---------------- 3) 批注 @ ----------------
job3, work3, _ = start("批注@")
if check("批注这一路拿得到单据", bool(work3), "发起没成功"):
status, _, message = api.post(f"/work/{work3}/comments", token=admin,
json={"content": "@一下,请看这一格",
"mentions": [ref(p_comment)], "mention_action": True})
check("批注 @ 打得通", status < 400, f"{status} {message}")
row = read_of(db, work3, ref(p_comment), "comment")
check("批注 @ 落在待阅里,且跟着那格「需要处理」",
row is not None and bool(row.requires_action),
f"来源 {[r.read_type for r in reads_of(db, work3, ref(p_comment))]}")
check("批注 @ 没有一落地就算已阅", not dones_of(db, work3, ref(p_comment)))
if row is not None:
status, data, message = api.post("/read/view", token=tokens[p_comment.id],
json={"job": job3})
check("批注 @ 勾了需处理:打开单据页同样不转已阅",
int((data or {}).get("count") or 0) == 0
and read_of(db, work3, ref(p_comment), "comment") is not None,
f"count={(data or {}).get('count')}")
# ---------------- 4) 分享 ----------------
job4, work4, _ = start("分享")
if check("分享这一路拿得到单据", bool(work4), "发起没成功"):
status, _, message = api.post(f"/work/{work4}/share", token=admin,
json={"identities": [ref(p_share)], "opinion": "分享给你看看"})
check("分享打得通", status < 400, f"{status} {message}")
row = read_of(db, work4, ref(p_share), "share")
check("分享落在待阅里,且不要求对方处理",
row is not None and row.requires_action is False,
f"来源 {[r.read_type for r in reads_of(db, work4, ref(p_share))]}")
if row is not None:
status, data, message = api.post("/read/view", token=tokens[p_share.id],
json={"job": job4})
check("分享的待阅:打开单据页即转已阅",
int((data or {}).get("count") or 0) == 1
and len(dones_of(db, work4, ref(p_share))) == 1,
f"count={(data or {}).get('count')}")
# ---------------- 5) 反向:加签 / 转办不产生待阅 ----------------
job5, work5, created5 = start("加签转办")
tasks5 = open_tasks(created5)
if check("加签转办这一路拿得到待办", bool(tasks5), "发起没给待办"):
task_id = str(tasks5[0].get("id") or "")
status, _, message = api.post(f"/task/{task_id}/addtask", token=admin,
json={"identities": [ref(p_plain)], "way": "after",
"opinion": "加你一起看"})
check("加签打得通", status < 400, f"{status} {message}")
check("加签给的是待办,不往待阅 / 已阅里塞东西",
not reads_of(db, work5, ref(p_plain)) and not dones_of(db, work5, ref(p_plain)),
f"待阅 {len(reads_of(db, work5, ref(p_plain)))} 条")
status, _, message = api.post(f"/task/{task_id}/transfer", token=admin,
json={"identities": [ref(p_action)], "opinion": "转给你办"})
check("转办打得通", status < 400, f"{status} {message}")
check("转办不往待阅 / 已阅里塞东西",
not reads_of(db, work5, ref(p_action)) and not dones_of(db, work5, ref(p_action)),
f"待阅 {len(reads_of(db, work5, ref(p_action)))} 条")
finally:
engine_module.cc_rules = REAL_CC_RULES
PROBE.clear()
# 清场也放在收尾里:断言跑到一半抛异常时,那几张校验单与它们名下的待阅
# 不能留在库里当「测试数据的新来源」
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())