#!/usr/bin/env python3 """守「Hub 换过主键留下的空壳部门」:判据、能不能删、一键清理到底删了什么。 踩过的坑:Hub 把部门挪了 ``organization_id``(重建、合并、换环境重导)之后,本地靠 「编码 + 名称」把那一支认回了原部门,旧的那一具就脱开了 —— ``hub_org_id`` 指着一个 永远不会再出现的组织,状态停在停用,编码与名称都已被在职的孪生部门占用。同步既不认它 也不并它,组织树上一排重名部门,部门下拉框里点哪个都可能错。以前只能手工「解绑 → 删除」, 一具一具点,测试站上攒过 12 具。 这里钉二十一项(含最后那条「库里没留东西」):: cd backend && PYTHONPATH=. python3 scripts/check_hub_sync_shell_units.py 1~5 :判据(同码同名 + 已停用 + 绑过 Hub 才算,少一条都不算); 6~8 :Hub 清单口径(它还认得的停用部门不是壳子;孪生不在清单里也不作数); 9~12 :删不掉的三种情况(有人、有下级、被角色当数据范围)与干净壳子; 13~16:一键清理(预演不落库、真删只删干净的、判据当场重算、再跑一次不重复删)。 全程待在同一个事务里,跑完 ``rollback``,库里不留任何临时行。 """ from __future__ import annotations import pathlib import sys from types import SimpleNamespace sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent)) from sqlalchemy import func, select # noqa: E402 from app import models # noqa: E402 from app.api import org as org_api # noqa: E402 from app.db import SessionLocal # noqa: E402 from app.schemas import UnitShellCleanupBody # noqa: E402 from app.service import hub_sync # noqa: E402 MARK = "zzshell-" ORG_BASE = 906100 UID_BASE = 906500 FAILS: list[str] = [] PASSED = 0 def check(label: str, passed: bool, detail: str = "") -> None: global PASSED if passed: PASSED += 1 print(f"[通过] {label}") else: FAILS.append(label) print(f"[FAIL] {label}{f' -> {detail}' if detail else ''}") def add_unit( db, # noqa: ANN001 *, hub_org_id: int | None, code: str, name: str, status=int(models.UnitStatus.ACTIVE), # noqa: B008 parent=None, # noqa: ANN001 ): # noqa: ANN201 row = models.Unit( name=name, code=code, alias=code, description="壳子检查", parent_id=parent.id if parent else None, hub_org_id=hub_org_id, status=status, ) db.add(row) db.flush() return row def add_user(db, account: str, unit): # noqa: ANN001, ANN201 row = models.User( account=account, display_name="壳子检查人员", email="", mobile="", password_hash="zz-check", role=models.ROLE_MEMBER, status=models.UserStatus.ACTIVE, source=models.AccountSource.LOCAL, organization_id=unit.id, ) db.add(row) db.flush() return row def shells(db) -> list[models.Unit]: # noqa: ANN001 """库内口径(不带 Hub 清单):清理接口用的就是这一份。""" return hub_sync.find_shell_units(org_api._hub_units(db)) def shell_ids(db) -> set[str]: # noqa: ANN001 return {str(row.id) for row in shells(db)} def run_cleanup(db, *, ids=None, dry_run=False): # noqa: ANN001, ANN201 """直接调接口函数:依赖注入的参数自己填,提交换成 flush,全程留在事务里。""" user = SimpleNamespace(person=SimpleNamespace(id=1), display_name="检查员", ref="zz-check") real_ip = org_api.client_ip real_commit = db.commit org_api.client_ip = lambda request: "127.0.0.1" # type: ignore[assignment] db.commit = db.flush # type: ignore[method-assign] try: payload = org_api.cleanup_shell_units( UnitShellCleanupBody(ids=ids or [], dry_run=dry_run), None, # request:client_ip 已被替掉,用不上 db=db, user=user, # type: ignore[arg-type] ) finally: org_api.client_ip = real_ip # type: ignore[assignment] db.commit = real_commit # type: ignore[method-assign] return payload["data"] if isinstance(payload, dict) and "data" in payload else payload def main() -> int: db = SessionLocal() try: db.begin() # 一对同名同码的:在职的孪生 + 脱开的旧身子 twin = add_unit(db, hub_org_id=ORG_BASE + 1, code=f"{MARK}a", name=f"{MARK}研发部") shell = add_unit(db, hub_org_id=ORG_BASE + 2, code=f"{MARK}a", name=f"{MARK}研发部", status=models.UnitStatus.DISABLED) # 反例四则:没有孪生 / 只同码不同名 / 没绑 Hub / 在职的双胞胎本身 lonely = add_unit(db, hub_org_id=ORG_BASE + 3, code=f"{MARK}b", name=f"{MARK}市场部", status=models.UnitStatus.DISABLED) add_unit(db, hub_org_id=ORG_BASE + 4, code=f"{MARK}a", name=f"{MARK}财务部", status=models.UnitStatus.DISABLED) add_unit(db, hub_org_id=None, code=f"{MARK}c", name=f"{MARK}本地部", status=models.UnitStatus.DISABLED) db.flush() found = shell_ids(db) check("壳子判据命中:同码同名 + 已停用 + 绑过 Hub", str(shell.id) in found, str(sorted(found))) check("在职的那个不算壳子", str(twin.id) not in found) check("没有在职同名同码孪生的停用部门不算壳子", str(lonely.id) not in found) check( "只同码不同名不算壳子(名称也认不回,删了就是删)", all(str(row.id) not in found for row in db.execute( select(models.Unit).where(models.Unit.name == f"{MARK}财务部") ).scalars().all()), ) check("本地自建部门永远不进这批", all(str(row.id) not in found for row in db.execute( select(models.Unit).where(models.Unit.name == f"{MARK}本地部") ).scalars().all())) # Hub 清单口径:体检时多一条"这一趟清单里确实没有它" check( "Hub 这一趟还认得它 → 只是正常停用的部门,不是壳子", str(shell.id) not in {str(row.id) for row in hub_sync.find_shell_units( org_api._hub_units(db), roster_org_ids={ORG_BASE + 1, ORG_BASE + 2} )}, ) check( "孪生部门不在这一趟清单里 → 没人接住这个身份,先别算壳子", str(shell.id) not in {str(row.id) for row in hub_sync.find_shell_units( org_api._hub_units(db), roster_org_ids={ORG_BASE + 2} )}, ) check( "清单口径下照常认得出壳子(孪生在册、自己不册)", [row.id for row in hub_sync.find_shell_units( org_api._hub_units(db), roster_org_ids={ORG_BASE + 1} )] == [shell.id], ) clean_reasons = hub_sync.shell_unit_blockers(db, shell) check("没人的没下级的没被角色引用的壳子:可以删", clean_reasons == [], str(clean_reasons)) member = add_user(db, f"{MARK}p1", shell) check("壳子上还挂着人 → 拦住", "直属人员 1 人" in " ".join(hub_sync.shell_unit_blockers(db, shell)), str(hub_sync.shell_unit_blockers(db, shell))) db.delete(member) db.flush() child = add_unit(db, hub_org_id=ORG_BASE + 5, code=f"{MARK}d", name=f"{MARK}下属组", parent=shell) check("壳子还有下级 → 拦住", "下级部门 1 个" in " ".join(hub_sync.shell_unit_blockers(db, shell)), str(hub_sync.shell_unit_blockers(db, shell))) db.delete(child) db.flush() role = models.AuthRole(name=f"{MARK}role", data_scope="custom", data_unit_ids=[str(shell.id)]) db.add(role) db.flush() blockers = hub_sync.shell_unit_blockers(db, shell) check("被权限角色当自定义数据范围 → 拦住(删了会安静少一片范围)", any("权限角色" in text for text in blockers), str(blockers)) db.delete(role) db.flush() # 一键清理:预演 → 真删 → 幂等 result = run_cleanup(db, dry_run=True) still_there = db.get(models.Unit, shell.id) is not None check("预演:报出要删的,一行都不动", len(result["deleted"]) == 1 and still_there, str(result)) result = run_cleanup(db) check("真删:只删判据命中的干净壳子", len(result["deleted"]) == 1 and db.get(models.Unit, shell.id) is None, str(result)) check("没孪生的停用部门一个都没被顺手删掉", db.get(models.Unit, lonely.id) is not None) logs = int(db.execute( select(func.count()).select_from(models.OperationLog).where( models.OperationLog.action == "org_unit_shell_cleanup" ) ).scalar() or 0) check("清理留了一条操作日志(谁删的、删了哪几具)", logs == 1, str(logs)) result = run_cleanup(db) check("再跑一次不重复删", result["deleted"] == [] and result["skipped"] == [], str(result)) result = run_cleanup(db, ids=[str(shell.id)]) check("传进来的 id 已经不是壳子:跳过并说明原因", result["deleted"] == [] and result["skipped"] and "已经不是空壳部门" in result["skipped"][0]["blockers"][0], str(result)) # 判据当场重算:预演讲"能删",真跑之前被人挂上人,就该改成跳过 shell2 = add_unit(db, hub_org_id=ORG_BASE + 6, code=f"{MARK}e", name=f"{MARK}测试部") shell3 = add_unit(db, hub_org_id=ORG_BASE + 7, code=f"{MARK}e", name=f"{MARK}测试部", status=models.UnitStatus.DISABLED) db.flush() add_user(db, f"{MARK}p2", shell3) result = run_cleanup(db, ids=[str(shell3.id)]) check("清理前重新核对判据与占用:中途被人挂上人就不删了", result["deleted"] == [] and "直属人员 1 人" in " ".join(result["skipped"][0]["blockers"]), str(result)) check("在职的孪生还在原地", db.get(models.Unit, shell2.id) is not None) finally: db.rollback() db.close() leftover = 0 probe = SessionLocal() try: leftover = int( probe.execute( select(func.count()).select_from(models.Unit).where(models.Unit.code.like(f"{MARK}%")) ).scalar() or 0 ) finally: probe.close() check("临时部门全部随事务回滚,库里不留壳子", leftover == 0, str(leftover)) print() if FAILS: print(f"未通过 {len(FAILS)} 项:") for name in FAILS: print(f" - {name}") return 1 print(f"全部通过:{PASSED} 项") return 0 if __name__ == "__main__": raise SystemExit(main())