683 lines
31 KiB
Python
683 lines
31 KiB
Python
#!/usr/bin/env python3
|
||
"""把库里所有「人员」与「组织」信息清干净:账号、身份、部门,以及挂在它们身上的引用。
|
||
|
||
删除口径(默认干跑,``--apply`` 才动手):
|
||
· ``users`` 整表清空,只留内置超管(``system.admin_account`` 指着的那个号)。一个都不留
|
||
有两个后果:谁都进不去,而且 ``users`` 空了下次启动会把演示组织和演示人员重新种回来
|
||
(见 ``app/seed.py::run``)。连它也删用 ``--all-people --yes-lockout``。
|
||
· ``oa_unit`` 全清;这些人身上的权限角色绑定、登录续期令牌、流程代理、
|
||
流程交接,以及待办、待阅、通知、草稿、批注、附件里归属他们的行一起删。
|
||
· 会议与日程按「归属人已清」删;网盘文件只删归属人被清的那些。
|
||
· ``oa_hub_sync_run`` 同步历史整表清空:记录里带操作人姓名、人数与部门名。
|
||
|
||
引用不删行,就地抹掉指针,流程设计与审批岗位留壳:
|
||
· ``oa_role.list_auth`` / ``oa_group.list_identity``:只留还认得到的身份 DN;
|
||
· ``oa_activity.config`` / ``oa_process_version.snapshot``:找人规则里等于已清身份 DN 的
|
||
条目剔掉,指向已清部门的名字(``unitManager`` 一类)也剔掉,环节交给 emptyApprover 兜底;
|
||
· ``oa_cms_document.author`` / ``author_identity``、各表 ``creator`` / ``creator_name``:
|
||
人没了就置空,正文与流程定义本身不动;
|
||
· ``oa_dict_item.extra`` 里等于已清部门名的附加值(演示预算科目的 owner)删键;
|
||
· ``oa_system_setting``:``hub_directory`` 那行同步游标删掉,``config:hub`` 的应急账号
|
||
名单只留内置超管,免得下一趟同步照名单把人再认回来。
|
||
|
||
顺手把 Hub 的定时全量与增量同步关掉(``--keep-sync`` 跳过):不关今晚到点就把人拉回来,
|
||
这趟等于白清。「允许定时同步」这一项只在界面上配,所以这一脚相当于替你在界面上那一栏
|
||
点了关闭——想恢复就去「系统设置 → 同步定时任务」把它打开;界面上的「立即同步」一直不受影响。
|
||
|
||
动手前整包备份成 gzip JSON(删除的行 + 被改行的改前值),``--restore`` 按行还原。
|
||
|
||
python3 scripts/purge_people_org.py # 干跑,只报数
|
||
python3 scripts/purge_people_org.py --apply # 真删
|
||
python3 scripts/purge_people_org.py --logs --apply # 连操作日志一起清
|
||
python3 scripts/purge_people_org.py --restore ../backups/purge-people-org-xxx.json.gz
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import gzip
|
||
import json
|
||
import sys
|
||
from datetime import date, datetime
|
||
from pathlib import Path
|
||
from typing import Any, Iterator
|
||
|
||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||
|
||
from sqlalchemy import select, text # noqa: E402
|
||
|
||
from app import db, dbconfig, models # noqa: E402
|
||
from app.config import settings # noqa: E402
|
||
from app.service import org as org_service # noqa: E402
|
||
|
||
BACKUP_DIR = Path(__file__).resolve().parents[2] / "backups"
|
||
|
||
#: 这几张表整表清空:记录本身就是人员/组织的痕迹,不按人筛
|
||
ALL_ROW_TABLES = ("oa_unit", "oa_hub_sync_run")
|
||
|
||
#: 「这一列存的是 ``users.id``」:命中已清人员就删整行
|
||
PERSON_COLUMNS: dict[str, tuple[str, ...]] = {
|
||
"users": ("id",),
|
||
"oa_person_auth_role": ("person_id",),
|
||
"oa_refresh_token": ("person",),
|
||
"oa_agent": ("person_id",),
|
||
"oa_handover": ("from_person", "to_person"),
|
||
"oa_notification": ("person",),
|
||
"oa_draft": ("person",),
|
||
"oa_attachment": ("person",),
|
||
"oa_work_comment": ("person",),
|
||
"oa_task": ("person",),
|
||
"oa_task_completed": ("person",),
|
||
"oa_read": ("person",),
|
||
"oa_read_completed": ("person",),
|
||
"oa_work": ("creator",),
|
||
"oa_work_completed": ("creator",),
|
||
"oa_meeting": ("creator",),
|
||
"oa_meeting_attendee": ("person",),
|
||
"oa_schedule": ("owner_person",),
|
||
"oa_file": ("owner_person",),
|
||
"oa_operation_log": ("person",),
|
||
# 收款账户两个键都认(person_id 认人、account 是对外口径,见 models.BankAccount):
|
||
# 删掉的人不该留下收款账户行,哪怕它挂的账号已经被下一个人认领了
|
||
"oa_bank_account": ("person_id",),
|
||
}
|
||
|
||
#: 这几张表只认「还留着的人」:person 查无此人就删(早几轮删人留下的悬空会话令牌)
|
||
KEEP_ONLY_TABLES = ("oa_refresh_token",)
|
||
|
||
#: 人员引用列:全部存登录账号;表里可能还压着历史遗留的身份 DN 写法(那种形状
|
||
#: 从今往后只可能来自备份还原),两种写法都按 :meth:`Scope.dead_ref` 判活。
|
||
IDENTITY_COLUMNS: dict[str, tuple[str, ...]] = {
|
||
"oa_agent": ("identity", "from_identity"),
|
||
"oa_handover": ("from_identity", "to_identity"),
|
||
"oa_notification": ("identity",),
|
||
"oa_draft": ("identity",),
|
||
"oa_work": ("creator_identity",),
|
||
"oa_work_completed": ("creator_identity",),
|
||
"oa_task": ("identity",),
|
||
"oa_task_completed": ("identity",),
|
||
"oa_read": ("identity", "creator_identity", "source_identity"),
|
||
"oa_read_completed": ("identity", "creator_identity", "source_identity"),
|
||
"oa_work_log": ("from_identity",),
|
||
"oa_work_comment": ("identity",),
|
||
"oa_meeting": ("creator_identity",),
|
||
"oa_meeting_attendee": ("identity",),
|
||
"oa_schedule": ("owner",),
|
||
"oa_file": ("owner",),
|
||
"oa_operation_log": ("identity",),
|
||
}
|
||
|
||
#: 「这一列存的是登录账号」:账号不再指向任何留下来的人,就删整行。
|
||
#: 收款账户这张表两个键都查(上面 ``PERSON_COLUMNS`` 里那条按 ``person_id`` 认,这里按账号认):
|
||
#: 早几轮删人留下的悬空行要清干净,否则账号被下一个人认领时,他会凭空继承上一个人的银行卡。
|
||
ACCOUNT_COLUMNS: dict[str, tuple[str, ...]] = {
|
||
"oa_bank_account": ("account",),
|
||
}
|
||
|
||
#: 删除顺序:先挂人的行,再单据,最后才是人员与部门本身
|
||
DELETE_ORDER = (
|
||
"oa_task", "oa_task_completed", "oa_read", "oa_read_completed", "oa_work_log",
|
||
"oa_work_comment", "oa_attachment", "oa_draft", "oa_notification",
|
||
"oa_work", "oa_work_completed",
|
||
"oa_meeting_attendee", "oa_meeting", "oa_schedule", "oa_file",
|
||
"oa_agent", "oa_handover", "oa_refresh_token", "oa_operation_log",
|
||
"oa_person_auth_role", "oa_hub_sync_run", "oa_bank_account",
|
||
"users", "oa_unit",
|
||
)
|
||
|
||
#: 还原顺序:部门 -> 人,再是挂在它们身上的行
|
||
RESTORE_ORDER = ("oa_unit", "users") + tuple(reversed(DELETE_ORDER))
|
||
|
||
#: 找人规则里「直接点人」的来源
|
||
PERSON_KINDS = frozenset({"identity", "person"})
|
||
#: 只有这几种来源的 ``data`` 存的是部门名。岗位「总经理」与部门「总经理」撞名是常态,
|
||
#: 拿部门名去筛 role / group 的选择项会把岗位一起剔掉。
|
||
UNIT_KINDS = frozenset({"unit", "unitManager", "prevUnitManager", "creatorParentUnitManager"})
|
||
|
||
#: 这几列存 JSON,里面可能还藏着身份 DN 或部门名
|
||
JSON_COLUMNS: tuple[tuple[str, str], ...] = (
|
||
("oa_activity", "config"),
|
||
("oa_process_version", "snapshot"),
|
||
("oa_form", "content"),
|
||
("oa_schedule", "shared_identities"),
|
||
("oa_file", "shared_identities"),
|
||
("oa_work_comment", "mentions"),
|
||
)
|
||
|
||
HUB_DIRECTORY_KEY = "hub_directory"
|
||
|
||
BY_TABLE = {
|
||
model.__tablename__: model
|
||
for mapper in db.Base.registry.mappers
|
||
for model in [mapper.class_]
|
||
if hasattr(model, "__tablename__")
|
||
}
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 小工具
|
||
# ---------------------------------------------------------------------------
|
||
|
||
def _jsonable(value: object) -> object:
|
||
return value.isoformat() if isinstance(value, (datetime, date)) else value
|
||
|
||
|
||
def _row_to_dict(obj: Any) -> dict[str, Any]:
|
||
return {col.name: _jsonable(getattr(obj, col.name)) for col in obj.__table__.columns}
|
||
|
||
|
||
def _looks_like_dn(value: object) -> bool:
|
||
"""身份 DN 长这样:``部门路径\\人员\\账号``。不带反斜杠的不当身份看,免得误伤正文。"""
|
||
return "\\" in str(value or "")
|
||
|
||
|
||
class Scope:
|
||
"""这一趟清谁、清到什么程度:谁留下、谁走、哪些身份还算「还在」。"""
|
||
|
||
def __init__(self, session, keep_admin: bool) -> None:
|
||
self.admin_account = settings.admin_account
|
||
admin = session.execute(
|
||
select(models.User).where(models.User.account == self.admin_account)
|
||
).scalar_one_or_none()
|
||
self.keep_person_ids: set[int] = {admin.id} if (keep_admin and admin) else set()
|
||
self.persons = list(session.execute(select(models.User).order_by(models.User.id)).scalars())
|
||
self.doomed_person_ids = {u.id for u in self.persons if u.id not in self.keep_person_ids}
|
||
self._doomed_ids = {str(i) for i in self.doomed_person_ids}
|
||
self.keep_ids_str = {str(i) for i in self.keep_person_ids}
|
||
self.doomed_person_names = {
|
||
u.display_name for u in self.persons
|
||
if u.id in self.doomed_person_ids and u.display_name
|
||
}
|
||
# 「还在的 DN」按留下来的人当前档案现算:身份表已经下线,而配置里那种
|
||
# ``部门\\姓名\\账号`` 的历史写法要能认出"主人还在",否则会被一起剔掉
|
||
kept = [row for row in self.persons if row.id in self.keep_person_ids]
|
||
unit_ids = sorted({row.organization_id for row in kept if row.organization_id})
|
||
paths = dict(
|
||
session.execute(select(models.Unit.id, models.Unit.path).where(
|
||
models.Unit.id.in_(unit_ids or [-1])
|
||
)).all()
|
||
)
|
||
self.alive_dns = {
|
||
org_service.dn_for(
|
||
(paths.get(row.organization_id) or "").rstrip(chr(92)), row.display_name, row.account
|
||
)
|
||
for row in kept
|
||
if row.account
|
||
}
|
||
self.alive_accounts = {
|
||
u.account for u in self.persons if u.id in self.keep_person_ids and u.account
|
||
}
|
||
#: 这一趟要走的人的账号:账号写法的引用列只认这份名单,别拿"查无此号"当死
|
||
self.doomed_accounts = {
|
||
u.account for u in self.persons if u.id not in self.keep_person_ids and u.account
|
||
}
|
||
self.units = list(session.execute(select(models.Unit).order_by(models.Unit.id)).scalars())
|
||
self.doomed_unit_names = {u.name for u in self.units if u.name}
|
||
|
||
def doomed_person(self, value: object) -> bool:
|
||
return str(value or "") in self._doomed_ids
|
||
|
||
def doomed_person_name(self, value: object) -> bool:
|
||
return str(value or "") in self.doomed_person_names
|
||
|
||
def dead_ref(self, value: object) -> bool:
|
||
"""人员引用列还指不指得到留下来的人:账号按账号查,DN 按 DN 查。
|
||
|
||
认人口径只有登录账号(``app/service/personref.py``),``oa_work.creator_identity``
|
||
这一列存的是账号,只按"像不像 DN"判活就永远不会命中——删了人却留下一堆悬空
|
||
单据、待办和未读通知。认不出的写法(手写名单里的姓名、编号)一律不算死引用:
|
||
删错一行的代价比留一行悬空数据大得多。
|
||
"""
|
||
text = str(value or "").strip()
|
||
if not text:
|
||
return False
|
||
if _looks_like_dn(text):
|
||
return text not in self.alive_dns
|
||
return text in self.doomed_accounts
|
||
|
||
def dead_account(self, value: object) -> bool:
|
||
"""这个登录账号还指不指得到留下来的人:账号列里只有账号,不用像 DN 那样先猜形状。"""
|
||
return bool(str(value or "").strip()) and str(value) not in self.alive_accounts
|
||
|
||
def doomed_unit(self, value: object) -> bool:
|
||
return str(value or "") in self.doomed_unit_names
|
||
|
||
|
||
class Ledger:
|
||
"""改了什么、删了什么,先记台账,再决定落不落盘。"""
|
||
|
||
def __init__(self) -> None:
|
||
self.deleted: dict[str, list[dict[str, Any]]] = {}
|
||
self.scrubbed: dict[str, list[dict[str, Any]]] = {}
|
||
self.counts: dict[str, int] = {}
|
||
self.notes: list[str] = []
|
||
|
||
def count(self, key: str, n: int = 1) -> int:
|
||
self.counts[key] = self.counts.get(key, 0) + n
|
||
return self.counts[key]
|
||
|
||
def note(self, message: str) -> None:
|
||
if message not in self.notes:
|
||
self.notes.append(message)
|
||
|
||
def record_delete(self, table: str, rows: list[Any]) -> None:
|
||
self.deleted.setdefault(table, []).extend(_row_to_dict(o) for o in rows)
|
||
self.count(table, len(rows))
|
||
|
||
def record_scrub(self, table: str, obj: Any, key: str, n: int = 1) -> None:
|
||
self.scrubbed.setdefault(table, []).append(_row_to_dict(obj))
|
||
self.count(key, n)
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 要删的行
|
||
# ---------------------------------------------------------------------------
|
||
|
||
def doomed_row(obj: Any, scope: Scope, table: str) -> bool:
|
||
"""这一行是不是属于被清的人 / 已失效的身份 / 整表清空的表。"""
|
||
if table in ALL_ROW_TABLES:
|
||
return True
|
||
if table in KEEP_ONLY_TABLES:
|
||
return str(getattr(obj, "person", "") or "") not in scope.keep_ids_str
|
||
if any(scope.doomed_person(getattr(obj, c, None)) for c in PERSON_COLUMNS.get(table, ())):
|
||
return True
|
||
if any(scope.dead_account(getattr(obj, c, None)) for c in ACCOUNT_COLUMNS.get(table, ())):
|
||
return True
|
||
return any(scope.dead_ref(getattr(obj, c, None)) for c in IDENTITY_COLUMNS.get(table, ()))
|
||
|
||
|
||
def delete_doomed_rows(session, scope: Scope, ledger: Ledger, with_logs: bool) -> None:
|
||
"""按 :data:`DELETE_ORDER` 逐表删,删之前先整行备份进台账。"""
|
||
for table in DELETE_ORDER:
|
||
if table == "oa_operation_log" and not with_logs:
|
||
continue
|
||
model = BY_TABLE.get(table)
|
||
if model is None:
|
||
ledger.note(f"{table} 在这个版本的模型里找不到,跳过")
|
||
continue
|
||
doomed = [o for o in session.execute(select(model)).scalars() if doomed_row(o, scope, table)]
|
||
if not doomed:
|
||
continue
|
||
ledger.record_delete(table, doomed)
|
||
for obj in doomed:
|
||
session.delete(obj)
|
||
# 留下来的人不再挂着已删部门与已删上级(外键是 SET NULL,这里显式走一遍,
|
||
# 免得某些库是 DBA 用 sql/schema.sql 手工建的、口径对不上)
|
||
for person_id in scope.keep_person_ids:
|
||
person = session.get(models.User, person_id)
|
||
if person is not None:
|
||
person.organization_id = None
|
||
person.leader_id = None
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 就地抹掉引用
|
||
# ---------------------------------------------------------------------------
|
||
|
||
def _strip_dead_refs(node: Any, scope: Scope) -> Any:
|
||
"""递归丢掉等于已清人员的条目(列表项与字典值都算)。"""
|
||
if isinstance(node, list):
|
||
return [_strip_dead_refs(v, scope) for v in node if not scope.dead_ref(v)]
|
||
if isinstance(node, dict):
|
||
return {k: _strip_dead_refs(v, scope) for k, v in node.items() if not scope.dead_ref(v)}
|
||
return node
|
||
|
||
|
||
def _approver_rules(node: Any) -> Iterator[dict[str, Any]]:
|
||
"""找出 JSON 里的找人规则条目:同时带 ``type`` 与 ``data`` / ``identities`` 的对象。"""
|
||
if isinstance(node, dict):
|
||
if isinstance(node.get("type"), str) and any(k in node for k in ("data", "identities")):
|
||
yield node
|
||
for value in node.values():
|
||
yield from _approver_rules(value)
|
||
elif isinstance(node, list):
|
||
for value in node:
|
||
yield from _approver_rules(value)
|
||
|
||
|
||
def _scrub_approver_rules(node: Any, scope: Scope) -> int:
|
||
"""洗掉找人规则里指向已清对象的选择:点人的剔掉认不到的 DN,点部门的剔掉已清部门名。"""
|
||
dropped = 0
|
||
for rule in _approver_rules(node):
|
||
kind = org_service.normalize_kind(rule.get("type"))
|
||
for key in ("data", "identities"):
|
||
values = rule.get(key)
|
||
if not isinstance(values, list):
|
||
continue
|
||
if kind in UNIT_KINDS:
|
||
# 点部门的规则:部门没了就剔掉,环节交给 emptyApprover 兜底
|
||
kept = [v for v in values if not (scope.doomed_unit(v) or scope.dead_ref(v))]
|
||
else:
|
||
# 点人、点岗位、点组、层级层数、表单字段路径:只剔已清人员的账号引用,
|
||
# 岗位名与部门名撞名(总经理既是岗位也是部门)时不能连岗位一起清掉
|
||
kept = [v for v in values if not scope.dead_ref(v)]
|
||
dropped += len(values) - len(kept)
|
||
if kept != values:
|
||
rule[key] = kept
|
||
return dropped
|
||
|
||
|
||
def _scrub_json_columns(session, scope: Scope, ledger: Ledger) -> None:
|
||
for table, column in JSON_COLUMNS:
|
||
model = BY_TABLE.get(table)
|
||
if model is None:
|
||
continue
|
||
for obj in session.execute(select(model)).scalars():
|
||
raw = getattr(obj, column, None)
|
||
if raw in (None, "", {}, []):
|
||
continue
|
||
try:
|
||
current = json.loads(json.dumps(raw, ensure_ascii=False, default=str))
|
||
except (TypeError, ValueError):
|
||
continue
|
||
cleaned = _strip_dead_refs(current, scope)
|
||
_scrub_approver_rules(cleaned, scope)
|
||
if cleaned == current:
|
||
continue
|
||
ledger.record_scrub(table, obj, f"{table}.{column}")
|
||
setattr(obj, column, cleaned)
|
||
|
||
|
||
def _scrub_selector_lists(session, scope: Scope, ledger: Ledger) -> None:
|
||
"""审批岗位与用户组:人清空了岗位本身留着,只把认不到人的选择项剔掉。"""
|
||
for model, column, doomed in (
|
||
(models.Role, "list_auth", scope.dead_ref),
|
||
(models.Group, "list_identity", scope.dead_ref),
|
||
# list_person 存的是账号(见 service/personref.py),按主键比永远比不中
|
||
(models.Group, "list_person", scope.dead_ref),
|
||
):
|
||
table = model.__tablename__
|
||
for obj in session.execute(select(model)).scalars():
|
||
values = list(getattr(obj, column) or [])
|
||
kept = [v for v in values if not doomed(v)]
|
||
if kept == values:
|
||
continue
|
||
ledger.record_scrub(table, obj, f"{table}.{column}", len(values) - len(kept))
|
||
setattr(obj, column, kept)
|
||
|
||
|
||
def _scrub_author_columns(session, scope: Scope, ledger: Ledger) -> None:
|
||
"""作者与创建者列:人没了就置空,正文、表单、流程定义本身都留着。"""
|
||
gone_tables = set(ledger.deleted)
|
||
for table, model in sorted(BY_TABLE.items()):
|
||
if table in gone_tables or not (hasattr(model, "creator") and hasattr(model, "creator_name")):
|
||
continue
|
||
for obj in session.execute(select(model)).scalars():
|
||
if not (scope.doomed_person(obj.creator) or scope.doomed_person_name(obj.creator_name)):
|
||
continue
|
||
if not (obj.creator or obj.creator_name):
|
||
continue
|
||
ledger.record_scrub(table, obj, f"{table}.creator")
|
||
obj.creator = ""
|
||
obj.creator_name = ""
|
||
for doc in session.execute(select(models.CmsDocument)).scalars():
|
||
if not (scope.dead_ref(doc.author_identity) or scope.doomed_person_name(doc.author)):
|
||
continue
|
||
if not (doc.author or doc.author_identity):
|
||
continue
|
||
ledger.record_scrub("oa_cms_document", doc, "oa_cms_document.author")
|
||
doc.author = ""
|
||
doc.author_identity = ""
|
||
|
||
|
||
def _scrub_dict_extra(session, scope: Scope, ledger: Ledger) -> None:
|
||
"""字典附加值里指向已清部门的那一项(演示预算科目的 owner)。"""
|
||
for item in session.execute(select(models.DictItem)).scalars():
|
||
extra = dict(item.extra or {})
|
||
kept = {k: v for k, v in extra.items() if not scope.doomed_unit(v)}
|
||
if kept == extra:
|
||
continue
|
||
ledger.record_scrub("oa_dict_item", item, "oa_dict_item.extra", len(extra) - len(kept))
|
||
item.extra = kept
|
||
|
||
|
||
def _delete_hub_cursor(session, scope: Scope, ledger: Ledger) -> None:
|
||
"""``hub_directory`` 存的是同步游标与人数:清完人员就该归零重来。"""
|
||
row = session.get(models.SystemSetting, HUB_DIRECTORY_KEY)
|
||
if row is None:
|
||
return
|
||
ledger.record_scrub("oa_system_setting", row, "oa_system_setting.hub_directory")
|
||
session.delete(row)
|
||
|
||
|
||
def _emergency_accounts(scope: Scope) -> tuple[str, str]:
|
||
"""应急本地登录账号名单:清完之后只该剩内置超管。返回(现值, 清后值)。"""
|
||
current = str(dbconfig.value("hub_local_accounts", "") or "")
|
||
kept = [a for a in (s.strip() for s in current.split(",")) if a == scope.admin_account]
|
||
return current, ",".join(kept)
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 备份与还原
|
||
# ---------------------------------------------------------------------------
|
||
|
||
def backup_path(stamp: str) -> Path:
|
||
return BACKUP_DIR / f"purge-people-org-{stamp}.json.gz"
|
||
|
||
|
||
def write_backup(path: Path, payload: dict[str, Any]) -> None:
|
||
path.parent.mkdir(parents=True, exist_ok=True)
|
||
with gzip.open(path, "wt", encoding="utf-8") as fh:
|
||
json.dump(payload, fh, ensure_ascii=False)
|
||
|
||
|
||
def _coerce(column: Any, value: Any) -> Any:
|
||
"""备份里的时间是 ISO 串,插回去之前按列类型换回来。"""
|
||
if value is None:
|
||
return None
|
||
type_name = column.type.__class__.__name__
|
||
if type_name in ("DateTime", "Timestamp") and isinstance(value, str):
|
||
return datetime.fromisoformat(value)
|
||
if type_name == "Date" and isinstance(value, str):
|
||
return date.fromisoformat(value)
|
||
return value
|
||
|
||
|
||
def restore(path: Path) -> dict[str, int]:
|
||
"""按备份逐表回写:主键不在了就插回整行,还在就把值改回备份里的样子。"""
|
||
with gzip.open(path, "rt", encoding="utf-8") as fh:
|
||
payload = json.load(fh)
|
||
deleted = payload.get("deleted") or {}
|
||
scrubbed = payload.get("scrubbed") or {}
|
||
tables = list(dict.fromkeys(list(deleted) + list(scrubbed)))
|
||
ordered = [t for t in RESTORE_ORDER if t in tables] + [t for t in tables if t not in RESTORE_ORDER]
|
||
|
||
counts: dict[str, int] = {}
|
||
session = db.SessionLocal()
|
||
try:
|
||
for table in ordered:
|
||
model = BY_TABLE.get(table)
|
||
if model is None:
|
||
print(f"跳过 {table}:这个版本的模型里没有这张表")
|
||
continue
|
||
meta = model.__table__
|
||
pk = [c.name for c in meta.primary_key]
|
||
alive = {
|
||
tuple(str(v) for v in row)
|
||
for row in session.execute(text(f"SELECT {', '.join(pk)} FROM `{table}`"))
|
||
}
|
||
done: set[tuple[str, ...]] = set()
|
||
# 同一行可能被洗两次:先出现的那条改前值才是最初的样值
|
||
for row in list(deleted.get(table, [])) + list(scrubbed.get(table, [])):
|
||
key = tuple(str(row.get(c, "")) for c in pk)
|
||
if key in done:
|
||
continue
|
||
done.add(key)
|
||
values = {c.name: _coerce(c, row.get(c.name)) for c in meta.columns if c.name in row}
|
||
if key in alive:
|
||
session.execute(
|
||
meta.update()
|
||
.where(*(meta.c[c] == values[c] for c in pk))
|
||
.values(**{c: v for c, v in values.items() if c not in pk})
|
||
)
|
||
else:
|
||
session.execute(meta.insert().values(**values))
|
||
counts[table] = counts.get(table, 0) + 1
|
||
session.commit()
|
||
finally:
|
||
session.close()
|
||
return counts
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 主流程
|
||
# ---------------------------------------------------------------------------
|
||
|
||
def purge(apply_changes: bool, keep_admin: bool, with_logs: bool,
|
||
keep_sync: bool, keep_hub_state: bool) -> dict[str, Any]:
|
||
session = db.SessionLocal()
|
||
try:
|
||
scope = Scope(session, keep_admin)
|
||
ledger = Ledger()
|
||
if not scope.keep_person_ids:
|
||
ledger.note("内置超管也在这次清理里:清完库里没有任何能登录的账号,"
|
||
"且 users 为空会让下次启动重新种演示人员")
|
||
before_accounts, after_accounts = _emergency_accounts(scope)
|
||
|
||
delete_doomed_rows(session, scope, ledger, with_logs)
|
||
_scrub_json_columns(session, scope, ledger)
|
||
_scrub_selector_lists(session, scope, ledger)
|
||
_scrub_author_columns(session, scope, ledger)
|
||
_scrub_dict_extra(session, scope, ledger)
|
||
if not keep_hub_state:
|
||
_delete_hub_cursor(session, scope, ledger)
|
||
if not keep_sync:
|
||
ledger.note(
|
||
"关掉 Hub 定时全量同步与增量轮询:去「系统设置 → 同步定时任务」打开「允许定时同步」就能恢复;"
|
||
"界面上的「立即同步」不受这一项影响,下次跑本脚本带 --keep-sync 也别碰它"
|
||
)
|
||
if not keep_hub_state and before_accounts != after_accounts:
|
||
ledger.note(f"应急本地登录账号名单:{before_accounts} -> {after_accounts or '(空)'}")
|
||
|
||
session.flush()
|
||
leftover = _leftover_report(session, scope)
|
||
|
||
path: Path | None = None
|
||
if apply_changes:
|
||
session.commit()
|
||
# 配置写入自己提交,放在正式清理之后:干跑一步都不碰它
|
||
if not keep_hub_state:
|
||
patch = {"hub_local_accounts": after_accounts} if before_accounts != after_accounts else {}
|
||
if patch:
|
||
dbconfig.apply(session, "hub", patch)
|
||
if not keep_sync:
|
||
dbconfig.apply(session, "hub_sync", {
|
||
"hub_sync_enabled": False,
|
||
"hub_sync_changes_enabled": False,
|
||
})
|
||
stamp = datetime.now().strftime("%Y%m%d-%H%M%S")
|
||
path = backup_path(stamp)
|
||
write_backup(path, {
|
||
"meta": {
|
||
"stamp": stamp,
|
||
"admin_account": scope.admin_account,
|
||
"kept_person_ids": sorted(scope.keep_person_ids),
|
||
"with_logs": with_logs,
|
||
"hub_sync_disabled": not keep_sync,
|
||
"hub_state_kept": keep_hub_state,
|
||
},
|
||
"deleted": ledger.deleted,
|
||
"scrubbed": ledger.scrubbed,
|
||
})
|
||
else:
|
||
session.rollback()
|
||
|
||
return {
|
||
"mode": "apply" if apply_changes else "dry-run",
|
||
"kept_person_ids": sorted(scope.keep_person_ids),
|
||
"admin_account": scope.admin_account,
|
||
"deleted_rows": sum(len(rows) for rows in ledger.deleted.values()),
|
||
"scrubbed_rows": sum(len(rows) for rows in ledger.scrubbed.values()),
|
||
"counts": ledger.counts,
|
||
"notes": ledger.notes,
|
||
"backup": str(path) if path else "",
|
||
"leftover": leftover,
|
||
}
|
||
finally:
|
||
session.close()
|
||
|
||
|
||
def _leftover_report(session, scope: Scope) -> dict[str, Any]:
|
||
"""就地扫一遍全库:这些姓名与部门名还出现在哪些列(走同一个事务,看得见的改动算已清)。"""
|
||
markers: dict[str, str] = {}
|
||
for name in scope.doomed_person_names:
|
||
if len(name) >= 2:
|
||
markers[name] = "人员"
|
||
for name in scope.doomed_unit_names:
|
||
if len(name) >= 3: # 两三个字的通称当标记只会刷屏,三字以上才算部门名
|
||
markers[name] = "部门"
|
||
# 留下来的账号自己的名字与 DN 里就含着「管理员」这类通称,拿它当标记全是噪音
|
||
alive_text = " ".join(sorted(scope.alive_dns))
|
||
markers = {m: kind for m, kind in markers.items() if m not in alive_text}
|
||
hits: dict[str, int] = {}
|
||
samples: dict[str, str] = {}
|
||
if not markers:
|
||
return {"by_column": hits, "sample": samples}
|
||
tables = [r[0] for r in session.execute(text("SHOW TABLES")).fetchall()]
|
||
for table in tables:
|
||
rows = session.execute(text(f"SELECT * FROM `{table}`")).mappings().all()
|
||
for row in rows:
|
||
for column, value in row.items():
|
||
if value is None:
|
||
continue
|
||
text_value = value if isinstance(value, str) else json.dumps(
|
||
value, ensure_ascii=False, default=str
|
||
)
|
||
for marker, kind in markers.items():
|
||
if marker in text_value:
|
||
key = f"{table}.{column}"
|
||
hits[key] = hits.get(key, 0) + 1
|
||
samples.setdefault(key, f"[{kind}] {marker}")
|
||
break
|
||
return {"by_column": hits, "sample": samples}
|
||
|
||
|
||
def main() -> int:
|
||
ap = argparse.ArgumentParser()
|
||
ap.add_argument("--apply", action="store_true", help="真删(默认只干跑报数)")
|
||
ap.add_argument("--all-people", action="store_true",
|
||
help="连内置超管一起删:删完谁都进不去,下次启动还会重新种演示人员")
|
||
ap.add_argument("--yes-lockout", action="store_true", help="确认接受上一条款的后果")
|
||
ap.add_argument("--logs", action="store_true", help="连操作日志(oa_operation_log)一起清")
|
||
ap.add_argument("--keep-sync", action="store_true", help="不动 Hub 同步开关")
|
||
ap.add_argument("--keep-hub-state", action="store_true",
|
||
help="保留 hub_directory 同步游标与应急账号名单")
|
||
ap.add_argument("--restore", metavar="FILE", help="从备份还原,不做清理")
|
||
args = ap.parse_args()
|
||
|
||
if args.restore:
|
||
counts = restore(Path(args.restore))
|
||
for table, n in sorted(counts.items(), key=lambda kv: -kv[1]):
|
||
print(f" {table:26} {n}")
|
||
print(f"\n共回写 {sum(counts.values())} 行")
|
||
return 0
|
||
|
||
if args.all_people and not args.yes_lockout:
|
||
print("--all-people 会把内置超管也删掉,确认后果后加 --yes-lockout 再来一次")
|
||
return 2
|
||
|
||
result = purge(
|
||
apply_changes=args.apply,
|
||
keep_admin=not args.all_people,
|
||
with_logs=args.logs,
|
||
keep_sync=args.keep_sync,
|
||
keep_hub_state=args.keep_hub_state,
|
||
)
|
||
printable = {k: v for k, v in result.items() if k not in ("counts", "leftover")}
|
||
print(json.dumps(printable, ensure_ascii=False, indent=2))
|
||
print("\n逐表:")
|
||
for key, n in sorted(result["counts"].items(), key=lambda kv: (-kv[1], kv[0])):
|
||
print(f" {key:34} {n}")
|
||
print("\n清完仍带这些姓名/部门名的列(多为演示文案、保留账号自己的记录,按需再处理):")
|
||
leftover = result["leftover"]["by_column"]
|
||
for key, n in sorted(leftover.items(), key=lambda kv: (-kv[1], kv[0]))[:15]:
|
||
print(f" {key:38} {n:5} 如 {result['leftover']['sample'].get(key, '')}")
|
||
if not leftover:
|
||
print(" (无)")
|
||
if not args.apply:
|
||
print("\n以上为干跑,未改任何数据;确认后加 --apply")
|
||
return 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
sys.exit(main())
|