unis-oa/backend/scripts/invoice_demo/purge.py

59 lines
2.4 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
"""按标题前缀清掉演练单据(含核验台账),只给"这套演练数据别留在库里"时用。
单据本体交给 ``expense/purge.py``(那张清单已经覆盖 work / task / log / read /
attachment / notification 与草稿、批注),这里只补它不认识的那一张表:
``oa_external_check``。**台账必须跟着一起清**——留着的话,界面上单没了、右栏那块
面板还在读一批指向空气的批次,下一个人只会以为是闸门坏了。
"""
from __future__ import annotations
import json
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from sqlalchemy import or_, select # noqa: E402
from app import db, models # noqa: E402
from expense import purge as expense_purge # noqa: E402
from .common import TITLE_PREFIX # noqa: E402
def purge(prefixes: list[str] | None = None) -> dict:
result = expense_purge.purge(prefixes or [TITLE_PREFIX])
jobs = set(result.get("jobs") or [])
counts: dict[str, int] = {}
session = db.SessionLocal()
try:
# 单据 id 与单号是两个东西:台账的 work 存的是 work id,job 存的是单号,
# 所以先把这批 job 对应的 work id 捞出来,两列都按各自口径清
work_ids: set[str] = set()
if jobs:
for model in (models.Work, models.WorkCompleted):
work_ids |= set(session.execute(
select(model.id).where(model.job.in_(jobs))
).scalars().all())
for model in (models.ExternalCheck, models.OutboundMessage):
rows = session.execute(select(model).where(or_(
model.job.in_(jobs), model.work.in_(work_ids)))).scalars().all()
counts[model.__tablename__] = len(rows)
for row in rows:
session.delete(row)
session.commit()
result["external_check"] = counts.get(models.ExternalCheck.__tablename__, 0)
# 发件箱也一起清:报文留着,列表上就是一排点开就报"单据不存在"的死信
result["outbound_message"] = counts.get(models.OutboundMessage.__tablename__, 0)
result["prefixes"] = prefixes or [TITLE_PREFIX]
return result
finally:
session.close()
if __name__ == "__main__":
print(json.dumps(purge(sys.argv[1:] or None), ensure_ascii=False, indent=2))