764 lines
35 KiB
Python
764 lines
35 KiB
Python
#!/usr/bin/env python3
|
||
"""把还存着"身份 DN"的引用列换成登录账号(多身份下线之后该做而没做的那一步)。
|
||
|
||
为什么会有这笔账
|
||
================
|
||
"一人多身份"那套 2026-10 整张下线之后,认人只认 ``users.account``。可引用是**按字符串**
|
||
存在配置里的:审批岗位成员 ``oa_role.list_auth``、日程归属人 ``oa_schedule.owner``、
|
||
网盘归属与共享 ``oa_file.owner`` / ``shared_identities``、流程可见/可发起人、代理人、
|
||
环节审批人 ``oa_activity.config.taskValues``……那里头存的是老的 O2OA 身份 DN
|
||
(``紫光汇智\\经营管理中心\\张梅\\zhangmei``、``系统管理员\\localadmin``),下线之后一个都解析不到人。
|
||
|
||
``migrate_to_users_table.py`` 当时明确写着"人名、身份 DN 一律不碰"——那时 DN 还认得,
|
||
这句话是对的;多身份一删,这句话就把这批引用留在了原地。后果不报错:环节审批人算出来是空的、
|
||
流程卡在第一个节点、日程与网盘的归属人显示成原始那串 DN。全站 14 个审批岗位**全部**解析
|
||
得出 0 人就是这个。
|
||
|
||
换算规则(宁可少改,不许改错审批人)
|
||
====================================
|
||
只动**现在解析不出任何人**的那几条,认得出的原样留着:
|
||
|
||
1. DN 最后一段是库里存在的登录账号 → 换成那个账号(``…\\张梅\\zhangmei`` -> ``zhangmei``);
|
||
2. 最后一段不是账号,但倒数第二段恰好只有一个同名的在职人 → 换成他的账号;
|
||
3. 剩下的(人不在库里、或者有歧义)一律不动,报出来由人去看——设计器把它报红是对的,
|
||
悄悄改成一个可能不对的审批人是错的。
|
||
|
||
默认只体检不写库,看清清单再加 ``--apply``::
|
||
|
||
PYTHONPATH=. python3 scripts/migrate_identity_refs.py # 看
|
||
PYTHONPATH=. python3 scripts/migrate_identity_refs.py --apply # 改
|
||
|
||
运行态那批历史行(``--runtime``)
|
||
================================
|
||
配置之外还有一大堆**运行态与历史行**也按字符串存着人:待办归谁 ``oa_task.identity``、
|
||
待阅归谁 ``oa_read.identity``、站内信发给谁 ``oa_notification.identity``、流转日志里
|
||
谁做的 ``oa_work_log.from_identity``、已办与操作日志、会议与评论……多身份下线之后这一批
|
||
同样解析不出人:那些单子的待办没人看得见、站内信没人收得到、日志上显示的是原始那串 DN。
|
||
|
||
``hub_refs`` 对运行态行的口径是"按账号挂着的行不搬"——那条讲的是**账号改名**,这里是
|
||
整个坐标系换掉了,那些字符串不是旧,是**读不出**。所以这一档单独开关、单独跑:
|
||
|
||
PYTHONPATH=. python3 scripts/migrate_identity_refs.py --runtime # 看
|
||
PYTHONPATH=. python3 scripts/migrate_identity_refs.py --runtime --apply # 改
|
||
|
||
配置那一档是默认跑的,这一档必须明写:它动的是历史留痕,不是配置。换算规则一模一样,
|
||
认不出的一律不动。常驻门 ``check_identity_refs.py`` 只钉配置那一档——历史行允许有
|
||
"人已经不在库里"的情况,不该把门钉红。
|
||
表单数据里选人那一格(``--form-data``)
|
||
======================================
|
||
还有一处既不属配置、也不属"某一列存人":**单据数据那一整份 JSON**。哪一格是人
|
||
按**字段类型**(``type: user``,含明细表里的选人列)说的,列名上看不出来,所以前两档都扫不到它。
|
||
最初那条故障就长在这里——``{"applicant": ["管理员\\DSH Hub Admin\\DSH Hub Admin"]}``
|
||
让 ``where account = :applicant`` 永远查不出收款账户,而报回来的只是"没查到数据"。
|
||
|
||
PYTHONPATH=. python3 scripts/migrate_identity_refs.py --form-data # 看
|
||
PYTHONPATH=. python3 scripts/migrate_identity_refs.py --form-data --apply # 只改在办与草稿
|
||
PYTHONPATH=. python3 scripts/migrate_identity_refs.py --form-data --all --apply # 连归档件一起
|
||
|
||
在办与草稿那一格认不出人,带出、额度、审批人解析就一起空,是现在还疼的;办结那一份记的是
|
||
"当时的张三",允许原样留着,所以常驻门只钉前者。文本格子里带反斜杠的(``a\\b\\c``)
|
||
一条都不碰,口径与 ``formruntime.normalize_person_values`` 同一份。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import json
|
||
import sys
|
||
from dataclasses import dataclass, field
|
||
from pathlib import Path
|
||
|
||
sys.path.insert(0, str(Path(__file__).resolve().parents[0].parent))
|
||
sys.path.insert(0, str(Path(__file__).resolve().parents[0]))
|
||
|
||
from sqlalchemy import select, text # noqa: E402
|
||
from sqlalchemy.orm import Session # noqa: E402
|
||
|
||
from sqlalchemy.orm.attributes import flag_modified # noqa: E402
|
||
|
||
from app import models # noqa: E402
|
||
from app.db import SessionLocal # noqa: E402
|
||
from app.service import formruntime, hub_refs, org # noqa: E402
|
||
|
||
|
||
@dataclass
|
||
class Hit:
|
||
"""一处解析不出人的引用,连它落在哪一格一起记下来,改写时不必再找一遍。
|
||
|
||
``account`` 为空表示换算不出来,只能报给人看;``json_path`` 是给
|
||
``oa_activity.config`` 这种 JSON 列用的(同一行里要改的是第几条审批人配置的 data)。
|
||
"""
|
||
|
||
model: type
|
||
pk: object
|
||
column: str
|
||
row_label: str
|
||
old: str
|
||
account: str
|
||
reason: str
|
||
json_path: tuple[str, int] = ("", -1)
|
||
|
||
@property
|
||
def where(self) -> str:
|
||
base = f"{self.model.__tablename__}.{self.column}"
|
||
return f"{base}[{self.row_label}]" if self.json_path[0] else base
|
||
|
||
|
||
@dataclass
|
||
class Scan:
|
||
migratable: list[Hit] = field(default_factory=list)
|
||
stuck: list[Hit] = field(default_factory=list)
|
||
|
||
@property
|
||
def total(self) -> int:
|
||
return len(self.migratable) + len(self.stuck)
|
||
|
||
|
||
def _people(db: Session) -> tuple[set[str], dict[str, list[str]]]:
|
||
"""一次把全库账号与"姓名 -> 账号"取回来,换算全靠这两份,不再逐条问库。"""
|
||
by_account: set[str] = set()
|
||
by_name: dict[str, list[str]] = {}
|
||
for account, display_name in db.execute(
|
||
select(models.User.account, models.User.display_name)
|
||
).all():
|
||
account = str(account or "")
|
||
by_account.add(account)
|
||
by_name.setdefault(str(display_name or "").strip(), []).append(account)
|
||
return by_account, by_name
|
||
|
||
|
||
def _account_for(value: str, by_account: set[str], by_name: dict[str, list[str]]) -> tuple[str, str]:
|
||
"""把一个解析不出人的字符串换成登录账号;换不出来返回空串与原因。"""
|
||
parts = [p for p in str(value).split("\\") if p]
|
||
if len(parts) < 2:
|
||
return "", "既不是 DN 形状,也不认识"
|
||
tail, named = parts[-1], parts[-2]
|
||
if tail in by_account:
|
||
return tail, f"DN 最后一段就是账号 {tail}"
|
||
hits = by_name.get(named, [])
|
||
if len(hits) == 1:
|
||
return hits[0], f"按倒数第二段的人名 {named} 唯一命中 {hits[0]}"
|
||
if len(hits) > 1:
|
||
return "", f"倒数第二段 {named} 库里有 {len(hits)} 个人同名,不敢挑"
|
||
return "", f"库里既没有账号 {tail},也没有叫 {named} 的人"
|
||
|
||
|
||
def _classify(
|
||
db: Session,
|
||
values: list[str],
|
||
*,
|
||
model: type,
|
||
pk: object,
|
||
column: str,
|
||
row_label: str,
|
||
people: tuple[set[str], dict[str, list[str]]],
|
||
json_path: tuple[str, int] = ("", -1),
|
||
out: Scan | None = None,
|
||
) -> list[Hit]:
|
||
"""一批成员值 -> 待换算清单;认得出人的那些一条都不进结果。"""
|
||
cleaned = [str(v).strip() for v in values if str(v or "").strip()]
|
||
if not cleaned:
|
||
return []
|
||
_resolved, unknown = org.split_selectors(db, cleaned)
|
||
by_account, by_name = people
|
||
hits: list[Hit] = []
|
||
for value in unknown:
|
||
account, reason = _account_for(value, by_account, by_name)
|
||
hits.append(Hit(model=model, pk=pk, column=column, row_label=row_label,
|
||
old=value, account=account, reason=reason, json_path=json_path))
|
||
if out is not None:
|
||
for hit in hits:
|
||
(out.migratable if hit.account else out.stuck).append(hit)
|
||
return hits
|
||
|
||
|
||
def scan(db: Session) -> Scan:
|
||
"""扫一遍 ``hub_refs.SELECTOR_COLUMNS`` 登记表与环节审批人配置,找出还指着身份 DN 的引用。"""
|
||
people = _people(db)
|
||
result = Scan()
|
||
for model, column, label_col, _loose in hub_refs.SELECTOR_COLUMNS:
|
||
for row in db.execute(select(model)).scalars().all():
|
||
raw = getattr(row, column, None)
|
||
values = raw if isinstance(raw, list) else ([raw] if raw else [])
|
||
_classify(db, [str(v) for v in values], model=model, pk=row.id, column=column,
|
||
row_label=str(getattr(row, label_col, "?")), people=people, out=result)
|
||
|
||
for act in db.execute(select(models.Activity)).scalars().all():
|
||
cfg = act.config if isinstance(act.config, dict) else {}
|
||
for index, row in enumerate(cfg.get("taskValues") or []):
|
||
if not isinstance(row, dict):
|
||
continue
|
||
# 动态来源(表单字段 / 发起人 / 上一环节…)里存的是字段名或关键字,不是人
|
||
if org.normalize_kind(row.get("type")) not in org.SELECTOR_KINDS:
|
||
continue
|
||
data = row.get("data") or []
|
||
if isinstance(data, str):
|
||
data = [data]
|
||
_classify(db, [str(v) for v in data], model=models.Activity, pk=act.id, column="config",
|
||
row_label=str(act.name or act.id), people=people,
|
||
json_path=("taskValues", index), out=result)
|
||
return result
|
||
|
||
|
||
def apply_fixes(db: Session, result: Scan) -> int:
|
||
"""按 :func:`scan` 的结论改写;按主键定位,一格只碰它自己那一列。"""
|
||
#: ``(模型, 主键, 列, JSON 路径) -> {旧值: 新账号}``
|
||
plan: dict[tuple, dict[str, str]] = {}
|
||
for hit in result.migratable:
|
||
key = (hit.model, hit.pk, hit.column, hit.json_path)
|
||
plan.setdefault(key, {})[hit.old] = hit.account
|
||
|
||
changed = 0
|
||
for (model, pk, column, json_path), mapping in plan.items():
|
||
row = db.get(model, pk)
|
||
if row is None:
|
||
continue
|
||
if json_path[0]:
|
||
cfg = dict(getattr(row, column) or {})
|
||
rows = [dict(item) if isinstance(item, dict) else item
|
||
for item in (cfg.get(json_path[0]) or [])]
|
||
if json_path[1] >= len(rows) or not isinstance(rows[json_path[1]], dict):
|
||
continue
|
||
item = rows[json_path[1]]
|
||
data = item.get("data") or []
|
||
if isinstance(data, str):
|
||
data = [data]
|
||
new = [mapping.get(str(v).strip(), v) for v in data]
|
||
if new == list(data):
|
||
continue
|
||
item["data"] = new
|
||
cfg[json_path[0]] = rows
|
||
setattr(row, column, cfg)
|
||
changed += 1
|
||
continue
|
||
raw = getattr(row, column)
|
||
if isinstance(raw, list):
|
||
new = [mapping.get(str(v).strip(), v) for v in raw]
|
||
if new == list(raw):
|
||
continue
|
||
elif str(raw or "").strip() in mapping:
|
||
new = mapping[str(raw).strip()]
|
||
else:
|
||
continue
|
||
setattr(row, column, new)
|
||
changed += 1
|
||
db.commit()
|
||
return changed
|
||
|
||
|
||
#: 运行态与历史行里按字符串存人的那些列:``(表, 列, 是不是 JSON 清单)``。
|
||
#: 与 ``hub_refs.SELECTOR_COLUMNS`` 分开列:那一份是"配置会悄悄失效",这一份是
|
||
#: "历史留痕读不出来",两者的处置与风险不是一回事,所以各开一个开关。
|
||
RUNTIME_COLUMNS: tuple[tuple[str, str, bool], ...] = (
|
||
("oa_work", "creator_identity", False),
|
||
("oa_work", "manual_identity_list", True),
|
||
("oa_work_completed", "creator_identity", False),
|
||
("oa_task", "identity", False),
|
||
("oa_task", "creator_identity", False),
|
||
("oa_task", "prev_task_identity", False),
|
||
("oa_task", "prev_task_identity_list", True),
|
||
("oa_task_completed", "identity", False),
|
||
("oa_task_completed", "creator_identity", False),
|
||
("oa_task_completed", "prev_task_identity", False),
|
||
("oa_task_completed", "prev_task_identity_list", True),
|
||
("oa_task_completed", "empower_from_identity", False),
|
||
("oa_read", "identity", False),
|
||
("oa_read", "creator_identity", False),
|
||
("oa_read", "source_identity", False),
|
||
("oa_read_completed", "identity", False),
|
||
("oa_read_completed", "creator_identity", False),
|
||
("oa_read_completed", "source_identity", False),
|
||
("oa_notification", "identity", False),
|
||
("oa_work_log", "from_identity", False),
|
||
("oa_work_comment", "identity", False),
|
||
("oa_operation_log", "identity", False),
|
||
("oa_meeting", "creator_identity", False),
|
||
("oa_meeting_attendee", "identity", False),
|
||
# 下面这几列是这一轮对着 information_schema 全表比出来补的:名字像"存人",
|
||
# 以前两份清单都没管过(今天库里是干净的,但"今天干净"不等于"以后不用扫")
|
||
("oa_draft", "identity", False),
|
||
("oa_notify_delivery", "identity", False),
|
||
("oa_cms_document", "author_identity", False),
|
||
("oa_task", "empower_from_identity", False),
|
||
("oa_task", "agent_from_identity", False),
|
||
("oa_task_completed", "empower_to_identity", False),
|
||
("oa_task_completed", "next_task_identity_list", True),
|
||
# 第三方替某个环节表态时留下的一行:这一列记的是**它代的是哪条待办的处理人**,
|
||
# 与人绑死(口径同 oa_task.identity),身份从 DN 换成账号时这行历史也得跟着走
|
||
("oa_node_decision", "task_identity", False),
|
||
)
|
||
|
||
|
||
#: JSON 格子里挂着人引用的那几处:``(表, 列, 键名…)``,假定主键列叫 ``id``。
|
||
#: ``oa_work.go_back_store`` 是"退回后回哪个环节"那份暂存,里面的 ``identity``
|
||
#: 存的是经办人的 ``Actor.ref``——它不是一整列,而是一份 JSON 里的一个键,
|
||
#: 按列名扫的那两份清单天生看不见它。
|
||
RUNTIME_BLOBS: tuple[tuple[str, str, tuple[str, ...]], ...] = (
|
||
("oa_work", "go_back_store", ("identity",)),
|
||
)
|
||
|
||
|
||
@dataclass
|
||
class RuntimePlan:
|
||
"""``{(表, 列): {库里的原值: 换好的新值}}``;JSON 清单那类整串换,不拆散。"""
|
||
|
||
#: ``{(表, 列): {库里的原值: 换好的新值}}``
|
||
plan: dict[tuple[str, str], dict[str, str]] = field(default_factory=dict)
|
||
#: JSON 格子那一类按主键改:``{(表, 列): {主键: 换好的整份 JSON}}``
|
||
blob_plan: dict[tuple[str, str], dict[object, str]] = field(default_factory=dict)
|
||
#: ``{(表, 列): 还认不出的那串}``
|
||
stuck: dict[tuple[str, str], set[str]] = field(default_factory=dict)
|
||
|
||
@property
|
||
def cells(self) -> int:
|
||
"""JSON 格子里要改的键数(这一类没有"整列同一个值"可数,数主键×键)。"""
|
||
return sum(len(mapping) for mapping in self.blob_plan.values())
|
||
|
||
@property
|
||
def values(self) -> int:
|
||
return sum(len(mapping) for mapping in self.plan.values())
|
||
|
||
|
||
def _swap_in_list(raw: str, people: tuple[set[str], dict[str, list[str]]]
|
||
) -> tuple[str | None, list[str]]:
|
||
"""JSON 清单那一类:逐个成员换算,回 ``(换好的整串, 换不出的成员)``。
|
||
|
||
整串不能当成一个人去换算——``["张三","李四"]`` 里最后一个反斜杠后面挂着的是
|
||
``"]"``,拿整串去认账号只会认出一串垃圾,写回去还会把这一列从 JSON 数组变成裸字符串。
|
||
"""
|
||
try:
|
||
items = json.loads(raw)
|
||
except ValueError:
|
||
return None, [raw]
|
||
if not isinstance(items, list):
|
||
return None, [raw]
|
||
out: list[object] = []
|
||
unknown: list[str] = []
|
||
changed = False
|
||
for item in items:
|
||
text_value = str(item or "")
|
||
if "\\" not in text_value:
|
||
out.append(item)
|
||
continue
|
||
account, _reason = _account_for(text_value, *people)
|
||
if account:
|
||
out.append(account)
|
||
changed = True
|
||
else:
|
||
out.append(item)
|
||
unknown.append(text_value)
|
||
if not changed:
|
||
return None, unknown
|
||
return json.dumps(out, ensure_ascii=False), unknown
|
||
|
||
|
||
def scan_runtime(db: Session) -> RuntimePlan:
|
||
"""扫运行态与历史行:把含反斜杠、且能换算成账号的那批值挑出来。
|
||
|
||
只认"含反斜杠"的值——运行态列里正常存的就是账号,一串带反斜杠的只可能是老 DN;
|
||
认不出的(人不在库里)原样留着,由报告交出去。
|
||
"""
|
||
people = _people(db)
|
||
result = RuntimePlan()
|
||
for table, column, is_list in RUNTIME_COLUMNS:
|
||
# 不用 LIKE 过滤反斜杠:MySQL 的 LIKE 还要再解一层转义,写法一错就静默匹配不到
|
||
# 任何东西(第一版就是这么扫出 0 条的)。DISTINCT 之后的值本来就没几个,
|
||
# 取回来在 Python 里认这个反斜杠,看得懂也错不了。
|
||
rows = db.execute(text(f"SELECT DISTINCT `{column}` AS v FROM `{table}`")).all()
|
||
for row in rows:
|
||
raw = str(row[0] or "")
|
||
if not raw or "\\" not in raw:
|
||
continue
|
||
if is_list:
|
||
new_value, unknown = _swap_in_list(raw, people)
|
||
if new_value is not None:
|
||
result.plan.setdefault((table, column), {})[raw] = new_value
|
||
for piece in unknown:
|
||
result.stuck.setdefault((table, column), set()).add(piece)
|
||
continue
|
||
account, reason = _account_for(raw, *people)
|
||
if account:
|
||
result.plan.setdefault((table, column), {})[raw] = account
|
||
else:
|
||
result.stuck.setdefault((table, column), set()).add(f"{raw}({reason})")
|
||
for table, column, keys in RUNTIME_BLOBS:
|
||
# JSON 格子没有"整列一个值"可换,只能连着主键一行一行看;这一列平时是空的,
|
||
# 只有退回过又没走完的单子上才挂着东西,一趟全表读不贵
|
||
for pk, raw in db.execute(text(f"SELECT `id`, `{column}` FROM `{table}`")).all():
|
||
if raw is None or raw == "" or raw == {} or raw == []:
|
||
continue
|
||
blob = raw if isinstance(raw, dict) else _json_of(raw)
|
||
if not isinstance(blob, dict):
|
||
continue
|
||
changed, unknown = _blob_swaps(blob, keys, people)
|
||
for key, value in unknown:
|
||
result.stuck.setdefault((table, column), set()).add(f"{key}={value}")
|
||
if changed:
|
||
merged = {**blob, **changed}
|
||
result.blob_plan.setdefault((table, column), {})[pk] = json.dumps(
|
||
merged, ensure_ascii=False)
|
||
return result
|
||
|
||
|
||
def _blob_swaps(blob: dict, keys: tuple[str, ...],
|
||
people: tuple[set[str], dict[str, list[str]]]) -> tuple[dict[str, str], list[tuple[str, str]]]:
|
||
"""JSON 格子里点名的那几个键逐个换算,回 ``({键: 新账号}, [(键, 换不出的原值)])``。
|
||
|
||
抽成不带库的一小段是为了能在门里断言:这一档改的是运行态数据,判断错了没人看得见。
|
||
"""
|
||
changed: dict[str, str] = {}
|
||
unknown: list[tuple[str, str]] = []
|
||
for key in keys:
|
||
value = str(blob.get(key) or "")
|
||
if "\\" not in value:
|
||
continue
|
||
account, _reason = _account_for(value, *people)
|
||
if account:
|
||
changed[key] = account
|
||
else:
|
||
unknown.append((key, value))
|
||
return changed, unknown
|
||
|
||
|
||
def _json_of(raw: object) -> object:
|
||
"""JSON 列可能回来的是 dict,也可能是一串文本(驱动与版本有关),两种都接住。"""
|
||
try:
|
||
return json.loads(str(raw))
|
||
except (TypeError, ValueError):
|
||
return None
|
||
|
||
|
||
def apply_runtime(db: Session, plan: RuntimePlan) -> int:
|
||
"""一条 (表, 列, 旧值) 一句 UPDATE:值只有一个,用不着把整表读进内存再逐行比。
|
||
|
||
JSON 清单那一列要 ``WHERE CAST(col AS CHAR) = :old``:MySQL 里 **JSON 值永远不等于
|
||
字符串**,直接拿等号比会一声不响地匹配 0 行(第一版就这么"改成功"了三列,复查才发现
|
||
一行没动)。JSON 列也不能整串当成一个值去 SET——那会把数组写成裸字符串。
|
||
"""
|
||
is_list = {(table, column): flag for table, column, flag in RUNTIME_COLUMNS}
|
||
changed = 0
|
||
for (table, column), mapping in plan.plan.items():
|
||
where = (f"CAST(`{column}` AS CHAR) = :old" if is_list[(table, column)]
|
||
else f"`{column}` = :old")
|
||
for old_value, new_value in mapping.items():
|
||
got = db.execute(
|
||
text(f"UPDATE `{table}` SET `{column}` = :new WHERE {where}"),
|
||
{"new": new_value, "old": old_value},
|
||
)
|
||
changed += int(getattr(got, "rowcount", 0) or 0)
|
||
for (table, column), by_pk in plan.blob_plan.items():
|
||
# JSON 列收的是一串合法 JSON 文本,MySQL 自己解析;按主键一行一句
|
||
for pk, new_value in by_pk.items():
|
||
got = db.execute(
|
||
text(f"UPDATE `{table}` SET `{column}` = :new WHERE `id` = :pk"),
|
||
{"new": new_value, "pk": pk},
|
||
)
|
||
changed += int(getattr(got, "rowcount", 0) or 0)
|
||
db.commit()
|
||
return changed
|
||
|
||
|
||
def report_runtime(plan: RuntimePlan) -> None:
|
||
print(f"运行态/历史行:{len(plan.plan)} 列上有可换算的身份 DN,共 {plan.values} 个不同的值")
|
||
for (table, column), mapping in sorted(plan.plan.items()):
|
||
sample = list(mapping.items())[:2]
|
||
pairs = "、".join(f"{old} -> {new}" for old, new in sample)
|
||
print(f" {table}.{column}: {len(mapping)} 个值 例:{pairs}")
|
||
for (table, column), by_pk in sorted(plan.blob_plan.items()):
|
||
print(f" {table}.{column}: {len(by_pk)} 份 JSON 里的人引用可换算(按主键改)")
|
||
for (table, column), stuck in sorted(plan.stuck.items()):
|
||
print(f" [留] {table}.{column}: {len(stuck)} 个值换算不出 —— {sorted(stuck)[:2]}")
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 表单数据里选人那一格:配置登记表与运行态列都不含它,单独一档
|
||
# ---------------------------------------------------------------------------
|
||
|
||
#: 存表单数据的那几张表:``(模型, 数据列, 这一档叫什么)``。
|
||
#: 在办与草稿单独看成一组:那一格认不出人,带出、额度、审批人解析就一起空掉,
|
||
#: 是"现在还疼"的;办结那一份记的是"当时的张三",允许原样留着,
|
||
#: 所以常驻门只钉前者,别把归档件变成一盏常红灯。
|
||
FORM_DATA_TABLES: tuple[tuple[type, str, str], ...] = (
|
||
(models.Work, "data", "在办"),
|
||
(models.Draft, "data", "草稿"),
|
||
(models.WorkCompleted, "data", "办结"),
|
||
)
|
||
|
||
|
||
@dataclass
|
||
class CellHit:
|
||
"""单据数据里选人那一格上的一个值,连它挂在哪一格一起记下来,改写时不必再找一遍。
|
||
|
||
``path`` 是改写用的路径:``("field", 格子名)`` 是主表那一格,
|
||
``("table", 格子名, 行号, 列名)`` 是明细表里的选人列。拿整份 ``data`` 去猜
|
||
会连文本格子里那串 ``a\\b\\c`` 一起改掉,那一刀是明令禁止的。
|
||
"""
|
||
|
||
model: type
|
||
column: str
|
||
pk: object
|
||
bucket: str
|
||
label: str
|
||
cell: str
|
||
old: str
|
||
account: str
|
||
reason: str
|
||
path: tuple
|
||
|
||
@property
|
||
def where(self) -> str:
|
||
return f"{self.model.__tablename__}.{self.cell}"
|
||
|
||
|
||
@dataclass
|
||
class FormDataPlan:
|
||
migratable: list[CellHit] = field(default_factory=list)
|
||
stuck: list[CellHit] = field(default_factory=list)
|
||
|
||
def live(self) -> list[CellHit]:
|
||
"""还活着的那几张单:在办 + 草稿。"""
|
||
return [hit for hit in self.migratable if hit.bucket != "办结"]
|
||
|
||
def done(self) -> list[CellHit]:
|
||
return [hit for hit in self.migratable if hit.bucket == "办结"]
|
||
|
||
|
||
def _person_cells(db: Session) -> dict[str, tuple[set[str], dict[str, set[str]]]]:
|
||
"""每张表单里"选人"的那几格:主表 ``type=user`` 加明细表里的选人列。
|
||
|
||
口径与 ``formruntime.normalize_person_values`` 一字不差——落库前洗的就是这几格,
|
||
体检扫的也必须是同样这几格;文本格子里带反斜杠的那种照旧一律不碰。
|
||
"""
|
||
out: dict[str, tuple[set[str], dict[str, set[str]]]] = {}
|
||
for row in db.execute(select(models.FormElement)).scalars().all():
|
||
keys: set[str] = set()
|
||
detail: dict[str, set[str]] = {}
|
||
for field_def in (row.content or {}).get("fields") or []:
|
||
if not isinstance(field_def, dict):
|
||
continue
|
||
key = str(field_def.get("key") or "")
|
||
kind = str(field_def.get("type") or "")
|
||
if not key:
|
||
continue
|
||
if kind == "user":
|
||
keys.add(key)
|
||
elif kind == "table":
|
||
cols = {str(item.get("key") or "") for item in formruntime.columns_of(field_def)
|
||
if str(item.get("type") or "") == "user"}
|
||
if cols:
|
||
detail[key] = {name for name in cols if name}
|
||
out[str(row.id)] = (keys, detail)
|
||
# 老单据那一列存过表单名,两种写法都认,免得体检自己先漏一批
|
||
out.setdefault(str(row.name or ""), (keys, detail))
|
||
return out
|
||
|
||
|
||
def _classify_cell(
|
||
plan: FormDataPlan, *, model: type, column: str, pk: object, bucket: str, label: str,
|
||
cell: str, path: tuple, value: object, people: tuple[set[str], dict[str, list[str]]]
|
||
) -> None:
|
||
"""一格(多选装的是数组)逐个值判:只有含反斜杠的才碰,认不出的一律不动。"""
|
||
for item in (value if isinstance(value, list) else [value]):
|
||
text_value = str(item or "")
|
||
if not text_value or "\\" not in text_value:
|
||
continue
|
||
account, reason = _account_for(text_value, *people)
|
||
hit = CellHit(model=model, column=column, pk=pk, bucket=bucket, label=label, cell=cell,
|
||
old=text_value, account=account, reason=reason, path=path)
|
||
(plan.migratable if account else plan.stuck).append(hit)
|
||
|
||
|
||
def scan_form_data(db: Session) -> FormDataPlan:
|
||
"""扫单据数据里选人那一格:这一档不在配置登记表里,也不在运行态列里。
|
||
|
||
为什么单独扫:那两处扫的都是"某一列存人",而表单数据是一整份 JSON,
|
||
哪一格是人按**字段类型**说的,不是按列名说的。最初的故障就从这里来——
|
||
``{"applicant": ["管理员\\DSH Hub Admin\\DSH Hub Admin"]}`` 让
|
||
``where account = :applicant`` 永远查不出收款账户,而它既不在配置列也不在运行态列里。
|
||
"""
|
||
people = _people(db)
|
||
cells_by_form = _person_cells(db)
|
||
plan = FormDataPlan()
|
||
for model, column, bucket in FORM_DATA_TABLES:
|
||
for row in db.execute(select(model)).scalars().all():
|
||
cells = cells_by_form.get(str(getattr(row, "form", "") or ""))
|
||
data = getattr(row, column, None)
|
||
if not cells or not isinstance(data, dict):
|
||
continue
|
||
keys, detail = cells
|
||
label = str(getattr(row, "title", "") or row.id)[:22]
|
||
for name in sorted(keys):
|
||
if name in data:
|
||
_classify_cell(plan, model=model, column=column, pk=row.id, bucket=bucket,
|
||
label=label, cell=name, path=("field", name),
|
||
value=data[name], people=people)
|
||
for name, cols in detail.items():
|
||
rows_value = data.get(name)
|
||
if not isinstance(rows_value, list):
|
||
continue
|
||
for index, item in enumerate(rows_value):
|
||
if not isinstance(item, dict):
|
||
continue
|
||
for col in sorted(cols):
|
||
if col in item:
|
||
_classify_cell(plan, model=model, column=column, pk=row.id,
|
||
bucket=bucket, label=label,
|
||
cell=f"{name}[{index}].{col}",
|
||
path=("table", name, index, col),
|
||
value=item[col], people=people)
|
||
return plan
|
||
|
||
|
||
def _swap_value(value: object, mapping: dict[str, str]) -> object:
|
||
"""一格里的值按表换:数组逐个换,形状不变(多选不能换成一个)。"""
|
||
if isinstance(value, list):
|
||
return [mapping.get(str(item or "").strip(), item) for item in value]
|
||
return mapping.get(str(value or "").strip(), value)
|
||
|
||
|
||
def _write_cell(data: dict, path: tuple, mapping: dict[str, str]) -> dict:
|
||
"""按路径写回那一格,返回**新的**那一份:整份 data 与明细行都不就地改。
|
||
|
||
与 ``formruntime.normalize_person_values`` 同一分寸——明细行是调用方手里那份
|
||
``data`` 里的同一批对象,就地改等于顺手改了别人手上的快照(拿 ORM 属性直接改还会
|
||
绕过 JSON 列的脏标记)。写回走 ``flag_modified``,改的始终是复制出来的那一份。
|
||
"""
|
||
out = dict(data)
|
||
if path[0] == "field":
|
||
out[path[1]] = _swap_value(out.get(path[1]), mapping)
|
||
return out
|
||
key, index, column = path[1], path[2], path[3]
|
||
rows = out.get(key)
|
||
if not isinstance(rows, list) or index >= len(rows) or not isinstance(rows[index], dict):
|
||
return out
|
||
rows = [dict(item) if isinstance(item, dict) else item for item in rows]
|
||
rows[index][column] = _swap_value(rows[index].get(column), mapping)
|
||
out[key] = rows
|
||
return out
|
||
|
||
|
||
def apply_form_data(db: Session, plan: FormDataPlan) -> int:
|
||
"""一份 ``data`` 只读改写一遍;JSON 列改完必须 ``flag_modified`` 才写得住。"""
|
||
grouped: dict[tuple[type, object], list[CellHit]] = {}
|
||
for hit in plan.migratable:
|
||
grouped.setdefault((hit.model, hit.pk), []).append(hit)
|
||
cells = 0
|
||
for (model, pk), hits in grouped.items():
|
||
row = db.get(model, pk)
|
||
if row is None:
|
||
continue
|
||
column = hits[0].column
|
||
data = dict(getattr(row, column) or {})
|
||
by_path: dict[tuple, dict[str, str]] = {}
|
||
for hit in hits:
|
||
by_path.setdefault(hit.path, {})[str(hit.old).strip()] = hit.account
|
||
for path, mapping in by_path.items():
|
||
data = _write_cell(data, path, mapping)
|
||
cells += 1
|
||
setattr(row, column, data)
|
||
flag_modified(row, column)
|
||
db.commit()
|
||
return cells
|
||
|
||
|
||
def _live_only(plan: FormDataPlan) -> FormDataPlan:
|
||
"""只留还活着的那几张单(在办与草稿)。
|
||
|
||
``--form-data --apply`` 默认走这一层:与 ``--runtime`` 同一分寸——**动历史留痕
|
||
要另写一个开关**。办结那份按口径是"当时的张三",想连它一起换得明写 ``--all``。
|
||
"""
|
||
return FormDataPlan(migratable=plan.live(), stuck=[hit for hit in plan.stuck if hit.bucket != "办结"])
|
||
|
||
|
||
def report_form_data(plan: FormDataPlan) -> None:
|
||
print(f"表单数据里选人那一格:可换算成账号的 {len(plan.migratable)} 处"
|
||
f"(在办/草稿 {len(plan.live())}、办结 {len(plan.done())}),换算不出 {len(plan.stuck)} 处")
|
||
for hit in plan.migratable[:15]:
|
||
print(f" [改] {hit.bucket} 「{hit.label}」 {hit.where}: {hit.old} -> {hit.account} ({hit.reason})")
|
||
if len(plan.migratable) > 15:
|
||
print(f" ...另有 {len(plan.migratable) - 15} 处")
|
||
for hit in plan.stuck[:15]:
|
||
print(f" [留] {hit.bucket} 「{hit.label}」 {hit.where}: {hit.old} —— {hit.reason}")
|
||
if len(plan.stuck) > 15:
|
||
print(f" ...另有 {len(plan.stuck) - 15} 处")
|
||
|
||
|
||
def report(result: Scan) -> None:
|
||
print(f"认不出人、且能认出是身份 DN 的引用:{result.total} 条"
|
||
f"(可换算 {len(result.migratable)},换算不出 {len(result.stuck)})")
|
||
for hit in result.migratable:
|
||
print(f" [改] {hit.where} 「{hit.row_label}」 {hit.old} -> {hit.account}"
|
||
f" ({hit.reason})")
|
||
for hit in result.stuck:
|
||
print(f" [留] {hit.where} 「{hit.row_label}」 {hit.old} —— {hit.reason}")
|
||
|
||
|
||
def main(argv: list[str]) -> int:
|
||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||
parser.add_argument("--apply", action="store_true", help="真的写库;不带就只体检")
|
||
parser.add_argument("--dry-run", action="store_true",
|
||
help="只体检。默认就是只体检,这个开关写出来图个心安")
|
||
parser.add_argument("--runtime", action="store_true",
|
||
help="连运行态与历史行一起看(待办 / 待阅 / 站内信 / 流转日志那些)")
|
||
parser.add_argument("--form-data", dest="form_data", action="store_true",
|
||
help="连单据数据里选人那一格一起看(applicant / handler 那些,含明细表)")
|
||
parser.add_argument("--all", action="store_true",
|
||
help="连办结归档的单据一起换算(只配 --form-data 时有意义,默认不动归档件)")
|
||
args = parser.parse_args(argv)
|
||
|
||
db = SessionLocal()
|
||
try:
|
||
if args.form_data:
|
||
plan = scan_form_data(db)
|
||
report_form_data(plan)
|
||
target = plan if args.all else _live_only(plan)
|
||
skipped = len(plan.migratable) - len(target.migratable)
|
||
if not args.all:
|
||
print(f"\n范围:只动在办与草稿({len(target.migratable)} 处)"
|
||
+ (f",办结那 {skipped} 处要另写 --all" if skipped else ""))
|
||
if args.apply and not args.dry_run and target.migratable:
|
||
print(f"已写库:换了 {apply_form_data(db, target)} 格")
|
||
after = _live_only(scan_form_data(db)) if not args.all else scan_form_data(db)
|
||
print(f"复查:还能换算的 {len(after.migratable)} 处"
|
||
+ ("(应当是 0)" if after.migratable else " ✅"))
|
||
if after.migratable:
|
||
report_form_data(after)
|
||
return 1
|
||
elif target.migratable:
|
||
print("(没写库。看清上面这份清单之后加 --apply 执行)")
|
||
return 0
|
||
if args.runtime:
|
||
plan = scan_runtime(db)
|
||
report_runtime(plan)
|
||
if args.apply and not args.dry_run and (plan.plan or plan.blob_plan):
|
||
print(f"\n已写库:改了 {apply_runtime(db, plan)} 行")
|
||
after = scan_runtime(db)
|
||
print(f"复查:还能换算的值 {after.values} 个"
|
||
+ ("(应当是 0)" if after.values else " ✅"))
|
||
if after.values:
|
||
report_runtime(after)
|
||
return 1
|
||
elif plan.plan:
|
||
print("\n(没写库。看清上面这份清单之后加 --apply 执行)")
|
||
return 0
|
||
result = scan(db)
|
||
report(result)
|
||
if not result.migratable:
|
||
print("\n可换算的身份 DN:0 条" + ("" if result.stuck else ";也没有换算不出的死引用"))
|
||
return 0
|
||
if args.apply and not args.dry_run:
|
||
changed = apply_fixes(db, result)
|
||
print(f"\n已写库:改了 {changed} 行配置")
|
||
after = scan(db)
|
||
print(f"复查:可换算 {len(after.migratable)} 条、换算不出 {len(after.stuck)} 条")
|
||
for hit in after.stuck:
|
||
print(f" [仍留] {hit.where} 「{hit.row_label}」 {hit.old} —— {hit.reason}")
|
||
else:
|
||
print("\n(没写库。看清上面这份清单之后加 --apply 执行)")
|
||
return 0
|
||
finally:
|
||
db.close()
|
||
|
||
|
||
if __name__ == "__main__":
|
||
raise SystemExit(main(sys.argv[1:]))
|