482 lines
26 KiB
Python
482 lines
26 KiB
Python
"""按快照补抄:把后来才配上的那条「归档抄送」,补到已经归档、当时没抄到的那批费用报销单上。
|
||
|
||
背景
|
||
====
|
||
「费用报销流程」的归档环节(``cr_archive``)原本只有两条办结抄送(财务经理需处理 +
|
||
发起人只需阅)。2026-11-16 设计器里加了第三条:抄给何凝香、需处理。加完只对**之后**归档的
|
||
单生效——已经落进 ``oa_work_completed`` 的那些不会回头再抄一次,于是这批单在她那里根本不存在。
|
||
2026-11-17 在生产库上数过(``--list`` 就是这一笔账):这条流程 12 张归档单,
|
||
FYBX202611020006 / FYBX202611020010 她已经有待阅(别人手工抄过、且已登记已阅),
|
||
FYBX202611160007 归档时走的已是新设计、三条规则一条没漏,剩下 **9 张一条都没有**:
|
||
FYBX202611030017 / 202611100004 / 202611090003 / 202611090002 / 202611030002 /
|
||
202611040003 / 202611030016 / 202611030012 / 202611020014。
|
||
|
||
上线前置:先跑 ``sql/upgrade/20261117_read_creator_snapshot.sql``
|
||
================================================================
|
||
待阅行新加的发起人两列(``creator_person`` / ``creator_unit_name``)在引擎写待阅的那条
|
||
链路上,而 ``create_reads`` 的 INSERT 带着整行列清单——生产库没补这四列就跑,第一条语句就撞
|
||
``(1054, Unknown column 'oa_read.creator_person')``,而生产档 ``auto_create_schema=false``
|
||
不会自己补。脚本开跑前逐张表比一遍 ORM 与库(:func:`schema_gaps`),缺哪列、该跑哪份升级
|
||
脚本,直接点名。列补齐之前先用 ``--list`` 看清单:那一条引擎都不调。
|
||
|
||
为什么走"改快照 + 调引擎",不直接 INSERT 待阅
|
||
==============================================
|
||
待阅行上那几格(``activity=cr_archive``、``sender=触发这次抄送的那位经手人``、
|
||
``requires_action``、``work_completed``、发起人两列)以及随它而来的站内信与渠道投递,
|
||
都是 :func:`app.engine.engine.create_reads` 一家算出来的。手抄一份 INSERT 要复刻的口径
|
||
太多,而且漏一条通知就是"她待阅里有这条、点开的轨迹图上却没有"。这一版做的是:
|
||
|
||
1. 把该单**冻结的那份设计快照**里 ``cr_archive`` 的 ``ccRules`` 临时换成第三条那一条;
|
||
2. 调一次 :func:`app.engine.engine.apply_activity_cc`(与办结那一刻引擎自己走的是同一条通道,
|
||
``when="arrive"``、``activity=cr_archive``、``actor=归档那一刻按按钮的人``);
|
||
3. 立刻把快照改回原样(连 ``update_time`` 一起按回去,改完当场逐字比一遍),最后默认整体回滚。
|
||
|
||
所以 ``sender=陈鹏``、"需处理"、站内信、以及 ``oa_read`` 上那一整套快照列,全是引擎自己写的,
|
||
脚本一个字都不代笔。
|
||
|
||
默认只让补进来的那一条开火(``--all-rules`` 放开)
|
||
==================================================
|
||
快照上原来那几条规则**当年已经抄过了**,跟着再跑一遍会把它们抄过的人重新算一次:其中看过
|
||
的那批,待阅行早被 ``mark_read`` 搬进 ``oa_read_completed``,而 ``create_reads`` 只认
|
||
``oa_read``,于是会给一个已经看过归档抄送的人凭空再生成一条没看的待阅——那张早就落定的单
|
||
又亮了一次红点。只跑这一条则一分不多:她不在原来那两条的名单里,单独跑与一起跑对她完全等价。
|
||
|
||
幂等:两道闸,都实测过
|
||
======================
|
||
* 引擎那一侧:``apply_activity_cc`` 判"本环节已经抄过谁"(``already``),抄过的人直接跳过;
|
||
真要走到底,``create_reads`` 对**同人同单同类型**也是更新已有那条、不新增行。
|
||
* 脚本这一侧:默认再挡一道——收件人在 ``oa_read`` / ``oa_read_completed`` 里对这张单
|
||
**已经有任何一条 cc 待阅**就不动它(``--all`` 关掉这道闸)。挡的是"已阅档里有一条
|
||
activity 为空的行"这一种:那种行不在 ``oa_read`` 里,引擎看不见,会让它再插一条新的,
|
||
结果同一个人同一张单在待阅和已阅里各躺一份。
|
||
|
||
用法
|
||
====
|
||
::
|
||
|
||
cd backend
|
||
OA_ENV=prod python3 scripts/backfill_archive_cc.py --list # 只点名,一次引擎都不调
|
||
OA_ENV=prod python3 scripts/backfill_archive_cc.py # 干跑:跑完回滚,库里不动
|
||
OA_ENV=prod python3 scripts/backfill_archive_cc.py --work FYBX202611100004 # 干跑一张
|
||
OA_ENV=prod python3 scripts/backfill_archive_cc.py --commit # 真落地
|
||
|
||
要补的规则按 id 认(``--rule-id``,默认 ``cc_mwepfiujecdy``),取的是**当前设计**里那一条的
|
||
原文——快照上没有的那几条规则各有各的来路,脚本不许把设计器里攒下的所有规则一股脑塞回
|
||
一张三年前的单子上。发送人默认 ``chenpeng01``(执行董事这一环的处理人,库里有两位「陈鹏」),
|
||
``--auto-sender`` 改成逐张取该单最后一个经手人。
|
||
|
||
已验
|
||
====
|
||
2026-11-17 在开发库(列已齐)上按同一套流程演过一遍:给备用金流程的归档环节临时挂一条
|
||
``person`` 抄送规则,跑 ``--commit``,事后逐格核对生成的待阅行——
|
||
``activity=pc_archive/归档``、``sender=归档那一刻的审批人``、``requires_action=1``、
|
||
``completed=1``、``work_completed=该单主键``、``creator_person=真发起人``,站内信一条
|
||
「需要您处理:…」;被改过的那份设计快照跑完之后与跑前逐字相同、``update_time`` 也没动。
|
||
再跑第二遍:三张全部跳过(脚本闸);带 ``--all`` 绕过脚本闸再跑:引擎报「已经抄过」,
|
||
一条都不新增。演完的三条测试数据与那条临时规则都已撤干净。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import copy
|
||
import sys
|
||
from pathlib import Path
|
||
|
||
sys.path.insert(0, str(Path(__file__).resolve().parents[0].parent))
|
||
|
||
from sqlalchemy import func, select, text # noqa: E402
|
||
|
||
from app import models # noqa: E402
|
||
from app.db import SessionLocal # noqa: E402
|
||
from app.db import engine as db_engine # noqa: E402
|
||
from app.engine import definition as definition_module # noqa: E402
|
||
from app.engine import engine as engine_module # noqa: E402
|
||
from app.service import channels, org # noqa: E402
|
||
|
||
#: 出问题的那条流程与那个归档环节
|
||
PROCESS = "费用报销流程"
|
||
ARCHIVE_ACTIVITY = "cr_archive"
|
||
#: 要补进去的那条抄送规则:设计器里现在挂在 cr_archive 上的第三条(抄给何凝香、需处理)
|
||
CC_RULE_ID = "cc_mwepfiujecdy"
|
||
#: 归档那一刻按按钮的人 = 执行董事这一环的处理人。库里有两个「陈鹏」,走这条线的是 chenpeng01
|
||
SENDER = "chenpeng01"
|
||
#: 本脚本认的库:防止 OA_ENV 忘了设、连上开发库把干跑当成已经补过
|
||
EXPECT_DATABASE = "unis_oa_prod"
|
||
|
||
|
||
def rule_summary(rule: dict) -> str:
|
||
"""把一条抄送规则压成一行给人看:抄给谁、要不要处理。"""
|
||
targets = "、".join(
|
||
f"{item.get('type')}:{'/'.join(str(x) for x in (item.get('data') or [])) or '-'}"
|
||
for item in (rule.get("taskValues") or [])
|
||
if isinstance(item, dict)
|
||
) or (str(rule.get("taskScript") or "").strip() and "script") or "(空)"
|
||
return f"{rule.get('id') or '(无 id)'} when={rule.get('when') or 'arrive'} 抄给 {targets}" + \
|
||
(" 需处理" if rule.get("requiresAction") else "")
|
||
|
||
|
||
def find_process(db, name_or_id: str) -> models.Process | None:
|
||
row = db.get(models.Process, name_or_id)
|
||
if row is not None:
|
||
return row
|
||
return db.execute(select(models.Process).where(models.Process.name == name_or_id)).scalars().first()
|
||
|
||
|
||
def live_cc_rule(db, process_id: str, activity_id: str, rule_id: str) -> dict | None:
|
||
"""当前设计(``oa_activity``)里那条要补的抄送规则原文。"""
|
||
activity = db.get(models.Activity, activity_id)
|
||
if activity is None or activity.process != process_id:
|
||
return None
|
||
for rule in (activity.config or {}).get("ccRules") or []:
|
||
if isinstance(rule, dict) and str(rule.get("id") or "") == rule_id:
|
||
return rule
|
||
return None
|
||
|
||
|
||
def activity_entry(payload: dict, activity_id: str) -> dict | None:
|
||
"""在冻结快照那份 JSON 里找 ``cr_archive`` 那一项(形状见 ``definition._to_payload``)。"""
|
||
activities = (payload or {}).get("activities") or []
|
||
if isinstance(activities, dict): # 老快照可能是 {id: 行},两种形状都认
|
||
activities = list(activities.values())
|
||
for item in activities:
|
||
if isinstance(item, dict) and str(item.get("id") or "") == activity_id:
|
||
return item
|
||
return None
|
||
|
||
|
||
def cc_recipients(db, work_id: str) -> set[str]:
|
||
"""这张单上已经有 cc 待阅的人(待阅 + 已阅两张表一起看)。"""
|
||
out: set[str] = set()
|
||
for model in (models.Read, models.ReadCompleted):
|
||
out |= set(db.execute(
|
||
select(model.identity).where(model.work == work_id, model.read_type == "cc")
|
||
).scalars().all())
|
||
return out
|
||
|
||
|
||
def raw_snapshot(db, snapshot_id: str) -> tuple[str, str]:
|
||
"""快照行此刻的 ``definition`` 原文与 ``update_time``,用来证明"改回来了"。"""
|
||
row = db.execute(
|
||
text("select definition, update_time from oa_process_snapshot where id = :i"), {"i": snapshot_id}
|
||
).first()
|
||
return (str(row[0]), str(row[1])) if row else ("", "")
|
||
|
||
|
||
def last_approver(db, work_id: str) -> str:
|
||
"""这张单最后一个经手人(``--auto-sender`` 用):已办里时间最新的那条。"""
|
||
return db.execute(
|
||
select(models.TaskCompleted.identity)
|
||
.where(models.TaskCompleted.work == work_id)
|
||
.order_by(models.TaskCompleted.update_time.desc(), models.TaskCompleted.id.desc())
|
||
).scalars().first() or ""
|
||
|
||
|
||
def counts(db, work_id: str) -> dict:
|
||
"""这张单上待阅 / 站内信 / 渠道投递的条数,跑前跑后各问一次,报的是差值。
|
||
|
||
站内信那两列是历史累计的:不这么问,一张早就抄过好几个人的单子上会报出
|
||
"站内信 5 条",而这一趟其实只新增了 1 条。
|
||
"""
|
||
return {
|
||
"reads": count_rows(db, models.Read, work=work_id),
|
||
"notices": count_rows(db, models.Notification, work=work_id, type="read"),
|
||
"queued": count_rows(db, models.NotifyDelivery, work=work_id),
|
||
}
|
||
|
||
|
||
def count_rows(db, model, **filters) -> int:
|
||
statement = select(func.count()).select_from(model)
|
||
for column, value in filters.items():
|
||
statement = statement.where(getattr(model, column) == value)
|
||
return int(db.execute(statement).scalar() or 0)
|
||
|
||
|
||
def select_works(db, process_id: str, args) -> list[models.WorkCompleted]:
|
||
statement = (
|
||
select(models.WorkCompleted)
|
||
.where(models.WorkCompleted.process == process_id)
|
||
.order_by(models.WorkCompleted.finish_time)
|
||
)
|
||
rows = list(db.execute(statement).scalars().all())
|
||
wanted = {str(item).strip() for item in args.work if str(item).strip()}
|
||
if wanted:
|
||
rows = [row for row in rows if row.serial in wanted or row.id in wanted]
|
||
if args.since:
|
||
rows = [row for row in rows if str(row.finish_time)[:10] >= args.since]
|
||
if args.until:
|
||
rows = [row for row in rows if str(row.finish_time)[:10] <= args.until]
|
||
return rows
|
||
|
||
|
||
def backfill_one(db, work, *, activity_id: str, rule: dict, sender: str, args) -> str:
|
||
"""给一张归档单补抄。返回一行给人看的结论;真正的写入都由引擎做。"""
|
||
if not work.design_snapshot:
|
||
return "跳过:这张单没有冻结设计快照(老单),现读的是当前设计,不动"
|
||
snapshot = db.get(models.ProcessSnapshot, work.design_snapshot)
|
||
if snapshot is None:
|
||
return f"跳过:快照行 {work.design_snapshot} 已经不在了"
|
||
if not isinstance(snapshot.definition, dict):
|
||
return "跳过:快照内容不是一个能改的 JSON 对象"
|
||
original_payload = snapshot.definition
|
||
if activity_entry(original_payload, activity_id) is None:
|
||
return f"跳过:这一版设计里根本没有 {activity_id} 环节"
|
||
entry_rules = ((activity_entry(original_payload, activity_id) or {}).get("config") or {}).get("ccRules") or []
|
||
if any(isinstance(item, dict) and str(item.get("id") or "") == str(rule.get("id")) for item in entry_rules):
|
||
return "跳过:这一版设计上已经有这条规则(当年就该抄到了)"
|
||
|
||
# 收件人在不在场:引擎只认 oa_read,已阅档里那一条它看不见,会让 create_reads 再插一条新的,
|
||
# 于是同一个人同一张单在待阅与已阅里各躺一份。默认挡掉,--all 放开。
|
||
already = cc_recipients(db, work.id)
|
||
if not args.all and _already_have_all_targets(db, already, rule):
|
||
return "跳过:收件人在这张单上已经有待阅(含已阅档),--all 可强跑"
|
||
if args.list:
|
||
targets = "、".join(person_targets(db, rule)) or "(要引擎现算)"
|
||
return f"待补抄:这一条要抄给 {targets}(该单上已有 {len(already)} 人有过待阅;--list 不调引擎)"
|
||
|
||
snapshot_before = raw_snapshot(db, snapshot.id)
|
||
update_time_before = snapshot.update_time
|
||
actor_account = last_approver(db, work.id) if args.auto_sender else sender
|
||
person = org.person_by_identity(db, actor_account)
|
||
if person is None:
|
||
return f"跳过:认不出抄送名义上的发送人 {actor_account}"
|
||
actor = engine_module.Actor.from_ref(db, person)
|
||
|
||
# WorkCompleted 没有 variables 这一列,而引擎那句 _context 直接读 work.variables
|
||
# (运行态传的是 Work,归档件是这一版脚本第一次拿它去走这条路):归档件本来也没有
|
||
# 流程变量可给,补一个空的实例属性,不写库。
|
||
if not hasattr(work, "variables"):
|
||
work.variables = {}
|
||
|
||
payload = copy.deepcopy(original_payload)
|
||
_inject(payload, activity_id, rule, not args.all_rules)
|
||
snapshot.definition = payload
|
||
db.flush()
|
||
definition_module.forget_snapshots() # 缓存里那份定义带着旧规则,不丢就白改
|
||
try:
|
||
definition = definition_module.for_work(db, work)
|
||
activity = definition.activity(activity_id)
|
||
if activity is None:
|
||
return "跳过:改完之后定义里读不出这个环节"
|
||
arriving = engine_module.cc_rules(activity, "arrive")
|
||
if not any(str(item.get("id") or "") == str(rule.get("id")) for item in arriving):
|
||
return "跳过:注入的规则没被 cc_rules(when=arrive) 认出来"
|
||
if args.no_channel:
|
||
channels.enqueue_for = lambda *_a, **_k: 0
|
||
tally0 = counts(db, work.id)
|
||
created = engine_module.apply_activity_cc(db, work, activity, actor, "arrive")
|
||
tally1 = counts(db, work.id)
|
||
finally:
|
||
if args.no_channel:
|
||
channels.enqueue_for = _REAL_ENQUEUE
|
||
snapshot.definition = original_payload
|
||
db.flush()
|
||
# onupdate 会把 update_time 抬一格:内容按回去之后把这一格也按回去,
|
||
# 让这一趟在快照表上留下的痕迹真的是零。
|
||
snapshot.update_time = update_time_before
|
||
db.flush()
|
||
definition_module.forget_snapshots()
|
||
|
||
snapshot_after = raw_snapshot(db, snapshot.id)
|
||
if snapshot_after != snapshot_before:
|
||
raise SystemExit(f"{work.serial} 快照没改回去,终止(提交前)")
|
||
if not created:
|
||
return "无改动:引擎判这一条已经抄过(already),或没解析出收件人"
|
||
fresh = tally1["reads"] - tally0["reads"]
|
||
notices = tally1["notices"] - tally0["notices"]
|
||
queued = tally1["queued"] - tally0["queued"]
|
||
people = "、".join(
|
||
f"{row.identity_name or row.identity}{'(需处理)' if row.requires_action else ''}"
|
||
f"@{row.activity or '-'}"
|
||
for row in created
|
||
)
|
||
return (f"补抄 {len(created)} 人(新增待阅 {fresh} 条、更新 {len(created) - fresh} 条):"
|
||
f"{people}|sender={actor.person_name}|站内信 {notices} 条|渠道投递 {queued} 条")
|
||
|
||
|
||
def _inject(payload: dict, activity_id: str, rule: dict, only: bool) -> None:
|
||
"""把那条规则放进快照 JSON 里 cr_archive 的 ccRules(就地改,改的是副本)。
|
||
|
||
``only`` 是默认:这一趟**只让这一条规则开火**。归档环节上另外那几条当年已经抄过了,
|
||
再跟着跑一遍会把它们抄过的人重新算一次——而其中看过的那批,待阅行早就被
|
||
``mark_read`` 搬进 ``oa_read_completed``,``create_reads`` 只认 ``oa_read``,
|
||
于是会给一个**已经看过归档抄送的人**凭空再生一条没看的待阅:单子的红点重新亮起来,
|
||
看上去像这张单又回来找他了。不 ``only``(``--all-rules``)就是字面意义上那次
|
||
"注入之后再走一遍办结抄送",那几条老规则一起重跑。
|
||
"""
|
||
entry = activity_entry(payload, activity_id) or {}
|
||
config = entry.get("config")
|
||
if not isinstance(config, dict):
|
||
config = {}
|
||
entry["config"] = config
|
||
config["ccRules"] = [copy.deepcopy(rule)] if only else \
|
||
list(config.get("ccRules") or []) + [copy.deepcopy(rule)]
|
||
|
||
|
||
def person_targets(db, rule: dict) -> list[str]:
|
||
"""这条规则里写死的那批人(``type=person``),认得出的才回来。
|
||
|
||
只对这一种写法给结论——角色 / 部门 / 上级 / 脚本要连着当次的表单数据才算得出来,
|
||
那种活交给引擎自己,脚本不在这儿猜一份可能不一样的名单。
|
||
"""
|
||
identities = [
|
||
str(item) for value in (rule.get("taskValues") or []) if isinstance(value, dict)
|
||
and str(value.get("type") or "").lower() == "person"
|
||
for item in (value.get("data") or [])
|
||
]
|
||
return [ref for ref in identities if org.person_by_identity(db, ref) is not None]
|
||
|
||
|
||
def _already_have_all_targets(db, already: set[str], rule: dict) -> bool:
|
||
"""预判:这条规则的收件人是不是**全部**已经在场(一张都没落下的才叫"不用补")。"""
|
||
resolved = person_targets(db, rule)
|
||
return bool(resolved) and all(ref in already for ref in resolved)
|
||
|
||
|
||
_REAL_ENQUEUE = channels.enqueue_for
|
||
|
||
|
||
UPGRADE_DIR = Path(__file__).resolve().parents[2] / "sql" / "upgrade"
|
||
|
||
#: 这一趟要读写到的表:ORM 里有、库里还没有的列,一律算"后端比库新"
|
||
CHECKED_MODELS = (
|
||
models.Process, models.Activity, models.ProcessSnapshot, models.WorkCompleted,
|
||
models.TaskCompleted, models.Read, models.ReadCompleted, models.Notification,
|
||
models.NotifyDelivery, models.User,
|
||
)
|
||
|
||
|
||
def schema_gaps(db) -> list[str]:
|
||
"""ORM 映射里有、库里还查不到的列,逐条列出(含该跑哪个升级脚本)。
|
||
|
||
这一刀不是洁癖:``create_reads`` 的 INSERT 与待阅的 SELECT 都带着整行列清单,生产档
|
||
``auto_create_schema=false`` 不补列——列没加就跑,报错是 ``(1054, Unknown column
|
||
'oa_read.creator_person')``,而那一长串语句 dump 出来远不如"先跑
|
||
``sql/upgrade/20261117_read_creator_snapshot.sql``"这句话有用。
|
||
"""
|
||
present = {
|
||
(str(row[0]), str(row[1]))
|
||
for row in db.execute(text("select table_name, column_name from information_schema.columns "
|
||
"where table_schema = database()")).all()
|
||
}
|
||
gaps: list[str] = []
|
||
for model in CHECKED_MODELS:
|
||
table = model.__tablename__
|
||
for column in model.__table__.columns:
|
||
if (table, column.name) not in present:
|
||
gaps.append(f"{table}.{column.name} <- {_upgrade_file_for(table, column.name)}")
|
||
return gaps
|
||
|
||
|
||
def _upgrade_file_for(table: str, column: str) -> str:
|
||
"""在 ``sql/upgrade/*.sql`` 里找加这一列的那份脚本,找不到就说该手工建。"""
|
||
if UPGRADE_DIR.is_dir():
|
||
for path in sorted(UPGRADE_DIR.glob("*.sql")):
|
||
body = path.read_text(encoding="utf-8", errors="replace")
|
||
if f"`{column}`" in body and f"`{table}`" in body:
|
||
return str(path.relative_to(UPGRADE_DIR.parents[1]))
|
||
return "(没有现成的升级脚本,按 sql/schema.sql 手工补列)"
|
||
|
||
|
||
def main() -> int:
|
||
parser = argparse.ArgumentParser(description="按快照给已归档单据补一条归档抄送(默认干跑)")
|
||
parser.add_argument("--process", default=PROCESS, help="流程名或 id(默认:费用报销流程)")
|
||
parser.add_argument("--activity", default=ARCHIVE_ACTIVITY, help="归档环节 id(默认 cr_archive)")
|
||
parser.add_argument("--rule-id", default=CC_RULE_ID, help="从当前设计里取哪条抄送规则补进去")
|
||
parser.add_argument("--sender", default=SENDER, help="抄送名义上的发送人账号(默认 chenpeng01)")
|
||
parser.add_argument("--auto-sender", action="store_true",
|
||
help="逐张取该单最后一个经手人当发送人,不统一用 --sender")
|
||
parser.add_argument("--work", action="append", default=[], metavar="单号或 id",
|
||
help="只处理这几张(可重复)")
|
||
parser.add_argument("--since", default="", metavar="YYYY-MM-DD", help="只看这个日期之后归档的")
|
||
parser.add_argument("--until", default="", metavar="YYYY-MM-DD", help="只看到这一天归档的")
|
||
parser.add_argument("--all", action="store_true",
|
||
help="收件人已经有待阅的也照跑(默认跳过,避免待阅 / 已阅各一份)")
|
||
parser.add_argument("--all-rules", action="store_true",
|
||
help="注入之外,让快照上原有的那几条归档抄送也重跑一遍"
|
||
"(默认只让补进来的这一条开火,见 _inject)")
|
||
parser.add_argument("--no-channel", action="store_true", help="只落站内信,不排企微那类渠道投递")
|
||
parser.add_argument("--list", action="store_true",
|
||
help="只点名哪些单子会补、哪些会跳过,一次引擎都不调"
|
||
"(库还没升级时用它看清单,配 --skip-schema-check)")
|
||
parser.add_argument("--limit", type=int, default=0, help="最多处理几张")
|
||
parser.add_argument("--commit", action="store_true", help="真提交(默认干跑,跑完整体回滚)")
|
||
parser.add_argument("--expect-database", default=EXPECT_DATABASE,
|
||
help=f"只连这个库(默认 {EXPECT_DATABASE});空串不校验")
|
||
parser.add_argument("--any-database", action="store_true", help="不校验库名")
|
||
parser.add_argument("--skip-schema-check", action="store_true",
|
||
help="明知库里少列也要跑(多半会在第一条 SQL 上撞 1054)")
|
||
args = parser.parse_args()
|
||
if args.any_database:
|
||
args.expect_database = ""
|
||
if args.list and args.commit:
|
||
# --list 的口径就是"一次引擎都不调",不该手滑把 --commit 一起带上落下去
|
||
print("--list 不调引擎,--commit 忽略")
|
||
args.commit = False
|
||
|
||
database = str(db_engine.url.database or "")
|
||
url = db_engine.url.render_as_string(hide_password=True)
|
||
if args.expect_database and database != args.expect_database:
|
||
raise SystemExit(f"连的是 {database or '(未知库)'},不是 {args.expect_database}。"
|
||
f"确认一下 OA_ENV(加 --any-database 可跳过这道校验)\n {url}")
|
||
print(f"库:{url}")
|
||
if not args.commit:
|
||
print("模式:干跑(所有写入跑完回滚,库里一个字都不动);要落地加 --commit")
|
||
|
||
with SessionLocal() as db:
|
||
if not args.skip_schema_check:
|
||
gaps = schema_gaps(db)
|
||
if gaps:
|
||
raise SystemExit(
|
||
"库比后端旧,缺这些列(先在生产库上把对应的 sql/upgrade 脚本整段跑完):\n "
|
||
+ "\n ".join(gaps)
|
||
)
|
||
process = find_process(db, args.process)
|
||
if process is None:
|
||
raise SystemExit(f"库里没有这条流程:{args.process}")
|
||
rule = live_cc_rule(db, process.id, args.activity, args.rule_id)
|
||
if rule is None:
|
||
raise SystemExit(f"当前设计的 {args.activity} 上找不到抄送规则 {args.rule_id},"
|
||
f"先在设计器里把那条加好,或把 --rule-id 指到真的那一条")
|
||
print(f"流程:{process.name}({process.id})")
|
||
print(f"环节:{args.activity}")
|
||
print(f"补入:{rule_summary(rule)}")
|
||
if args.auto_sender:
|
||
print("发送人:逐张取该单最后一个经手人(--auto-sender)")
|
||
else:
|
||
person = org.person_by_identity(db, args.sender)
|
||
if person is None:
|
||
raise SystemExit(f"认不出发送人账号 {args.sender}")
|
||
print(f"发送人:{person.display_name}({args.sender})")
|
||
|
||
works = select_works(db, process.id, args)
|
||
if args.limit:
|
||
works = works[: args.limit]
|
||
print(f"\n候选:{len(works)} 张归档单\n" + "-" * 72)
|
||
done = todo = skipped = 0
|
||
for work in works:
|
||
line = backfill_one(db, work, activity_id=args.activity, rule=rule, sender=args.sender, args=args)
|
||
tag = "ok " if line.startswith("补抄") else ("todo" if line.startswith("待补抄") else "skip")
|
||
done += tag == "ok "
|
||
todo += tag == "todo"
|
||
skipped += tag == "skip"
|
||
print(f"[{tag}] {work.serial} {work.finish_time:%Y-%m-%d %H:%M} "
|
||
f"发起人={work.creator_person} {line}")
|
||
print("-" * 72)
|
||
tail = f",其中 {todo} 张待补抄" if todo else ""
|
||
print(f"合计:补抄 {done} 张,跳过 {skipped} 张,候选 {len(works)} 张{tail}")
|
||
|
||
# 一张一开火、最后一笔提交:中途任何一张抛异常(连不上、快照读不出、引擎判错)
|
||
# 都是整批不落地,不会留下"九张里补了四张、快照还挂着临时规则"那种半截状态。
|
||
if args.commit:
|
||
db.commit()
|
||
print("已提交(整批一笔)。")
|
||
else:
|
||
db.rollback()
|
||
print("已回滚——库里没动。核对无误后加 --commit 再跑一遍。")
|
||
return 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
sys.exit(main())
|