395 lines
23 KiB
Python
395 lines
23 KiB
Python
#!/usr/bin/env python3
|
||
"""守「统一待办」那一格的红点与四档口径(2026-11 改版)。
|
||
|
||
用户口径原话:抄送 / 转发**需处理**的都推进待办,每条待办都要有一枚红点说"还没看过",
|
||
读过红点就消失、但行还留在待办里,只有单条或批量**处理**之后才移进已办;抄送 / 转发
|
||
**不需处理**的也在待办里,已阅之后直接归进已阅,界面上不再有单独的「待阅」。
|
||
|
||
翻成代码是四句话,这一篇逐条钉(口径见 :mod:`app.service.inbox`)::
|
||
|
||
PYTHONPATH=. python3 scripts/check_inbox_read.py
|
||
|
||
1. **三类行并成一页,档位各归各的**:我自己的待办 = ``approval``;抄送/转发需处理 =
|
||
``cc_action``;抄送/转发只需阅 = ``cc_read``。三档各自筛得出来,加起来等于「全部」,
|
||
``total`` 与逐档那条 ``_key_part`` 用的是同一份条件——分页与页眉那句「共 N 条」不许各说一套。
|
||
2. **红点只说"看没看过"**:待办认 ``oa_task.view_time``,抄送认 ``oa_read.seen_time``,
|
||
两列在界面上是同一枚点。"看过"绝不把行推出待办:盖过章的那几条 ``unread=false`` 而
|
||
照旧在列表里;``unread`` 那一项计数(页眉「N 条未读」+ 那颗只看未读的钮)跟着一起降。
|
||
3. **只有"处理"才让它离开待办**:只需阅那几条一登记已阅就整行搬进 ``oa_read_completed``、
|
||
当场离开待办(这就是"界面上不需要待阅"那一句的落点);需处理那几条只有写了处理意见
|
||
的 ``mark_read(handling=True)`` 转得了,批量那一路没写意见时**一条都不许动**,
|
||
单独报一档 ``skipped``,不混进"办砸了",也不替人把该表的态表掉。
|
||
4. **一次勾选混着两档照样办得动**:``/task/inbox/seen`` 与 ``/task/inbox/execute`` 都按
|
||
档位分开走再并成一份账单;抄送行不许参与「共同出口」的计算(它压根没有出口)。
|
||
|
||
库里跑真流程再自己删干净(复用 ``check_write_payload.purge``)。没有可用流程 / 凑不出
|
||
真人账号时整篇报「跳过」并回 0,不硬闯。
|
||
"""
|
||
|
||
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
|
||
|
||
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 fresh(db):
|
||
"""换一次数据库快照再问。
|
||
|
||
本脚本这一份 Session 从开头就开着事务,MySQL 的 REPEATABLE READ 让它一直看见
|
||
第一次读那一瞬间的库——接口动的是另一个 Session,已提交的新行在这一份里根本不存在,
|
||
照着它下判据会把「已经搬进已阅」读成「一条都没有」。回滚一次就是换新快照。
|
||
"""
|
||
db.rollback()
|
||
return db
|
||
|
||
|
||
def inbox_of(api: Api, token: str, *, kind: str = "", viewed: str = "") -> dict:
|
||
"""统一待办的一页。返回报文 data(含 items / total)。"""
|
||
query = "&".join(part for part in (
|
||
f"kind={kind}" if kind else "",
|
||
f"viewed={viewed}" if viewed else "",
|
||
"page=1", "page_size=200",
|
||
) if part)
|
||
status, data, message = api.get(f"/task/inbox?{query}", token=token)
|
||
if status >= 400:
|
||
print(f" [取列表失败] {status} {message}")
|
||
return data or {"items": [], "total": 0}
|
||
|
||
|
||
def rows_for(data: dict, job: str) -> list[dict]:
|
||
"""只留这一张校验单上的行(库里别人压着的待办不参与判据)。"""
|
||
return [row for row in (data.get("items") or []) if str(row.get("job") or "") == job]
|
||
|
||
|
||
def kinds_of(rows: list[dict]) -> set[str]:
|
||
return {str(row.get("inbox_kind") or "") for row in rows}
|
||
|
||
|
||
def main() -> int: # noqa: C901 - 一条直线跑完这张校验单的一生,拆开反而到处传 job
|
||
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) < 3:
|
||
print(f"[跳过] 除发起人之外只凑出 {len(others)} 个真人账号,三档分不开")
|
||
db.close()
|
||
return 0
|
||
|
||
api = Api()
|
||
admin = api.token(starter)
|
||
p_action, p_plain, p_more = others[:3]
|
||
tokens = {row.id: api.token(row) for row in others}
|
||
ref = personref.ref_of
|
||
|
||
jobs: list[str] = []
|
||
titles: list[str] = []
|
||
|
||
def start(label: str) -> tuple[str, str, dict]:
|
||
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
|
||
|
||
try:
|
||
# ---------------- 1) 三类行并成一页 ----------------
|
||
job, work, created = start("三档并页")
|
||
if not check("发起拿得到待办", bool(created.get("tasks")), "发起没给待办"):
|
||
return 1
|
||
task_id = str((created.get("tasks") or [{}])[0].get("id") or "")
|
||
status, _, message = api.post(f"/task/{task_id}/cc", token=admin,
|
||
json={"identities": [ref(p_action)], "opinion": "请写一句意见",
|
||
"requires_action": True})
|
||
check("抄送需处理打得通", status < 400, f"{status} {message}")
|
||
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}")
|
||
|
||
mine = rows_for(inbox_of(api, admin), job)
|
||
check("我自己的待办在统一待办里,档位是 approval",
|
||
any(row.get("inbox_kind") == "approval" and str(row.get("id")) == task_id for row in mine),
|
||
str([(r.get("inbox_kind"), r.get("id")) for r in mine]))
|
||
check("待办那一行一上来带着红点(还没点开过)",
|
||
any(row.get("inbox_kind") == "approval" and row.get("unread") is True for row in mine),
|
||
str([(r.get("inbox_kind"), r.get("unread")) for r in mine]))
|
||
|
||
action_rows = rows_for(inbox_of(api, tokens[p_action.id]), job)
|
||
plain_rows = rows_for(inbox_of(api, tokens[p_plain.id]), job)
|
||
action_row = next((row for row in action_rows if row.get("inbox_kind") == "cc_action"), None)
|
||
check("抄送需处理落进取件箱,档位是 cc_action,且带着红点",
|
||
action_row is not None and action_row.get("unread") is True,
|
||
str([(r.get("inbox_kind"), r.get("unread")) for r in action_rows]))
|
||
check("抄送只需阅也在取件箱里,档位是 cc_read,且带着红点",
|
||
kinds_of(plain_rows) == {"cc_read"} and plain_rows[0].get("unread") is True,
|
||
str([(r.get("inbox_kind"), r.get("unread")) for r in plain_rows]))
|
||
check("需处理那一条把「要我动手」说在报文里(requires_action)",
|
||
action_row is not None and action_row.get("requires_action") is True, "")
|
||
|
||
# 分档计数与逐档列表同一个口径:三档加起来 = 全部,且每档筛出来只剩自己
|
||
counts_status, counts, _ = api.get("/task/processing/count", token=admin)
|
||
breakdown_ok = counts_status < 400 and counts
|
||
per_kind = {}
|
||
for kind in ("approval", "cc_action", "cc_read"):
|
||
per_kind[kind] = len(rows_for(inbox_of(api, admin, kind=kind), job))
|
||
check("档位筛选各归各的:选了那一档就只剩那一档",
|
||
all(kinds_of(rows_for(inbox_of(api, admin, kind=kind), job)) <= {kind}
|
||
for kind in ("approval", "cc_action", "cc_read")),
|
||
str({k: sorted(kinds_of(rows_for(inbox_of(api, admin, kind=k), job)))
|
||
for k in ("approval", "cc_action", "cc_read")}))
|
||
mine_all = rows_for(inbox_of(api, admin), job)
|
||
check("我自己的那一格「全部」= 三档相加(页眉那句共 N 条与逐档的数一把尺)",
|
||
len(mine_all) == per_kind["approval"] + per_kind["cc_action"] + per_kind["cc_read"],
|
||
str((len(mine_all), per_kind)))
|
||
check("计数接口报出三档与未读数(红点那条筛选题与页眉都吃它)",
|
||
bool(breakdown_ok) and {"approval", "cc_action", "cc_read", "unread"} <= set(counts or {}),
|
||
str(counts))
|
||
|
||
# ---------------- 2) 看过:红点灭,行留下 ----------------
|
||
before = counts.get("unread") if counts else None
|
||
status, data, message = api.post(f"/task/{task_id}/view", token=admin, json={})
|
||
after_rows = rows_for(inbox_of(api, admin), job)
|
||
approval = next((row for row in after_rows if str(row.get("id")) == task_id), None)
|
||
check("单条「标记已读」打得通", status < 400, f"{status} {message}")
|
||
check("看过之后红点灭了", approval is not None and approval.get("unread") is False,
|
||
str(approval and (approval.get("unread"))))
|
||
check("但行照旧留在待办里(已读不是已办)",
|
||
approval is not None
|
||
and any(row.get("inbox_kind") == "approval" for row in after_rows),
|
||
str(kinds_of(after_rows)))
|
||
after_counts = api.get("/task/processing/count", token=admin)[1] or {}
|
||
check("未读数跟着降,总条数不降",
|
||
(before is None or after_counts.get("unread") is None
|
||
or int(after_counts["unread"]) <= int(before))
|
||
and int(after_counts.get("total") or 0) >= int((counts or {}).get("total") or 0),
|
||
str((before, after_counts.get("unread"), after_counts.get("total"))))
|
||
viewed_only = rows_for(inbox_of(api, admin, viewed="0"), job)
|
||
check("只看未读那一档里,刚看过的那条不再出现",
|
||
all(str(row.get("id")) != task_id for row in viewed_only),
|
||
str([(r.get("id"), r.get("unread")) for r in viewed_only]))
|
||
|
||
# 只需阅那条:打开单据页即已阅 -> 当场离开待办,界面上没有第二张「待阅」列表
|
||
status, data, message = api.post("/read/view", token=tokens[p_plain.id], json={"job": job})
|
||
still = rows_for(inbox_of(api, tokens[p_plain.id]), job)
|
||
archived = fresh(db).execute(select(models.ReadCompleted).where(
|
||
models.ReadCompleted.work == work,
|
||
models.ReadCompleted.identity == ref(p_plain))).scalars().all()
|
||
check("只需阅那条:打开单据页就算看完",
|
||
status < 400 and int((data or {}).get("count") or 0) == 1, f"{status} {message}")
|
||
check("只需阅那条:看完直接离开待办(不再有单独的待阅列表可去)",
|
||
not still and not any(row.get("inbox_kind") == "cc_read" for row in still),
|
||
str([(r.get("inbox_kind"), r.get("unread")) for r in still]))
|
||
check("只需阅那条:归进已阅表,且带的是真的已阅时刻",
|
||
len(archived) == 1 and archived[0].view_time is not None, f"已阅 {len(archived)} 条")
|
||
done_rows = api.get("/read/completed?page=1&page_size=200", token=tokens[p_plain.id])
|
||
check("已阅列表读得到那一条(/read 这一页只剩已阅一档)",
|
||
any(str(row.get("job")) == job for row in ((done_rows[1] or {}).get("items") or [])),
|
||
str(done_rows[:2]))
|
||
|
||
# 需处理那条:打开单据只灭红点,行必须留下
|
||
status, data, message = api.post("/read/view", token=tokens[p_action.id], json={"job": job})
|
||
# 这一档单独筛着看:这条流程自己配了自动抄送,收件人手上不止我抄的那一条
|
||
action_after = rows_for(inbox_of(api, tokens[p_action.id], kind="cc_action"), job)
|
||
left = action_after[0] if action_after else None
|
||
check("需处理那条:打开单据页不登记已阅(还留在待办里)",
|
||
status < 400 and int((data or {}).get("count") or 0) == 0 and left is not None,
|
||
f"{status} {message} 档位 {sorted(kinds_of(action_after))}")
|
||
check("需处理那条:单据页既然打开了,红点就此熄灭",
|
||
left is not None and left.get("unread") is False, str(left and left.get("unread")))
|
||
check("需处理那条:行照旧在待办里,等本人点「处理」",
|
||
left is not None and left.get("requires_action") is True, "")
|
||
|
||
# 批量"看过":已经看过的那条不许重盖第一次看的时间,报 already 不报 failed
|
||
action_id = str(left.get("id")) if left else ""
|
||
status, data, message = api.post("/task/inbox/seen", token=tokens[p_action.id],
|
||
json={"ids": [action_id]})
|
||
check("批量「看过」对已经看过的那条报「之前就标过」,不报失败",
|
||
status < 400 and int((data or {}).get("already") or 0) == 1
|
||
and int((data or {}).get("failed") or 0) == 0,
|
||
f"{status} {message} {data}")
|
||
|
||
# ---------------- 3) 只有"处理"才让它离开待办,办完归已办 ----------------
|
||
status, data, message = api.post("/task/inbox/execute", token=tokens[p_action.id],
|
||
json={"ids": [action_id], "opinion": "已按要求处理"})
|
||
after = rows_for(inbox_of(api, tokens[p_action.id], kind="cc_action"), job)
|
||
moved = fresh(db).execute(select(models.ReadCompleted).where(
|
||
models.ReadCompleted.work == work,
|
||
models.ReadCompleted.identity == ref(p_action))).scalars().all()
|
||
check("批量「处理」写了意见,那条就此离开待办",
|
||
status < 400 and int((data or {}).get("succeeded") or 0) == 1 and not after,
|
||
f"{status} {message} {data} 还剩 {len(after)} 行")
|
||
check("归档行看得出是需处理那类、说的是本人那句、带的是真的处理时刻",
|
||
len(moved) == 1 and bool(moved[0].requires_action) and moved[0].handle_time is not None
|
||
and moved[0].opinion == "已按要求处理",
|
||
f"归档 {len(moved)} 条")
|
||
# 界面上的落点:需处理办完归**已办**,已阅只收不需处理那一条(判据同一个)
|
||
done_rows = api.get("/task/completed?page=1&page_size=200", token=tokens[p_action.id])
|
||
read_rows = api.get("/read/completed?page=1&page_size=200", token=tokens[p_action.id])
|
||
check("已办列表读得到这一条,并说得出它是抄送处理",
|
||
any(str(row.get("job")) == job and row.get("done_source") == "cc"
|
||
for row in ((done_rows[1] or {}).get("items") or [])),
|
||
str([(r.get("job"), r.get("done_source"))
|
||
for r in ((done_rows[1] or {}).get("items") or [])][:6]))
|
||
check("已阅列表不再收到需处理那一档(两处各认 requires_action 的一半)",
|
||
not any(str(row.get("job")) == job and bool(row.get("requires_action"))
|
||
for row in ((read_rows[1] or {}).get("items") or [])),
|
||
str([(r.get("job"), r.get("requires_action"))
|
||
for r in ((read_rows[1] or {}).get("items") or [])][:6]))
|
||
|
||
# ---------------- 4) 一次勾选混两档 ----------------
|
||
job2, _work2, created2 = start("混合批量")
|
||
tasks2 = [row for row in (created2.get("tasks") or []) if not row.get("finish_time")]
|
||
if check("混合批量这张校验单拿得到待办", bool(tasks2), ""):
|
||
task2 = str(tasks2[0].get("id") or "")
|
||
status, _, message = api.post(f"/task/{task2}/cc", token=admin,
|
||
json={"identities": [ref(p_more)], "opinion": "写一句",
|
||
"requires_action": True})
|
||
check("混合批量:抄送需处理打得通", status < 400, f"{status} {message}")
|
||
mine2 = rows_for(inbox_of(api, admin), job2)
|
||
check("混合批量:我自己的那一条在发起人取件箱里",
|
||
any(row.get("inbox_kind") == "approval" and str(row.get("id")) == task2
|
||
for row in mine2),
|
||
str(sorted(kinds_of(mine2))))
|
||
cc_row = next((row for row in rows_for(inbox_of(api, tokens[p_more.id]), job2)
|
||
if row.get("inbox_kind") == "cc_action"), None)
|
||
check("混合批量:那条抄送落进收件人自己的取件箱", cc_row is not None, str(sorted(
|
||
kinds_of(rows_for(inbox_of(api, tokens[p_more.id]), job2)))))
|
||
status, data, message = api.post("/task/inbox/seen", token=admin, json={"ids": [task2]})
|
||
check("批量「看过」只动我自己的待办那一条时照样成",
|
||
status < 400 and int((data or {}).get("marked") or 0) == 1, f"{status} {message}")
|
||
# 批量处理:抄送行不许参与「共同出口」——它没有出口,界面上那排出口只按待办算
|
||
# (前端的 batchRoutes 认这个口径;后端这一路按档位分开走,不拿空出口清单顶掉整批)
|
||
# ---------------- 5) 处理意见是选填的(2026-11 第二条口径) ----------------
|
||
# 混批框里不写那句是常态:以前这一趟会把抄送原样退回来(报一档 skipped),
|
||
# 现在必填的是那颗钮,不是那几个字——空着也办得掉,来意那句留在档案里。
|
||
# 得赶在 task2 被办掉之前抄,抄送挂在待办上,那条待办一办完就抄不出去了。
|
||
status, _, message = api.post(f"/task/{task2}/cc", token=admin,
|
||
json={"identities": [ref(p_action)],
|
||
"opinion": f"空意见校验-{STAMP}",
|
||
"requires_action": True})
|
||
check("再抄一条需处理给空意见这一路(同一张单上换了个人)", status < 400, f"{status} {message}")
|
||
blank_rows = [row for row in rows_for(inbox_of(api, tokens[p_action.id], kind="cc_action"), job2)
|
||
if row.get("opinion") == f"空意见校验-{STAMP}"]
|
||
blank_id = str((blank_rows[0] if blank_rows else {}).get("id") or "")
|
||
status, data, message = api.post("/task/inbox/execute", token=tokens[p_action.id],
|
||
json={"ids": [blank_id], "opinion": " "})
|
||
left_after = [row for row in rows_for(inbox_of(api, tokens[p_action.id], kind="cc_action"), job2)
|
||
if str(row.get("id")) == blank_id]
|
||
if check("空着意见按「处理」也照样办得掉:不再报 skipped",
|
||
bool(blank_id) and status < 400
|
||
and int((data or {}).get("succeeded") or 0) == 1
|
||
and int((data or {}).get("skipped") or 0) == 0 and not left_after,
|
||
f"id={blank_id} {status} {message} {data} 还剩 {len(left_after)} 行"):
|
||
blank_row = fresh(db).execute(select(models.ReadCompleted).where(
|
||
models.ReadCompleted.read == blank_id)).scalar_one_or_none()
|
||
check("空意见不改写档案:抄送时那句来意原样留着,处理时刻照落",
|
||
blank_row is not None and blank_row.handle_time is not None
|
||
and blank_row.opinion == f"空意见校验-{STAMP}",
|
||
str(blank_row and (blank_row.handle_time, blank_row.opinion)))
|
||
|
||
status, data, message = api.post("/task/inbox/execute", token=admin,
|
||
json={"ids": [task2],
|
||
"route_name": (tasks2[0].get("route_name_list") or ["submit"])[0],
|
||
"opinion": "同意"})
|
||
check("批量「处理」按待办那一条的出口走得动",
|
||
status < 400 and int((data or {}).get("succeeded") or 0) == 1, f"{status} {message}")
|
||
return 0
|
||
finally:
|
||
purge(db, jobs, titles)
|
||
print(f"\n合计 {PASSED + len(FAILS)} 项:通过 {PASSED} / 失败 {len(FAILS)}")
|
||
for item in FAILS:
|
||
print(f" 未通过:{item}")
|
||
db.close()
|
||
|
||
|
||
if __name__ == "__main__":
|
||
raise SystemExit(main())
|