unis-oa/backend/scripts/set_approvers.py

277 lines
13 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
"""测试环境专用:把流程审批环节的审批人统一改成一个来源(默认发起人)。
生产配的是真岗位角色、部门主管、指定人,测试库里那些人往往一个都不在——单据发到
「财务经理」就挂在没人认领的待办上。这一条把审批环节的审批人整体换成发起人本人
(``taskValues = [{"type": "creator", "data": []}]``,与设计器保存的形状一字不差),
自己发自己审,一条流程点到底。
改的是设计数据(``oa_activity.config``),只动 ``type=manual`` 的审批环节**顶层**那一份
``taskValues``:抄送规则 ``ccRules`` 里同名的 ``taskValues`` 说的是抄送给谁,不算审批人,
不碰;环节上的表单权限、退回配置、外部审批接口、空审批人兜底一概原样。
**顺带必须处理的开关**:审批人换成发起人之后,"同一个审批人自动放行"那几档会把这些
环节悄悄吃掉,改了等于没改——
* ``skipStarter``(环节级与流程级):发起人自己不重复审批;
* ``dedup``:同一审批人前面批过就自动通过;
* ``dedupAhead``:同一审批人后面还要批时跳过前面这一环。
默认把它们关掉,让每个环节都真的停在发起人手上。想让流程一路自动跑到底就别关:
加 ``--keep-auto-pass``。
在途单据不受影响:发起那一刻设计已经冻结在 ``oa_process_snapshot`` 上,走的还是老配置。
要退回生产原来的审批人配置,直接重跑 ``migrate_design.py --apply``(它以生产为准)。
python3 scripts/set_approvers.py # 干跑:列每个环节要改成什么
python3 scripts/set_approvers.py --apply # 真改(默认测试档 dev)
python3 scripts/set_approvers.py --process 印章 # 只改名字带「印章」的流程
python3 scripts/set_approvers.py --keep-auto-pass # 只换审批人,不动自动放行开关
python3 scripts/set_approvers.py --kind role --value 财务经理 # 换成别的口径
python3 scripts/set_approvers.py --restore ../backups/approvers-XXXX.json.gz
"""
from __future__ import annotations
import argparse
import gzip
import json
import sys
from datetime import datetime
from pathlib import Path
from typing import Any
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from sqlalchemy import update # noqa: E402
from sqlalchemy.orm import sessionmaker # noqa: E402
import migrate_design as md # noqa: E402 同一套连库 / 备份 / 清缓存 / 校验口径
TABLES = md.TABLES
BACKUP_DIR = md.BACKUP_DIR
#: 只有这种环节是"审批环节"(会发待办);begin / end / choice / script 不算
APPROVAL_NODE = "manual"
#: 审批人来源的中文名,报告里要说清楚这一格从哪儿取人
KIND_LABELS = {
"creator": "发起人",
"person": "指定人",
"role": "岗位角色",
"post": "岗位角色",
"unit": "部门",
"group": "分组",
"identity": "身份",
"form": "按表单字段取值",
"prev": "上一环节处理人",
"prevunit": "上一环节处理人所在部门",
"prevLeader": "上一环节处理人的上级",
"prevUnitManager": "上一环节处理人所在部门负责人",
"creatorLeader": "发起人的上级",
"creatorLeaderChain": "发起人的多级上级",
"creatorTeamLeader": "发起人的科室负责人",
"creatorUnitManager": "发起人所在部门负责人",
"creatorParentUnitManager": "发起人上级部门负责人",
"unitManager": "指定部门负责人",
}
#: 会把这些环节悄悄放行的开关:环节级 skipStarter,流程级这三项
FLOW_AUTO_PASS = ("skipStarter", "dedup", "dedupAhead")
def describe(rows: Any) -> str:
"""把一份 ``taskValues`` 说成人话:``岗位角色「财务经理」+ 发起人所在部门负责人``。"""
parts: list[str] = []
for row in rows or []:
if not isinstance(row, dict):
parts.append(str(row))
continue
kind = str(row.get("type") or "")
label = KIND_LABELS.get(kind, kind or "未配置")
data = [str(item) for item in (row.get("data") or []) if str(item)]
parts.append(f"{label}「{'、'.join(data)}」" if data else label)
return " + ".join(parts) or "(空)"
class Plan:
def __init__(self) -> None:
#: 环节 id -> (环节行, 新 config, 说明)
self.nodes: dict[str, tuple[dict, dict, list[str]]] = {}
#: 流程 id -> (流程行, 新 approval_config, 说明)
self.flows: dict[str, tuple[dict, dict, list[str]]] = {}
@property
def touched_processes(self) -> list[str]:
ids = {row["process"] for row, _, _ in self.nodes.values()}
return sorted(ids | set(self.flows))
def build_plan(scope: dict, kind: str, values: list[str], clear_auto_pass: bool) -> Plan:
"""按「审批人 = 某个来源」算出每个审批环节要改成什么样。"""
plan = Plan()
wanted = [{"type": kind, "data": [str(item) for item in values]}]
for row in scope["activities"].values():
if row["type"] != APPROVAL_NODE or row["process"] not in scope["processes"]:
continue
config = dict(row.get("config") or {})
notes: list[str] = []
before, after = describe(config.get("taskValues")), describe(wanted)
if before != after:
config["taskValues"] = [dict(item) for item in wanted]
notes.append(f"审批人 {before} → {after}")
if clear_auto_pass and config.get("skipStarter"):
config["skipStarter"] = False
notes.append("关掉「发起人自己不再审批」(不然这一环直接自动过)")
if notes:
plan.nodes[row["id"]] = (row, config, notes)
if not clear_auto_pass:
return plan
for pid, process in scope["processes"].items():
approval = dict(process.get("approval_config") or {})
notes: list[str] = []
for key in FLOW_AUTO_PASS:
value = approval.get(key)
if key == "skipStarter":
if value:
approval[key] = False
notes.append("「发起人自己不重复审批」关掉")
elif value and str(value) != "none":
approval[key] = "none"
label = "同一审批人前面批过就自动通过" if key == "dedup" else "同一审批人后面还要批时跳过前面这一环"
notes.append(f"「{label}」{value} → none")
if notes:
plan.flows[pid] = (process, approval, notes)
return plan
def report(plan: Plan, scope: dict, conf: dict, kind: str) -> None:
print(f"目标库(写) {md.label(conf)}")
print(f"审批人来源 {KIND_LABELS.get(kind, kind)}\n")
if not plan.nodes and not plan.flows:
print("所有审批环节已经是这个口径了,一行都不用改。")
return
for pid, process in sorted(scope["processes"].items(), key=lambda item: str(item[1]["name"])):
nodes = [item for item in plan.nodes.values() if item[0]["process"] == pid]
flow = plan.flows.get(pid)
if not nodes and not flow:
continue
total = sum(1 for row in scope["activities"].values()
if row["process"] == pid and row["type"] == APPROVAL_NODE)
print(f"\n{process['name']}(审批环节 {total} 个,这一趟动 {len(nodes)} 个)")
for row, _, notes in sorted(nodes, key=lambda item: item[0]["order_number"]):
print(f" - {row['name']}:" + ";".join(notes))
if flow:
print(" · 流程级:" + ";".join(flow[2]))
print(f"\n合计:审批环节 {len(plan.nodes)} 个、流程 {len(plan.flows)} 条要写")
def apply_plan(plan: Plan, profile: str) -> Path:
"""备份原值 + 一个事务写完。"""
engine = md.connect(md.db_conf(profile))
session = sessionmaker(bind=engine)()
path = BACKUP_DIR / f"approvers-{datetime.now().strftime('%Y%m%d-%H%M%S')}.json.gz"
payload = {
"written_at": datetime.now().isoformat(timespec="seconds"),
"profile": profile,
"note": "set_approvers.py 改动前的原值;--restore 按这个退回",
"nodes": {aid: row.get("config") or {} for aid, (row, _, _) in plan.nodes.items()},
"flows": {pid: row.get("approval_config") or {} for pid, (row, _, _) in plan.flows.items()},
}
path.parent.mkdir(parents=True, exist_ok=True)
with gzip.open(path, "wt", encoding="utf-8") as handle:
json.dump(payload, handle, ensure_ascii=False)
try:
table = TABLES["oa_activity"]
for aid, (_, config, _) in plan.nodes.items():
session.execute(update(table).where(table.c.id == aid).values(config=config))
table = TABLES["oa_process"]
for pid, (_, approval, _) in plan.flows.items():
session.execute(update(table).where(table.c.id == pid).values(approval_config=approval))
session.commit()
except Exception:
session.rollback()
raise
finally:
session.close()
return path
def restore(path: Path, profile: str) -> None:
"""把审批人与自动放行开关退回备份那一刻。"""
with gzip.open(path, "rt", encoding="utf-8") as handle:
payload = json.load(handle)
conf = md.db_conf(profile)
engine = md.connect(conf)
md.probe(engine, conf)
session = sessionmaker(bind=engine)()
try:
table = TABLES["oa_activity"]
for aid, config in (payload.get("nodes") or {}).items():
session.execute(update(table).where(table.c.id == aid).values(config=config))
table = TABLES["oa_process"]
for pid, approval in (payload.get("flows") or {}).items():
session.execute(update(table).where(table.c.id == pid).values(approval_config=approval))
session.commit()
except Exception:
session.rollback()
raise
finally:
session.close()
print(f"已按 {path.name} 退回:审批环节 {len(payload.get('nodes') or {})} 个、"
f"流程 {len(payload.get('flows') or {})} 条({md.label(conf)})")
def main(argv: list[str]) -> int:
parser = argparse.ArgumentParser(description="批量设置测试环境流程审批环节的审批人")
parser.add_argument("--profile", default="dev", help="改哪一档的库,默认 dev(测试档)")
parser.add_argument("--kind", default="creator", help="审批人来源,默认 creator(发起人)")
parser.add_argument("--value", action="append", default=[],
help="来源取值,role / unit / person / group / form 才需要;可重复")
parser.add_argument("--process", nargs="*", default=[], help="只改名字里带这些词的流程")
parser.add_argument("--keep-auto-pass", action="store_true",
help="只换审批人,不动 skipStarter / dedup(这些环节会被自动放行)")
parser.add_argument("--restore", metavar="备份文件", help="按备份退回改动前")
parser.add_argument("--apply", action="store_true", help="真写;默认只干跑")
args = parser.parse_args(argv)
if args.restore:
restore(Path(args.restore), args.profile)
return 0
need_value = {"role": "岗位角色名", "unit": "部门名", "group": "分组名",
"person": "登录账号", "form": "表单字段 key"}
if args.kind in need_value and not args.value:
raise SystemExit(f"--kind {args.kind} 要用 --value 给出{need_value[args.kind]}")
conf = md.db_conf(args.profile)
engine = md.connect(conf)
md.probe(engine, conf)
processes = {row["id"]: row for row in md.fetch(engine, "oa_process")
if not args.process or any(word in str(row["name"]) for word in args.process)}
if not processes:
print("--process 一个流程都没圈到,先别写了")
return 1
scope = {"processes": processes, "activities": md.by_key(md.fetch(engine, "oa_activity"), "id")}
plan = build_plan(scope, args.kind, args.value, not args.keep_auto_pass)
report(plan, scope, conf, args.kind)
if not args.apply:
print(f"\n干跑结束:{len(plan.nodes) + len(plan.flows)} 行待写。加 --apply 落地(写之前先备份)。")
return 0
if not plan.nodes and not plan.flows:
return 0
path = apply_plan(plan, args.profile)
print(f"\n已写入 {md.label(conf)},原值备份在 {path.relative_to(md.BACKEND.parent)}")
print(f" 要退回:python3 scripts/set_approvers.py --profile {args.profile} --restore {path}")
print(md.invalidate_cache(engine, args.profile, plan.touched_processes))
issues = md.verify(engine, plan.touched_processes)
print("设计器校验:" + ("全部通过" if not issues else f"{len(issues)} 条问题"))
for line in issues[:10]:
print(f" ! {line}")
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))