549 lines
32 KiB
Python
549 lines
32 KiB
Python
#!/usr/bin/env python3
|
||
"""守批量这一路的三件事:待办能批量标已读、批量能按当前筛选取整片、五档账目对得平。
|
||
|
||
用户口径(2026-11 提的):「待办、待阅中我希望可以实现批量已读、批量处理」。待阅那边
|
||
先前已经有一条 ``POST /read/view/batch``,这一篇补的是另外三块:
|
||
|
||
1. **待办有「批量已读」**:``POST /task/view/batch`` 只给 ``oa_task.view_time`` 盖一个时间戳,
|
||
不表态、不流转。这一条最容易坏的就是把「已读」顺手做成「已办」,所以断言盯着:待办还
|
||
pending、还在原环节、出口与超时时刻一个字没变、单据照旧 running;再盯第二次点不重盖
|
||
时间戳(那一格说的是「第一次点开」);外人名下那条动不了,且只回那一条的原因。
|
||
2. **批量能按当前筛选取整片**:两个批量口子都收 ``scope``,字段名与各自那个列表查询一字
|
||
不差。表头那只勾只勾得到已经翻到的几页,「还有 30 条没滑到」时批量就成了假省力。这一条
|
||
钉的是**同一把尺**:列表筛出几条 = 动了几条 + 因超限留下几条,一条都不许两头都不在;
|
||
以及身份那一道不被绕过 —— 同一串关键词,别人名下没有这几条,就一条都动不了。
|
||
3. **五档各归各**:成了几条 / 早就是这状态的 ``already`` / 需要额外条件没动的 ``skipped`` /
|
||
超限一条没碰的 ``truncated`` / 真没办成带逐条原因的 ``failed``。混档的代价是人以为这批
|
||
出了错,回头把整批重勾一遍。
|
||
|
||
第 1、4 段走真接口真单据(发得起来才证得了口径落在真链路上),收尾按 job 与标题清干净
|
||
(``check_write_payload.purge``);第 2、3 段要的条数(几十条、别人名下、超限)不该往开发库
|
||
里发几十张真单,全程在一个未提交事务里摆探针行,收尾 ``rollback``。::
|
||
|
||
PYTHONPATH=. python3 scripts/check_task_batch_read.py
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import os
|
||
import pathlib
|
||
import sys
|
||
from datetime import datetime, timedelta
|
||
|
||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent))
|
||
# TestClient 会跑一遍应用启动:不关掉调度线程,超时标记与写回投递会在断言中间自己动
|
||
os.environ.setdefault("OA_SCHEDULER", "off")
|
||
|
||
from sqlalchemy import delete, func, select # noqa: E402
|
||
from starlette.testclient import TestClient # noqa: E402
|
||
|
||
from app import models, schemas # noqa: E402
|
||
from app.api import runtime # noqa: E402
|
||
from app.db import SessionLocal # noqa: E402
|
||
from app.deps import CurrentUser # 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")
|
||
#: 与 ``app/api/runtime.py::BATCH_LIMIT`` 同一个数:那边改了这边要红给你看
|
||
BATCH_LIMIT = 50
|
||
|
||
FAILS: list[str] = []
|
||
PASSED = 0
|
||
|
||
|
||
def check(label: str, passed: bool, detail: str = "") -> bool:
|
||
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, model, row_id):
|
||
"""绕开身份映射里那份旧快照,回库重新问一行(接口用的是另一个 Session)。"""
|
||
db.rollback()
|
||
return db.get(model, row_id)
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 1~4 段:真接口、真单据
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
def live_part(api: Api, db, starter, outsider, process) -> list[str]:
|
||
"""跑真单据那几段,回本次发过的 job(供收尾清理)。"""
|
||
admin = api.token(starter)
|
||
stranger = api.token(outsider)
|
||
jobs: list[str] = []
|
||
titles: list[str] = []
|
||
|
||
def start(label: str):
|
||
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 ""))
|
||
open_tasks = [row for row in (data.get("tasks") or []) if not row.get("finish_time")]
|
||
return str(data.get("job") or ""), str(data.get("work") or ""), open_tasks
|
||
|
||
# ---------------- 1) 批量标记已读只盖章,不表态 ----------------
|
||
job1, work1, open1 = start("只盖章")
|
||
if not check("这张校验单发得起来", bool(open1), str(open1)[:120]):
|
||
return jobs
|
||
task_id = str(open1[0].get("id") or "")
|
||
before = fresh(db, models.Task, task_id)
|
||
snapshot = (before.status, before.activity, before.route_name, before.expire_time,
|
||
before.opinion, before.view_time) if before else None
|
||
|
||
status, data, message = api.post("/task/view/batch", token=admin, json={"task_ids": [task_id]})
|
||
check("批量标记待办已读:一条盖得上,逐条账目回得齐",
|
||
status < 400 and int((data or {}).get("marked") or 0) == 1
|
||
and int((data or {}).get("failed") or 0) == 0
|
||
and int((data or {}).get("already") or 0) == 0
|
||
and "truncated" in (data or {}), f"{status} {message} {data}")
|
||
|
||
after = fresh(db, models.Task, task_id)
|
||
same = after is not None and (after.status, after.activity, after.route_name, after.expire_time,
|
||
after.opinion) == snapshot[:5]
|
||
check("盖完章:还 pending、还在原环节、出口/超时/意见一个字没动(「已读」不是「已办」)",
|
||
same, None if after is None else str((after.status, after.activity, after.route_name,
|
||
after.expire_time, after.opinion)))
|
||
check("盖完章确实留下了已读时间,而从前只有进详情页才盖得上",
|
||
after is not None and after.view_time is not None
|
||
and (snapshot is None or snapshot[5] is None),
|
||
None if after is None else repr(after.view_time))
|
||
work_row = fresh(db, models.Work, work1)
|
||
check("单据照旧在流转:批量已读没把流程往前推一步",
|
||
work_row is not None and work_row.status == "running",
|
||
None if work_row is None else work_row.status)
|
||
|
||
# ---------------- 2) 再点一次:归 already,不重盖时间戳 ----------------
|
||
first_time = fresh(db, models.Task, task_id).view_time
|
||
status, data, message = api.post("/task/view/batch", token=admin, json={"task_ids": [task_id]})
|
||
check("同一批再点一次:归 already,不算失败也不重复盖章",
|
||
status < 400 and int((data or {}).get("marked") or 0) == 0
|
||
and int((data or {}).get("already") or 0) == 1
|
||
and int((data or {}).get("failed") or 0) == 0, f"{status} {message} {data}")
|
||
check("第一次那个时间戳没被第二次顶掉:界面那一格说的是「第一次点开」",
|
||
fresh(db, models.Task, task_id).view_time == first_time, repr(first_time))
|
||
|
||
# ---------------- 3) 逐条原因与越界 ----------------
|
||
status, data, message = api.post(
|
||
"/task/view/batch", token=admin, json={"task_ids": [f"查无此条-{STAMP}"]})
|
||
errors = (data or {}).get("errors") or []
|
||
check("查无此条:进 failed,并把这一条自己的原因带回去",
|
||
status < 400 and int((data or {}).get("failed") or 0) == 1
|
||
and len(errors) == 1 and str(errors[0].get("message") or ""), f"{status} {message} {data}")
|
||
|
||
status, data, message = api.post("/task/view/batch", token=stranger, json={"task_ids": [task_id]})
|
||
errors = (data or {}).get("errors") or []
|
||
check("外人名下这条动不了:只回这一条的原因,不替别人盖章",
|
||
status < 400 and int((data or {}).get("marked") or 0) == 0
|
||
and int((data or {}).get("failed") or 0) == 1
|
||
and ("身份" in str(errors[0].get("message")) or "不属于" in str(errors[0].get("message"))),
|
||
f"{status} {message} {data}")
|
||
|
||
status, data, message = api.post("/task/view/batch", token=admin, json={"task_ids": []})
|
||
check("空勾选按 400 回,不闷头提交一个空批", status == 400, f"{status} {message}")
|
||
|
||
# ---------------- 4) 批量处理按 id 那条路一字未动 ----------------
|
||
status, data, message = api.post(
|
||
"/task/batch-execute", token=admin,
|
||
json={"task_ids": [task_id], "route_name": "", "opinion": "整批一起同意"})
|
||
check("批量处理按 id 那条路一字未动:这一条真办掉了",
|
||
status < 400 and int((data or {}).get("succeeded") or 0) == 1, f"{status} {message} {data}")
|
||
check("批量处理的返回里也带 truncated(按 id 提交时恒为 0,不是漏字段)",
|
||
status >= 400 or int((data or {}).get("truncated") or 0) == 0, f"{data}")
|
||
|
||
# ---------------- 4b) 真单据 + 真筛选:整片标记已读与列表同口径 ----------------
|
||
# 这一片(整条流程的未读待办)里可能混着库里本来就躺着的那几条——比如别人留下的那张校
|
||
# 验单。先把它们记下来,收尾照原样还回去:批量已读读得到别人的档案,但不该改别人的档案。
|
||
untouched = {row.id for row in db.execute(
|
||
select(models.Task).where(models.Task.identity == personref.ref_of(starter),
|
||
models.Task.process == process.id,
|
||
models.Task.view_time.is_(None))).scalars().all()}
|
||
# 这一段的筛选只用 process 那一项:这条流程把标题重算过(发单时给的标题会被换成
|
||
# 「流程名(部门)-人名…」),按关键词筛真单会挑到别人那一批校验数据,条数就不是本次说的
|
||
# 那一片了。流程号压不住的是"这一条此刻归谁",那一条由服务端那道身份筛管着。
|
||
second = start("整片筛选")
|
||
if second[2]:
|
||
scope = {"process": process.id, "viewed": "0"}
|
||
listed = api.get(
|
||
f"/task/processing?process={process.id}&viewed=0&page=1&page_size=50", token=admin)
|
||
items = ((listed[1] or {}).get("items") or [])
|
||
total_live = int(((listed[1] or {}).get("total")) or 0)
|
||
touched = [str(row.get("id")) for row in items if str(row.get("id")) in untouched]
|
||
status, data, message = api.post("/task/view/batch", token=admin, json={"scope": scope})
|
||
payload = data or {}
|
||
marked, truncated = int(payload.get("marked") or 0), int(payload.get("truncated") or 0)
|
||
check("整片标记已读动到的条数 + 因超限留下的 = 列表按同一条件筛出的条数",
|
||
status < 400 and marked + truncated == total_live and marked > 0,
|
||
f"{status} {message} marked={marked} truncated={truncated} total={total_live}")
|
||
check("刚被整片标记掉的那一条,列表按 viewed=0 再筛就不见了(两处同一把尺)",
|
||
str(second[2][0].get("id")) not in [
|
||
str(row.get("id")) for row in ((api.get(
|
||
f"/task/processing?process={process.id}&viewed=0&page=1&page_size=50",
|
||
token=admin)[1] or {}).get("items") or [])],
|
||
str([str(row.get("id")) for row in items])[:160])
|
||
# 本次真发的那两张单要按标题清掉,多出来的已读时间无所谓;库里原本躺着的那几条
|
||
# (不是本次发的)必须回到没读过的样子,否则跑一次校验就替人盖一次章
|
||
restored = 0
|
||
for row_id in touched:
|
||
row = fresh(db, models.Task, row_id)
|
||
if row is not None and row.view_time is not None:
|
||
row.view_time = None
|
||
restored += 1
|
||
db.commit()
|
||
leftovers = [row_id for row_id in touched
|
||
if getattr(fresh(db, models.Task, row_id), "view_time", None) is not None]
|
||
check("整片标记顺带扫到的旧待办已还原成未读:校验单不在别人那张单上留新章",
|
||
not leftovers, f"还原 {restored} 条,还剩 {leftovers}")
|
||
return jobs
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 5~6 段:按筛选取整片(探针行 + rollback,不往开发库里发几十张真单)
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
#: 探针行统一挂在这个前缀的身份下:真人的身份就是账号名(localadmin / zhangsan…),
|
||
#: 撞不上,所以按它清理不会误伤别人的数据。
|
||
PROBE_IDENTITY = "__batch_scope_"
|
||
|
||
|
||
def purge_probe(db, identities: list[str]) -> int:
|
||
"""删掉探针行,回删掉的条数。开头清一次、结尾再清一次。
|
||
|
||
批量那三个口子(标记已读、批量处理、待阅登记)末尾都走 ``_commit``:它们**真的提交**。
|
||
所以脚本里那句 ``db.rollback()`` 退不掉探针行——探针行跟接口那一次提交一起进了库。
|
||
上一轮留下的几十条要是不清干净,下一轮「列表按这串关键词筛出几条」读到的就是两轮合计,
|
||
账对不平,红的还是假红。开头那一次管的是上一轮跑崩留下的,结尾这一次管的是自己这轮。
|
||
|
||
待办、待阅、已办、已阅四张表都按 ``identity`` 前缀删;操作日志只删本次这几条批量动作
|
||
(``batch_view_task`` / ``batch_execute_task`` / ``batch_view_read``)留下的那些行。
|
||
"""
|
||
rows = 0
|
||
for model in (models.ReadCompleted, models.Read, models.TaskCompleted, models.Task):
|
||
result = db.execute(
|
||
delete(model).where(model.identity.like(f"{PROBE_IDENTITY}%")))
|
||
rows += int(getattr(result, "rowcount", 0) or 0)
|
||
db.execute(
|
||
delete(models.OperationLog).where(
|
||
models.OperationLog.identity.in_(identities or ["-1"]),
|
||
models.OperationLog.action.in_(
|
||
("batch_view_task", "batch_execute_task", "batch_view_read"))))
|
||
db.commit()
|
||
return rows
|
||
|
||
|
||
def scope_part(db, starter, process) -> None:
|
||
me = f"{PROBE_IDENTITY}me_{STAMP}"
|
||
other = f"{PROBE_IDENTITY}other_{STAMP}"
|
||
wide = f"批量已读门-超限-{STAMP}"
|
||
#: 批量处理自己那一片,与上面那片各用各的关键词:两边都按「整片」取范围,
|
||
#: 共用一片就会被对方先动过,条数立刻对不上(这一条踩过一次,记在这)
|
||
exec_wide = f"批量已读门-整片处理-{STAMP}"
|
||
mine = CurrentUser(person=starter, ref=me, is_admin=False, permissions=("work:profile",))
|
||
theirs = CurrentUser(person=starter, ref=other, is_admin=False, permissions=("work:profile",))
|
||
|
||
def task_row(tag: str, index: int, identity: str, *, viewed: bool = False,
|
||
title: str = "", read_work: str = "") -> models.Task:
|
||
row = models.Task(
|
||
job=f"job-{tag}-{index}", work=f"work-{tag}-{index}",
|
||
title=title or f"{tag}-{index}", process=process.id, process_name=process.name,
|
||
serial=f"PROBE{tag}{index:03d}", activity="act-probe", activity_name="校验环节",
|
||
person=str(starter.id), identity=identity, identity_name=starter.display_name,
|
||
unit="", unit_name="", creator="", creator_person="", creator_identity="",
|
||
creator_unit="", creator_unit_name="", form="f", act="create",
|
||
start_time=datetime.now() - timedelta(minutes=index),
|
||
route_name_list=["同意"], route_list=["r"])
|
||
if viewed:
|
||
row.view_time = datetime.now() - timedelta(seconds=30)
|
||
return row
|
||
|
||
try:
|
||
# ---------------- 5) 待办:整片的条数、只取未读、超限、逐条失败 ----------------
|
||
for index in range(BATCH_LIMIT + 7):
|
||
db.add(task_row(wide, index, me))
|
||
# 同一片里再摆三条"已经读过"的:整片标记默认不该把它们算进来占额度
|
||
for index in range(3):
|
||
db.add(task_row(wide, 900 + index, me, viewed=True))
|
||
# 探针行**先提交**再动手:批量那几个口子末尾都走 ``_commit``,同一个 Session 里
|
||
# flush 下去的行会被它们顺手一起提交,靠收尾那句 rollback 退不掉(上一轮就是这么漏
|
||
# 下一库的)。干脆自己落干净,清库交给 purge_probe,别让「以为回滚了」骗人。
|
||
db.commit()
|
||
|
||
listed = runtime.list_processing(
|
||
user=mine, db=db, keyword=wide, process="", category="", activity="", expired="",
|
||
start_date="", end_date="", viewed="", order_by="start_time", order="desc",
|
||
work_status="", page=1, page_size=BATCH_LIMIT + 20)
|
||
total_live = int(((listed.get("data") or {}).get("total")) or 0)
|
||
check("列表按这串关键词筛得到的条数拿得到(scope 用的就是这一份筛选)",
|
||
total_live == BATCH_LIMIT + 10, f"total={total_live}")
|
||
|
||
unread = runtime.list_processing(
|
||
user=mine, db=db, keyword=wide, process="", category="", activity="", expired="",
|
||
start_date="", end_date="", viewed="0", order_by="start_time", order="desc",
|
||
work_status="", page=1, page_size=BATCH_LIMIT + 20)
|
||
total_unread = int(((unread.get("data") or {}).get("total")) or 0)
|
||
check("列表按 viewed=0 筛只筛没点开过的那几条:批量那一路认的是同一个条件",
|
||
total_unread == BATCH_LIMIT + 7, f"total={total_unread}")
|
||
|
||
res = runtime.view_tasks_batch(
|
||
body=schemas.TaskViewBatchBody(scope={"keyword": wide}), user=mine, db=db, request=None)
|
||
payload = res.get("data") or {}
|
||
marked, truncated = int(payload.get("marked") or 0), int(payload.get("truncated") or 0)
|
||
check("只交筛选条件不交 id:整片里的待办被标记掉,且动到的是上限那一沓",
|
||
marked == BATCH_LIMIT, f"marked={marked}")
|
||
check("被上限挡在外面的条数照实报 truncated(一条都没碰,既不算成功也不算失败)",
|
||
truncated == total_unread - BATCH_LIMIT, f"truncated={truncated}")
|
||
check("账目对得平:动了的 + 因超限留下的 = 列表按同一条件筛出的条数",
|
||
marked + truncated == total_unread, f"{marked} + {truncated} vs {total_unread}")
|
||
check("整片里那三条「早读过的」不占额度也不报错:整片标记只取没点开过的那些",
|
||
int(payload.get("already") or 0) == 0, f"already={payload.get('already')}")
|
||
|
||
# 同一条件再点一次:没点开过的已经被自己点光了
|
||
try:
|
||
res = runtime.view_tasks_batch(
|
||
body=schemas.TaskViewBatchBody(scope={"keyword": wide}), user=mine, db=db, request=None)
|
||
check("同一条件再点一次只剩超限那几条没动:这一次动的是剩下的,不是重盖",
|
||
int((res.get("data") or {}).get("already") or 0) == 0
|
||
and int((res.get("data") or {}).get("marked") or 0) == truncated, str(res)[:160])
|
||
except Exception as exc: # 全被上一轮点光时按空勾选回
|
||
check("整片已无未读时按 400 回,不提交一个空批",
|
||
getattr(exc, "status_code", 0) == 400, str(exc))
|
||
|
||
# 身份那一道:同一串关键词,别人名下一条都没有
|
||
try:
|
||
runtime.view_tasks_batch(
|
||
body=schemas.TaskViewBatchBody(scope={"keyword": wide}), user=theirs, db=db, request=None)
|
||
check("同一片关键词在别人名下没有待阅/待办:回空勾选,不替别人盖章", False, "没报空勾选")
|
||
except Exception as exc:
|
||
check("同一片关键词在别人名下没有待办:回空勾选,不替别人盖章",
|
||
getattr(exc, "status_code", 0) == 400, str(exc))
|
||
|
||
# 批量处理也认 scope。这里的探针行没有对应的单据行(不该为了这一条往开发库里
|
||
# 发几十张真单),所以钉的不是"办成了几条",而是**取到的正是列表那一片**:窗口内
|
||
# 逐条各有下场、加起来的条数正好是上限那一沓,窗外那几条原样留着、一条都没碰。
|
||
for index in range(BATCH_LIMIT + 2):
|
||
db.add(task_row(exec_wide, index, me))
|
||
db.commit()
|
||
exec_total = int(db.execute(
|
||
select(func.count(models.Task.id)).where(models.Task.identity == me,
|
||
models.Task.title.like(f"%{exec_wide}%"))
|
||
).scalar() or 0)
|
||
check("批量处理那一片摆好了条数(比上限多两条,好让超限那档真被走到)",
|
||
exec_total == BATCH_LIMIT + 2, f"total={exec_total}")
|
||
# 先按待办列表那一页记下窗口内的是哪 50 条,再让批量去取整片:两处取到的必须是同一沓
|
||
window = [str(row.get("id")) for row in
|
||
((runtime.list_processing(
|
||
user=mine, db=db, keyword=exec_wide, process="", category="", activity="",
|
||
expired="", start_date="", end_date="", viewed="", order_by="start_time",
|
||
order="desc", work_status="", page=1, page_size=BATCH_LIMIT
|
||
).get("data") or {}).get("items") or [])]
|
||
res = runtime.batch_execute_task(
|
||
body=schemas.BatchExecuteBody(scope={"keyword": exec_wide},
|
||
route_name="同意", opinion="整片一起同意"),
|
||
user=mine, db=db, request=None)
|
||
payload = res.get("data") or {}
|
||
accounted = int(payload.get("succeeded") or 0) + int(payload.get("failed") or 0)
|
||
spilled = int(payload.get("truncated") or 0)
|
||
attempted = [str(item.get("id") or "") for item in (payload.get("errors") or [])]
|
||
attempted += [str(item.get("id") or item.get("task_id") or "")
|
||
for item in (payload.get("results") or [])]
|
||
check("批量处理按筛选取整片:动到的正是上限那一沓,逐条各有下场、不多不少",
|
||
accounted == BATCH_LIMIT, str(payload)[:200])
|
||
check("批量处理按筛选取到的就是列表那一页的同一沓:同一把尺,不漏办也不多办",
|
||
sorted(attempted) == sorted(window) and len(window) == BATCH_LIMIT,
|
||
f"批量 {len(set(attempted))} 条 / 列表 {len(set(window))} 条")
|
||
check("批量处理按筛选时同样报 truncated:窗外那几条既没动也没算进账",
|
||
"truncated" in payload and spilled == exec_total - BATCH_LIMIT,
|
||
f"truncated={spilled} total={exec_total}")
|
||
still = int(db.execute(
|
||
select(func.count(models.Task.id)).where(
|
||
models.Task.identity == me,
|
||
models.Task.title.like(f"%{exec_wide}%"),
|
||
models.Task.status == "pending")).scalar() or 0)
|
||
check("整片都办不动时一条都没搬走:52 条待办照旧挂在待办里,界面上不会凭空少几行",
|
||
still == exec_total, f"库里还剩 {still} 条 / 摆了 {exec_total} 条")
|
||
check("逐条失败的那几条各带一句原因,界面才说得出是哪几条",
|
||
bool(payload.get("errors"))
|
||
and all(str(item.get("message") or "") for item in payload.get("errors") or []),
|
||
str(payload.get("errors"))[:200])
|
||
finally:
|
||
# 探针行是提交进来的,回滚退不掉;清库交给开头与结尾那两次 purge_probe
|
||
db.rollback()
|
||
|
||
try:
|
||
# ---------------- 6) 待阅:整片登记 + 需处理那几条不被批量洗掉 ----------------
|
||
work_tag = f"批量已读门-待阅-{STAMP}"
|
||
for index in range(4):
|
||
db.add(models.Read(
|
||
job=f"job-read-{index}", work=f"work-read-{index}", completed=False,
|
||
title=f"{work_tag}-{index}", process=process.id, process_name=process.name,
|
||
category="", serial=f"PROBEREAD{index}", activity="act-probe", activity_name="校验环节",
|
||
person=str(starter.id), identity=me, identity_name=starter.display_name, unit="",
|
||
sender=starter.display_name, creator_identity="", opinion="请补一句处理意见",
|
||
start_time=datetime.now() - timedelta(minutes=index), read_type="cc",
|
||
# 两条要处理、两条不用:批量已阅应当只办掉不要处理的那两条
|
||
requires_action=index % 2 == 0, attachments=[]))
|
||
db.commit()
|
||
res = runtime.view_reads_batch(
|
||
body=schemas.ReadBatchBody(ids=[], handling=False, scope={"keyword": work_tag}),
|
||
user=mine, db=db, request=None)
|
||
payload = res.get("data") or {}
|
||
check("待阅按筛选整片登记:无需处理的两条进已阅",
|
||
int(payload.get("marked") or 0) == 2, str(payload)[:200])
|
||
check("需处理的两条原样留在待阅里,报的是 skipped 不是 failed",
|
||
int(payload.get("skipped") or 0) == 2 and int(payload.get("failed") or 0) == 0,
|
||
str(payload)[:200])
|
||
check("skipped 那两条说得出为什么没动(要点「处理」那一颗钮)",
|
||
all("处理" in str(item.get("reason"))
|
||
for item in (payload.get("skipped_items") or [])) and payload.get("skipped_items"),
|
||
str(payload)[:200])
|
||
# 同一片里再点一次「批量已阅」:需处理那两条还在,仍然只是 skipped
|
||
res = runtime.view_reads_batch(
|
||
body=schemas.ReadBatchBody(ids=[], handling=False, scope={"keyword": work_tag}),
|
||
user=mine, db=db, request=None)
|
||
payload = res.get("data") or {}
|
||
check("再点一次整片:已登记掉的那两条不再被选中,只剩需处理那两条",
|
||
int(payload.get("marked") or 0) == 0 and int(payload.get("skipped") or 0) == 2,
|
||
str(payload)[:200])
|
||
try:
|
||
runtime.view_reads_batch(
|
||
body=schemas.ReadBatchBody(ids=[], handling=False, scope={"keyword": work_tag}),
|
||
user=theirs, db=db, request=None)
|
||
check("待阅那片关键词在别人名下一条都没有:回空勾选,不替别人登记", False, "没报空勾选")
|
||
except Exception as exc:
|
||
check("待阅那片关键词在别人名下一条都没有:回空勾选,不替别人登记",
|
||
getattr(exc, "status_code", 0) == 400, str(exc))
|
||
# 逐条勾选优先于筛选:勾了 1 条就只动 1 条,哪怕筛选能圈到更多
|
||
db.rollback()
|
||
for index in range(3):
|
||
db.add(models.Read(
|
||
job=f"job-mix-{index}", work=f"work-mix-{index}", completed=False,
|
||
title=f"{work_tag}-混-{index}", process=process.id, process_name=process.name,
|
||
category="", serial=f"PROBEMIX{index}", activity="act-probe", activity_name="校验环节",
|
||
person=str(starter.id), identity=me, identity_name=starter.display_name, unit="",
|
||
sender="", creator_identity="", opinion="", start_time=datetime.now(),
|
||
read_type="cc", requires_action=False, attachments=[]))
|
||
db.commit()
|
||
only = db.execute(
|
||
select(models.Read).where(models.Read.identity == me,
|
||
models.Read.title == f"{work_tag}-混-1")).scalars().first()
|
||
res = runtime.view_reads_batch(
|
||
body=schemas.ReadBatchBody(ids=[only.id], handling=False, scope={"keyword": work_tag}),
|
||
user=mine, db=db, request=None)
|
||
payload = res.get("data") or {}
|
||
check("id 与筛选同时给时以勾上的那条为准:屏幕上勾着什么就登记什么",
|
||
int(payload.get("marked") or 0) == 1, str(payload)[:200])
|
||
finally:
|
||
db.rollback()
|
||
|
||
|
||
def shape_part() -> None:
|
||
"""请求体口径:两种给法、驼峰与下划线都认。"""
|
||
body = schemas.TaskViewBatchBody.model_validate({"task_ids": ["a1"], "scope": {"keyword": "x"}})
|
||
check("批量标记已读认 task_ids 与 scope 两种给法",
|
||
body.task_ids == ["a1"] and body.scope == {"keyword": "x"}, repr(body))
|
||
body = schemas.BatchExecuteBody.model_validate(
|
||
{"scope": {"keyword": "x"}, "routeName": "同意", "opinion": "好"})
|
||
check("批量处理的驼峰写法(routeName)照旧认,scope 也认",
|
||
body.route_name == "同意" and body.scope == {"keyword": "x"}, repr(body))
|
||
body = schemas.TaskBatchBody.model_validate({"taskIds": ["a1", "a2"]})
|
||
check("两个批量口子共用同一份「动哪几条」的形状",
|
||
body.task_ids == ["a1", "a2"] and body.scope == {}, repr(body))
|
||
body = schemas.ReadBatchBody.model_validate({"ids": ["r1"], "scope": {"kind": "cc"}})
|
||
check("待阅那个口子也认 scope,且默认仍是「带意见一起处理」",
|
||
body.scope == {"kind": "cc"} and body.handling is True, repr(body))
|
||
|
||
|
||
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)
|
||
others = [row for row in people if starter is None or row.id != starter.id]
|
||
if starter is None or not others:
|
||
print("[跳过] 库里凑不出一个管理员加一个真人账号,批量这一路校不了")
|
||
db.close()
|
||
return 0
|
||
api = Api()
|
||
jobs: list[str] = []
|
||
titles = [f"批量已读门-只盖章-{STAMP}", f"批量已读门-整片选中-{STAMP}"]
|
||
try:
|
||
# 先把上一轮跑崩留下的探针行洗掉:批量那几个口子是真提交的,rollback 退不掉,
|
||
# 不清就有两轮的探针行叠在同一片筛选里,条数怎么算都对不上
|
||
stale = purge_probe(db, [])
|
||
if stale:
|
||
print(f"[提示] 清掉上一轮残留的探针行 {stale} 条")
|
||
jobs = live_part(api, db, starter, others[0], process)
|
||
scope_part(db, starter, process)
|
||
shape_part()
|
||
finally:
|
||
db.rollback()
|
||
purge(db, jobs, titles)
|
||
purge_probe(db, [f"{PROBE_IDENTITY}me_{STAMP}", f"{PROBE_IDENTITY}other_{STAMP}"])
|
||
db.close()
|
||
|
||
print(f"\n合计 {PASSED + len(FAILS)} 项:通过 {PASSED} / 失败 {len(FAILS)}")
|
||
return 1 if FAILS else 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
raise SystemExit(main())
|