446 lines
21 KiB
Python
446 lines
21 KiB
Python
"""统一身份同步改名之后,把按字符串存着的审批与共享引用搬到新值上。
|
||
|
||
平台的权限分两层,同步对它们的杀伤力完全不同:
|
||
|
||
* **按主键挂的那一层搬不走也不会掉**:权限角色 ``oa_person_auth_role`` 挂 ``users.id``,
|
||
数据范围按 ``oa_unit.id`` 递归算,部门负责人存 ``manager_person_id``。同步只改字段值、
|
||
只停用不删行、永远不改 ``users.id`` / ``oa_unit.id``,所以配好权限再全量同步,这一层
|
||
一次都不会掉——前提正是 ``hub_user_id`` / ``hub_org_id`` 唯一且不被清空。
|
||
* **按字符串存的那一层会悄悄失效**:审批岗位 ``oa_role.list_auth``、岗位组
|
||
``oa_group.list_identity``、流程环节审批人(``oa_activity.config`` 的 ``taskValues``)、
|
||
流程可见/可发起人、代理人、日程与网盘的共享名单……存的都是部门路径、部门名、
|
||
登录账号、姓名,运行时时现解析(见 ``service/org.py::_expand``)。Hub 一改名、一挪层级、
|
||
一换账号,这些字符串就解析不到人了:环节审批人算出来是空的,流程卡在第一个节点,
|
||
界面上一个错误都不报——这是"同步一次系统就不能用了"的真正来源。
|
||
|
||
同步收尾时按 ``hub_sync`` 记下的"旧值 -> 新值"映射把这一层一起搬走。搬不动的(有歧义、
|
||
或者新值本地已经另有人用)一律不动,只计数报进同步记录,让人去设计器里确认——宁可留一个
|
||
看得见的问题,也不要悄悄改错审批人。
|
||
|
||
除配置之外还有一类**按账号挂着的本地数据行**:个人收款账户 ``oa_bank_account``(人在
|
||
个人资料里自己填的开户行与收款账号)。它不在 Hub 的清单里、同步永远不写它,但账号一改名
|
||
就会跟着落空,所以搬引用的时候顺带把它一起搬,见 :func:`_move_bank_accounts`。
|
||
|
||
运行态那些按账号存的历史行(``oa_work.creator_identity``、``oa_task.identity``……)**不搬也
|
||
搬不动**,于是登录账号改名是这套口径唯一剩下的尖角:老账号上的单会从"我发起的""我的待办"
|
||
里消失。这一层只把它数出来报进同步记录(:func:`runtime_drift`),真正守住它的是运维口径——
|
||
**登录账号不改**。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import logging
|
||
from dataclasses import dataclass, field
|
||
from typing import Any
|
||
|
||
from sqlalchemy import func, select
|
||
from sqlalchemy.orm import Session
|
||
|
||
from .. import models
|
||
from . import org
|
||
|
||
logger = logging.getLogger("unisoa.hub.refs")
|
||
|
||
|
||
@dataclass
|
||
class Maps:
|
||
"""一次同步(或一次预检)产生的"旧值 -> 新值"映射。
|
||
|
||
``strict`` 只放部门路径、登录账号这类一眼看得出是引用的值,连流程环节那种
|
||
混着表单文字的 JSON 也敢照着搬;``unit_names`` / ``person_names`` 是部门名与姓名,
|
||
纯文本、会撞车,用之前要先过一遍歧义检查(见 ``_safe_names``)。
|
||
"""
|
||
|
||
strict: dict[str, str] = field(default_factory=dict)
|
||
unit_names: dict[str, str] = field(default_factory=dict)
|
||
person_names: dict[str, str] = field(default_factory=dict)
|
||
#: 登录账号改名映射(旧账号 -> 新账号)。和 ``strict`` 分开存一份:那一份里还混着
|
||
#: 部门路径,拿来搬"按账号挂着的数据行"会把不该搬的搬走。
|
||
accounts: dict[str, str] = field(default_factory=dict)
|
||
|
||
@property
|
||
def names(self) -> dict[str, str]:
|
||
return {**self.unit_names, **self.person_names}
|
||
|
||
@property
|
||
def loose(self) -> dict[str, str]:
|
||
return {**self.strict, **self.names}
|
||
|
||
@property
|
||
def empty(self) -> bool:
|
||
return not (self.strict or self.unit_names or self.person_names or self.accounts)
|
||
|
||
@dataclass
|
||
class RefReport:
|
||
rewritten: int = 0
|
||
skipped: int = 0
|
||
#: 因为歧义没敢搬的名字,同步收尾时按它们再查一遍哪些配置还指着旧名
|
||
dropped_names: list[str] = field(default_factory=list)
|
||
#: 改过去之后本地有同名的部门/人,选择器会一并命中,报出来让人核对
|
||
homonyms: list[str] = field(default_factory=list)
|
||
#: 随账号改名搬走的本地数据行(目前是个收款账户)
|
||
accounts_moved: int = 0
|
||
#: 账号改了名但没敢搬的本地数据行,报出来让人手工核对
|
||
accounts_stuck: list[str] = field(default_factory=list)
|
||
hits: list[str] = field(default_factory=list)
|
||
|
||
def sample(self, text: str) -> None:
|
||
if len(self.hits) < 12:
|
||
self.hits.append(text)
|
||
|
||
|
||
#: ``(模型, 列, 行标签取的列, 是否允许按姓名/部门名搬)``;列值可以是字符串或字符串列表。
|
||
SELECTOR_COLUMNS: tuple[tuple[Any, str, str, bool], ...] = (
|
||
(models.Role, "list_auth", "name", True),
|
||
(models.Role, "unit", "name", True),
|
||
(models.Group, "list_identity", "name", True),
|
||
(models.Group, "list_person", "name", True),
|
||
(models.Group, "unit", "name", True),
|
||
(models.Process, "start_identity_list", "name", True),
|
||
(models.Process, "manageable_identity_list", "name", True),
|
||
(models.Process, "visible_identity_list", "name", True),
|
||
(models.Agent, "identity", "person_name", False),
|
||
(models.Agent, "from_identity", "person_name", False),
|
||
(models.Handover, "from_identity", "title", False),
|
||
(models.Handover, "to_identity", "title", False),
|
||
(models.Schedule, "owner", "title", False),
|
||
(models.Schedule, "shared_identities", "title", False),
|
||
(models.PortalFile, "owner", "name", False),
|
||
(models.PortalFile, "shared_identities", "name", False),
|
||
)
|
||
|
||
#: 混合格式的 JSON 配置块:只按 ``strict`` 搬,免得把表单文字一起改了。
|
||
JSON_COLUMNS: tuple[tuple[Any, str, str], ...] = ((models.Activity, "config", "name"),)
|
||
|
||
|
||
def path_variants(path: str) -> tuple[str, ...]:
|
||
"""``oa_unit.path`` 在系统里有三种写法,选择器里存哪一种都要认。"""
|
||
if not path:
|
||
return ()
|
||
bare = path.rstrip("\\")
|
||
out = [path]
|
||
if bare != path:
|
||
out.append(bare)
|
||
out.append(f"o={bare}")
|
||
return tuple(dict.fromkeys(out))
|
||
|
||
|
||
def build_maps(
|
||
*,
|
||
path_map: dict[str, str] | None = None,
|
||
unit_name_map: dict[str, str] | None = None,
|
||
account_map: dict[str, str] | None = None,
|
||
display_name_map: dict[str, str] | None = None,
|
||
) -> Maps:
|
||
"""把同步记下的各类改名拼成可直接查表的映射。"""
|
||
strict: dict[str, str] = {}
|
||
for old, new in (path_map or {}).items():
|
||
for old_variant, new_variant in zip(path_variants(old), path_variants(new)):
|
||
strict[old_variant] = new_variant
|
||
for old, new in (account_map or {}).items():
|
||
strict[old] = new
|
||
return Maps(
|
||
strict=strict,
|
||
accounts={
|
||
old: new
|
||
for old, new in (account_map or {}).items()
|
||
if old and new and old != new
|
||
},
|
||
unit_names={k: v for k, v in (unit_name_map or {}).items() if k and v},
|
||
person_names={k: v for k, v in (display_name_map or {}).items() if k and v},
|
||
)
|
||
|
||
|
||
def _safe_names(
|
||
db: Session, unit_names: dict[str, str], person_names: dict[str, str]
|
||
) -> tuple[dict[str, str], dict[str, str], list[str], list[str]]:
|
||
"""部门名与姓名的歧义检查:认不准就不搬,只报数。
|
||
|
||
判据照 ``service/org.py::_expand`` 的解析顺序来(人员账号/姓名 > 部门 >
|
||
审批岗位 > 岗位组):旧名字要是还被某个人员占着,选择器解析出来的本来就是那个人,
|
||
按部门改名去搬它会改错对象;新名字要是撞上某个人员的账号或姓名,搬过去会让选择器从
|
||
"部门"悄悄变成"个人",审批人完全变一批人,这种也不搬。审批岗位与岗位组排在部门后面,
|
||
同名时部门先命中,所以不挡路。
|
||
|
||
"本地已经有别的部门/人叫新名字"不算歧义:那是 Hub 改名本身造成的(对面就是给了这么个
|
||
名字),引用留在旧名上只会彻底解析不到人。这种改完单独报一条,让人去核对同名。
|
||
"""
|
||
kept_units: dict[str, str] = {}
|
||
kept_people: dict[str, str] = {}
|
||
dropped: list[str] = []
|
||
homonyms: list[str] = []
|
||
|
||
def count(model, column, value: str) -> int:
|
||
return int(db.execute(select(func.count()).select_from(model).where(column == value)).scalar() or 0)
|
||
|
||
def login_taken(value: str) -> bool:
|
||
"""登录账号占没被占:账号在解析顺序里排在部门名与姓名前面,撞上就不能用名字去搬。"""
|
||
return bool(db.execute(select(models.User.id).where(models.User.account == value)).first())
|
||
|
||
def named_the_same(value: str) -> bool:
|
||
"""有没有人以这个姓名登录可见:姓名被人员占着时,选择器解析出来的是那个人而不是部门。"""
|
||
return bool(db.execute(select(models.User.id).where(models.User.display_name == value)).first())
|
||
|
||
for old, new in unit_names.items():
|
||
# 同步这时已经把部门改完了:还查得到旧名 = 本地另有同名部门,搬过去会改到那一支
|
||
if not old or not new or old == new or count(models.Unit, models.Unit.name, old):
|
||
dropped.append(old)
|
||
continue
|
||
# 旧名/新名撞上人员的账号或姓名:搬过去等于把审批来源从"部门"换成"某个人"
|
||
if login_taken(old) or named_the_same(old) or login_taken(new) or named_the_same(new):
|
||
dropped.append(old)
|
||
continue
|
||
kept_units[old] = new
|
||
if count(models.Unit, models.Unit.name, new) > 1: # 除了改过来的这个,本地还有同名部门
|
||
homonyms.append(f"部门「{new}」")
|
||
|
||
for old, new in person_names.items():
|
||
wanted = sum(1 for value in person_names.values() if value == new)
|
||
if not old or not new or old == new or wanted != 1:
|
||
dropped.append(old)
|
||
continue
|
||
if login_taken(old) or login_taken(new) or count(models.User, models.User.display_name, old):
|
||
dropped.append(old)
|
||
continue
|
||
# 改完本人就带着新姓名了,所以"多出来的那一个"才算另有其人
|
||
if count(models.User, models.User.display_name, new) > 1:
|
||
dropped.append(old)
|
||
continue
|
||
kept_people[old] = new
|
||
|
||
return kept_units, kept_people, dropped, sorted(set(homonyms))
|
||
|
||
|
||
def _walk_json(value: Any, mapping: dict[str, str], report: RefReport, where: str) -> Any:
|
||
"""递归换掉 JSON 里等于旧值的字符串叶子。"""
|
||
if isinstance(value, str):
|
||
replacement = mapping.get(value)
|
||
if replacement:
|
||
report.rewritten += 1
|
||
report.sample(f"{where}:{value} -> {replacement}")
|
||
return replacement
|
||
return value
|
||
if isinstance(value, list):
|
||
return [_walk_json(item, mapping, report, where) for item in value]
|
||
if isinstance(value, dict):
|
||
return {key: _walk_json(item, mapping, report, where) for key, item in value.items()}
|
||
return value
|
||
|
||
|
||
def _move_bank_accounts(db: Session, accounts: dict[str, str], report: RefReport) -> None:
|
||
"""登录账号改名后,把按账号挂着的本地数据行(``oa_bank_account``)搬到新账号上。
|
||
|
||
个人收款账户不在 Hub 的清单里,同步只管 ``users`` 那几列;不搬就等于把人的银行卡落在
|
||
一个已经不存在的账号上——他下次打开个人资料是空的,报销单自动带出的还是上辈子的号。
|
||
|
||
``oa_bank_account.account`` 上有唯一索引,而本项目的 Session 关了 autoflush:一边循环
|
||
一边改,遇到甲乙互换账号就会撞上唯一键(和 ``hub_sync._apply_account_renames`` 里记的
|
||
是同一个坑),所以先把要搬的行统统挪到一个撞不上的临时值上 flush,再落最终值。
|
||
目标账号上还压着别人的行(早几轮删人留下的孤儿行)就不搬,只报出来:宁可少搬一条让人
|
||
去核对,也不要顶着唯一键把整趟人员同步顶失败。
|
||
"""
|
||
if not accounts:
|
||
return
|
||
rows = db.execute(
|
||
select(models.BankAccount).where(models.BankAccount.account.in_(list(accounts)))
|
||
).scalars().all()
|
||
if not rows:
|
||
return
|
||
plan = [(row, accounts[row.account], row.account) for row in rows]
|
||
for row, _new, _old in plan:
|
||
row.account = f"~hub-rename-{row.id}"[:190] # 没人会用这种账号,先把唯一键腾开
|
||
db.flush()
|
||
for row, new_account, old_account in plan:
|
||
occupied = db.execute(
|
||
select(models.BankAccount.id).where(
|
||
models.BankAccount.account == new_account,
|
||
models.BankAccount.id != row.id,
|
||
)
|
||
).first()
|
||
if occupied is not None:
|
||
row.account = old_account # 新账号上另有其行:原地退回,报出来待人工确认
|
||
report.accounts_stuck.append(old_account)
|
||
report.sample(f"收款账户:{old_account} 改成了 {new_account},没搬(新账号上已有一条)")
|
||
continue
|
||
row.account = new_account
|
||
report.accounts_moved += 1
|
||
db.flush()
|
||
|
||
|
||
def rewrite(db: Session, maps: Maps) -> RefReport:
|
||
"""按映射把配置里的人名/部门名/账号引用搬到新值。"""
|
||
report = RefReport()
|
||
if maps.empty:
|
||
return report
|
||
# 本项目的 Session 关了 autoflush:不先 flush 一下,下面这些"本地还有谁叫旧名"的
|
||
# 查询读到的还是改名之前的样子,会把每一个改名都误判成有歧义。
|
||
db.flush()
|
||
safe_units, safe_people, report.dropped_names, report.homonyms = _safe_names(
|
||
db, maps.unit_names, maps.person_names
|
||
)
|
||
report.skipped += len(report.dropped_names)
|
||
# 按登录账号挂着的本地数据行也在这次改名里,一起搬(放在 ``loose`` 那一步之前,
|
||
# 保证"只有账号改名、名字一个没动"的那趟同步也会走到这里)
|
||
_move_bank_accounts(db, maps.accounts, report)
|
||
loose = {**maps.strict, **safe_units, **safe_people}
|
||
if not loose:
|
||
return report
|
||
for model, column, label_field, allow_names in SELECTOR_COLUMNS:
|
||
mapping = loose if allow_names else maps.strict
|
||
if not mapping:
|
||
continue
|
||
for row in db.execute(select(model)).scalars().all():
|
||
value = getattr(row, column, None)
|
||
label = str(getattr(row, label_field, "") or row.__class__.__name__)
|
||
if isinstance(value, str):
|
||
replacement = mapping.get(value)
|
||
if replacement:
|
||
setattr(row, column, replacement)
|
||
report.rewritten += 1
|
||
report.sample(f"{label}({column}):{value} -> {replacement}")
|
||
elif isinstance(value, list):
|
||
changed = False
|
||
moved = []
|
||
for item in value:
|
||
if isinstance(item, str) and mapping.get(item):
|
||
moved.append(mapping[item])
|
||
report.rewritten += 1
|
||
report.sample(f"{label}({column}):{item} -> {mapping[item]}")
|
||
changed = True
|
||
else:
|
||
moved.append(item)
|
||
if changed:
|
||
deduped: list[Any] = []
|
||
for item in moved:
|
||
if item not in deduped:
|
||
deduped.append(item)
|
||
setattr(row, column, deduped)
|
||
for model, column, label_field in JSON_COLUMNS:
|
||
if not maps.strict:
|
||
continue
|
||
for row in db.execute(select(model)).scalars().all():
|
||
value = getattr(row, column, None)
|
||
if not isinstance(value, (dict, list)):
|
||
continue
|
||
label = str(getattr(row, label_field, "") or row.__class__.__name__)
|
||
setattr(row, column, _walk_json(value, maps.strict, report, f"{label}({column})"))
|
||
if report.rewritten:
|
||
logger.info("Hub 同步:搬走 %s 处按字符串存的审批/共享引用", report.rewritten)
|
||
if report.skipped:
|
||
logger.warning("Hub 同步:%s 个改名的名字有歧义,相关配置保持原样待人工确认", report.skipped)
|
||
return report
|
||
|
||
|
||
def scan(db: Session, maps: Maps, limit: int = 20) -> tuple[int, list[dict[str, str]]]:
|
||
"""只读预检:这些名字要是改了,会牵动哪几处配置。同步前的"影响预检"用它。"""
|
||
hits: list[dict[str, str]] = []
|
||
total = 0
|
||
if maps.empty:
|
||
return 0, hits
|
||
loose = maps.loose
|
||
for model, column, label_field, _allow_names in SELECTOR_COLUMNS:
|
||
for row in db.execute(select(model)).scalars().all():
|
||
value = getattr(row, column, None)
|
||
label = str(getattr(row, label_field, "") or row.__class__.__name__)
|
||
values = value if isinstance(value, list) else [value] if isinstance(value, str) else []
|
||
for item in values:
|
||
if isinstance(item, str) and loose.get(item):
|
||
total += 1
|
||
if len(hits) < limit:
|
||
hits.append(
|
||
{"where": f"{label} · {column}", "value": item, "becomes": loose[item]}
|
||
)
|
||
for model, column, label_field in JSON_COLUMNS:
|
||
for row in db.execute(select(model)).scalars().all():
|
||
value = getattr(row, column, None)
|
||
if not isinstance(value, (dict, list)):
|
||
continue
|
||
label = str(getattr(row, label_field, "") or row.__class__.__name__)
|
||
found: list[str] = []
|
||
_collect(value, loose, found)
|
||
for item in found:
|
||
total += 1
|
||
if len(hits) < limit:
|
||
hits.append({"where": f"{label} · {column}", "value": item, "becomes": loose[item]})
|
||
return total, hits
|
||
|
||
|
||
def _collect(value: Any, mapping: dict[str, str], out: list[str]) -> None:
|
||
if isinstance(value, str):
|
||
if mapping.get(value):
|
||
out.append(value)
|
||
elif isinstance(value, list):
|
||
for item in value:
|
||
_collect(item, mapping, out)
|
||
elif isinstance(value, dict):
|
||
for item in value.values():
|
||
_collect(item, mapping, out)
|
||
|
||
|
||
#: 运行态里按登录账号挂着的历史行。**故意不在 ``rewrite()`` 的搬运清单里**:那张单记的是
|
||
#: "当时的那个人",而表单数据里还嵌着同一串,搬它等于改写流程实例。
|
||
#:
|
||
#: 代价要写明白:登录账号改了名,这些行就从"我发起的""我的待办"里消失(查询用的是等号)。
|
||
#: 这是"只存登录账号"这套口径唯一剩下的尖角,也是它要求的不变量本身——**账号不改**。
|
||
#: 同步能做的只有把它数出来报进同步记录,别让人第二天自己发现。
|
||
RUNTIME_PERSON_COLUMNS: tuple[tuple[Any, str, str], ...] = (
|
||
(models.Work, "creator_identity", "我发起的"),
|
||
(models.WorkCompleted, "creator_identity", "已办结的单"),
|
||
(models.Task, "identity", "我的待办"),
|
||
(models.TaskCompleted, "identity", "我的已办"),
|
||
(models.Read, "identity", "我的待阅"),
|
||
(models.ReadCompleted, "identity", "我的已阅"),
|
||
(models.Notification, "identity", "通知"),
|
||
(models.Draft, "identity", "草稿"),
|
||
)
|
||
|
||
|
||
def runtime_drift(db: Session, accounts: dict[str, str]) -> list[tuple[str, str, int]]:
|
||
"""账号改了名,运行态里还压着多少条按旧账号存的行:``[(旧账号, 新账号, 行数), ...]``。
|
||
|
||
只数不改。给同步记录用(见 ``hub_sync._carry_references``)。
|
||
"""
|
||
if not accounts:
|
||
return []
|
||
out: list[tuple[str, str, int]] = []
|
||
for old, new in accounts.items():
|
||
total = 0
|
||
for model, column, _label in RUNTIME_PERSON_COLUMNS:
|
||
total += int(
|
||
db.execute(
|
||
select(func.count()).select_from(model).where(getattr(model, column) == old)
|
||
).scalar() or 0
|
||
)
|
||
if total:
|
||
out.append((old, new, total))
|
||
return out
|
||
|
||
|
||
def stale_references(
|
||
db: Session, values: set[str], limit: int = 20
|
||
) -> tuple[int, list[dict[str, str]]]:
|
||
"""同步之后仍然解析不到人的引用清单,只看 ``values`` 里那些名字。
|
||
|
||
这些是"名字改了、但配置里的引用因为歧义没敢自动搬"的死角:流程走到那个环节才会发现
|
||
没人可派,而且界面上不报错。同步记录里主动把它们报出来,比让人第二天查强。
|
||
"""
|
||
broken: list[dict[str, str]] = []
|
||
total = 0
|
||
if not values:
|
||
return 0, broken
|
||
seen: set[str] = set()
|
||
for model, column, label_field, _allow_names in SELECTOR_COLUMNS:
|
||
for row in db.execute(select(model)).scalars().all():
|
||
value = getattr(row, column, None)
|
||
label = str(getattr(row, label_field, "") or row.__class__.__name__)
|
||
items = value if isinstance(value, list) else [value] if isinstance(value, str) else []
|
||
for item in items:
|
||
if not isinstance(item, str) or item not in values or item in seen:
|
||
continue
|
||
seen.add(item)
|
||
if org._expand(db, item) == [item]:
|
||
total += 1
|
||
if len(broken) < limit:
|
||
broken.append({"where": f"{label} · {column}", "value": item})
|
||
return total, broken
|