fourcal-pms/backend/app/service/org_sync.py

608 lines
25 KiB
Python
Raw Permalink 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.

"""把统一身份的组织与人同步进本地。
三条硬规则,跟 unisoa 一致:
1. **只认主键,不认名字**。组织靠 ``hub_org_id``、人靠 ``hub_user_id`` 对上号;账号名
和姓名都会在 Hub 侧改,靠名字对号迟早对到别人身上。
2. **本地账号永远不动**。``source=local`` 的账号(含内置超管)同步不碰,避免夜间同步
把管理员改没。
3. **Hub 侧消失的一律停用而不是删除**。审批记录、项目创建人要一直指得到人,物理删除
会让历史数据失去解释。
"""
from __future__ import annotations
import json
from dataclasses import dataclass, field
from datetime import datetime
from typing import Any
from sqlalchemy import select
from sqlalchemy.orm import Session
from ..config import settings
from ..models import Account, AccountIdentity, AccountSource, HubSyncRun, OrgUnit, Status
from . import hub_api
@dataclass
class SyncStats:
org_total: int = 0
# "必须退回全量"的信号走这个独立字段,不混进 errors:errors 会被拼进
# hub_sync_run.error 直接显示到界面上,内部前缀漏出去很难看也很难懂。
escalate: str = ""
org_created: int = 0
org_updated: int = 0
org_disabled: int = 0
account_total: int = 0
account_created: int = 0
account_updated: int = 0
account_disabled: int = 0
skipped_local: int = 0
steps: list[dict[str, Any]] = field(default_factory=list)
errors: list[str] = field(default_factory=list)
def step(self, name: str, **detail: Any) -> None:
self.steps.append({"name": name, "at": datetime.now().isoformat(timespec="seconds"), **detail})
def sync_all(db: Session, *, trigger: str = "manual") -> HubSyncRun:
"""跑一次完整同步,结果写 ``hub_sync_run``。"""
run = HubSyncRun(trigger=trigger, status="running", started_at=datetime.now())
db.add(run)
db.flush()
stats = SyncStats()
cursor = 0
try:
directory = hub_api.fetch_directory()
organizations = directory["organizations"]
users = directory["users"]
stats.step("fetch", organizations=len(organizations), users=len(users),
totalUsers=directory["total_users"])
org_map = _sync_units(db, organizations, stats)
stats.step("units", created=stats.org_created, updated=stats.org_updated)
_sync_people(db, users, org_map, stats)
stats.step("people", created=stats.account_created, updated=stats.account_updated)
if settings.hub.missing_org_action == "disable":
_disable_missing_units(db, organizations, stats)
if settings.hub.missing_account_action == "disable":
_disable_missing_accounts(db, users, stats)
_refresh_paths(db)
# 文档 §6.3:全量落地后记一次游标边界,之后的增量从这里接着走。
# 这一步失败不影响全量结果本身,单独记一笔,别把整次同步判成失败。
cursor = _cursor_boundary(stats)
status = "partial" if stats.errors else "success"
except hub_api.HubError as exc:
stats.errors.append(str(exc))
status = "failed"
run.status = status
run.finished_at = datetime.now()
run.org_total, run.org_created, run.org_updated, run.org_disabled = (
stats.org_total, stats.org_created, stats.org_updated, stats.org_disabled)
run.account_total, run.account_created, run.account_updated, run.account_disabled = (
stats.account_total, stats.account_created, stats.account_updated, stats.account_disabled)
run.skipped_local = stats.skipped_local
run.cursor_after = cursor
run.steps_json = json.dumps(stats.steps, ensure_ascii=False)
run.error = ";".join(stats.errors)
db.flush()
return run
def _cursor_boundary(stats: SyncStats) -> int:
"""拉一次增量只为拿 newest_seq,作为下一次增量的起点。"""
try:
return int(hub_api.fetch_changes(0, limit=1)["newest_seq"])
except hub_api.HubError as exc:
stats.errors.append(f"全量已落地但没拿到游标边界,下次仍会走全量:{exc}")
return 0
def local_cursor(db: Session) -> int:
"""本地已同步到的目录游标。没有增量批次就返回 0(表示只能走全量)。"""
return int(
db.execute(
select(HubSyncRun.cursor_after)
.where(HubSyncRun.status.in_(("success", "partial")),
HubSyncRun.cursor_after > 0)
.order_by(HubSyncRun.id.desc())
.limit(1)
).scalars().first()
or 0
)
def sync_changes(db: Session, *, trigger: str = "scheduled", max_batches: int = 20) -> HubSyncRun:
"""按游标拉一次增量并幂等应用,结果写 ``hub_sync_run``。
游标只在"整批都成功"之后才推进:文档要求同一批循环拉到 ``has_more=false`` 才允许提交,
中途失败必须从老游标重来,否则会永久漏掉中间那些事件。
两种情况直接升级成全量重跑,不硬扛:
* ``since`` 落到 ``oldest_seq`` 之前 —— 中间流水已被裁剪,增量补不回来;
* 收到"只带 id 和 status / parent_id"的组织事件 —— 文档 §6.4 明说这类 payload 不带
``path``、组织停用也不会给子孙逐个发事件,禁止靠它推导父子关系。硬套批量同步函数
会因为 payload 里没有 ``name`` 而把好好的部门名刷成"组织 12"。
"""
cursor = local_cursor(db)
run = HubSyncRun(trigger=trigger, status="running", started_at=datetime.now())
db.add(run)
db.flush()
stats = SyncStats()
stats.step("cursor", since=cursor)
escalate_reason = ""
if cursor <= 0:
escalate_reason = "本地还没有游标(从未成功同步过),只能走全量"
else:
since = cursor
batches = 0
batches_ok = 0
applied = 0
try:
while batches < max_batches:
batches += 1
batch = hub_api.fetch_changes(since)
batches_ok += 1
if batch["behind"]:
escalate_reason = (
f"本地游标 {since} 已落后于 Hub 侧最早流水 {batch['oldest_seq']},"
"中间事件被裁剪,退回全量重建"
)
break
org_structure_changed = False
for change in batch["changes"]:
if _apply_change(db, change, stats=stats) == "escalate":
break # 单条错误只记账,不中断整批;升级信号由 stats 里的标记带出去
applied += 1
if str(change.get("entity") or "").lower() == "organization":
org_structure_changed = True
if org_structure_changed:
# path / level 是按 parent_id 全量重算的,一批一次就够,别一条一算。
_refresh_paths(db)
org_structure_changed = False
since = batch["cursor"]
stats.step("batch", seq=since, changes=len(batch["changes"]),
hasMore=batch["has_more"])
if outcome_stopped(stats) or not batch["has_more"]:
break
except hub_api.HubError as exc:
stats.errors.append(str(exc))
if not escalate_reason and stats.escalate:
escalate_reason = stats.escalate
if escalate_reason:
stats.step("escalate", reason=escalate_reason)
run.status = "skipped"
run.error = escalate_reason
run.cursor_after = 0
run.finished_at = datetime.now()
run.steps_json = json.dumps(stats.steps, ensure_ascii=False)
db.flush()
full = sync_all(db, trigger=f"{trigger}+full")
# 升级前后的过程记录要接在一起,才能在"同步历史"里看清是先退回再全量的。
# 这里不能直接 json.loads(run.steps_json):列默认值是 Python 侧给的,
# 一个刚 new 出来还没 flush 的 HubSyncRun 上它就是 None,直接抛 TypeError。
full.steps_json = json.dumps(_steps_of(run) + _steps_of(full), ensure_ascii=False)
db.flush()
return full
# 一批都没拉成功 = 这次同步压根没发生,报 partial 会把"对端挂了"粉饰成"同步好了大部分"。
# 只有先落了几批、后面才断的,才算 partial。
if batches_ok == 0:
run.status = "failed"
else:
run.status = "partial" if stats.errors else "success"
run.finished_at = datetime.now()
run.cursor_after = since
run.account_total = applied
run.account_updated = stats.account_updated
run.account_created = stats.account_created
run.account_disabled = stats.account_disabled
run.org_updated = stats.org_updated
run.org_created = stats.org_created
run.org_disabled = stats.org_disabled
run.steps_json = json.dumps(stats.steps, ensure_ascii=False)
run.error = ";".join(stats.errors)
db.flush()
return run
def outcome_stopped(stats: SyncStats) -> bool:
"""批内出现"必须退回全量"的信号时,停止继续消费增量。"""
return bool(stats.escalate)
def _apply_change(db: Session, change: dict[str, Any], *, stats: SyncStats) -> str:
"""应用一条目录变更。返回 ``ok`` / ``escalate``。
``data`` 的键名随来源变化(``source=hub`` 用 ``id``,``source=wecom`` 用
``organization_id`` / ``user_id``),先按 entity 分支再取值。
"""
entity = str(change.get("entity") or "").strip().lower()
op = str(change.get("op") or "").strip().lower()
payload = change.get("data") if isinstance(change.get("data"), dict) else {}
seq = change.get("seq")
if entity == "organization":
hub_id = _node_id(payload) or (int(change["entity_id"])
if str(change.get("entity_id") or "").isdigit() else None)
if hub_id is None:
stats.errors.append(f"变更 seq={seq} 是组织但取不到主键,忽略")
return "ok"
if op == "delete":
unit = _hub_unit(db, hub_id)
if unit is not None:
unit.is_deleted = True
unit.status = Status.DISABLED
stats.org_disabled += 1
return "ok"
if not str(payload.get("name") or "").strip():
# 只带 id + status / parent_id 的部分 payload:按文档必须重拉全量。
stats.escalate = (f"seq={seq} 的组织事件只给了 id 与状态,按契约不能靠它推导层级")
return "escalate"
_sync_units(db, [payload], stats)
_refresh_paths(db)
return "ok"
if entity == "user":
hub_id = _person_id(payload) or (int(change["entity_id"])
if str(change.get("entity_id") or "").isdigit() else None)
if hub_id is None:
stats.errors.append(f"变更 seq={seq} 是人员但取不到主键,忽略")
return "ok"
account = _hub_account(db, hub_id)
if op == "delete":
if account is not None:
# 软删除:审批记录和项目创建人要一直指得到人。
account.status = Status.DISABLED
account.is_deleted = True
stats.account_disabled += 1
return "ok"
has_identity = str(payload.get("account") or "").strip() and \
str(payload.get("display_name") or "").strip()
if account is None and not has_identity:
stats.escalate = (f"seq={seq} 的新人员事件字段不全,本地没有对应账号,需全量补建")
return "escalate"
if account is None:
_sync_people(db, [payload], _hub_org_map(db), stats)
return "ok"
# 已有账号:payload 里给了什么就更新什么,没给的一律不动。
if "organization_id" in payload or "org_id" in payload:
unit = _hub_org_map(db).get(_person_org_id(payload) or -1)
if unit is not None and account.org_unit_id != unit.id:
account.org_unit_id = unit.id
stats.account_updated += 1
if "status" in payload:
status = Status.normalize(payload.get("status", 1))
if account.status != status:
account.status = status
stats.account_updated += 1
if str(payload.get("display_name") or "").strip():
display = str(payload["display_name"]).strip()
if account.display_name != display:
account.display_name = display
stats.account_updated += 1
if str(payload.get("email") or "").strip():
account.email = str(payload["email"]).strip()
account.hub_synced_at = datetime.now()
return "ok"
stats.errors.append(f"变更 seq={seq} 的 entity={entity!r} 不认识,忽略")
return "ok"
def _hub_unit(db: Session, hub_org_id: int) -> OrgUnit | None:
return db.execute(select(OrgUnit).where(OrgUnit.hub_org_id == hub_org_id)).scalars().first()
def _hub_account(db: Session, hub_user_id: int) -> Account | None:
return db.execute(
select(Account).where(Account.hub_user_id == hub_user_id)
).scalars().first()
def _hub_org_map(db: Session) -> dict[int, OrgUnit]:
return {
unit.hub_org_id: unit
for unit in db.execute(select(OrgUnit).where(OrgUnit.hub_org_id.isnot(None))).scalars().all()
}
def _node_id(node: dict[str, Any]) -> int | None:
for key in ("organization_id", "org_id", "id", "deptId", "dept_id"):
value = node.get(key)
if value is not None and str(value).strip().isdigit():
return int(value)
return None
def _node_parent_id(node: dict[str, Any]) -> int | None:
for key in ("parent_id", "parentId", "parent"):
value = node.get(key)
if value is not None and str(value).strip().isdigit() and int(value) > 0:
return int(value)
return None
def _tree_nodes(organizations: list[dict[str, Any]], stats: SyncStats) -> list[dict[str, Any]]:
"""把 Hub 返回的组织摊平成"父先子后"的有序列表。
Hub 可能返回一棵嵌套树,也可能是扁平数组,两种都要能吃;同时挡一下环形父子,
否则后面的 path 计算会无限递归。
"""
flat: list[dict[str, Any]] = []
def walk(node: Any) -> None:
if not isinstance(node, dict):
return
children = node.get("children") or node.get("child") or []
shallow = {key: value for key, value in node.items() if key not in ("children", "child")}
flat.append(shallow)
if isinstance(children, list):
for child in children:
walk(child)
for item in organizations or []:
walk(item)
stats.org_total = len(flat)
ordered: list[dict[str, Any]] = []
placed: set[int] = set()
pending = list(flat)
guard = 0
while pending and guard < 50:
guard += 1
remaining: list[dict[str, Any]] = []
for node in pending:
key = _node_id(node)
parent = _node_parent_id(node)
if key is None:
continue
if parent is None or parent in placed:
ordered.append(node)
placed.add(key)
else:
remaining.append(node)
if len(remaining) == len(pending): # 环形或父缺失,剩下的直接按原序补上
ordered.extend(remaining)
break
pending = remaining
return ordered
def _sync_units(db: Session, organizations: list[dict[str, Any]], stats: SyncStats) -> dict[int, OrgUnit]:
existing = {
unit.hub_org_id: unit
for unit in db.execute(select(OrgUnit).where(OrgUnit.hub_org_id.isnot(None))).scalars().all()
}
mapping: dict[int, OrgUnit] = {}
for node in _tree_nodes(organizations, stats):
hub_id = _node_id(node)
if hub_id is None:
continue
name = str(node.get("name") or node.get("departName") or "").strip() or f"组织 {hub_id}"
code = str(node.get("code") or node.get("orgCode") or "").strip()
status = Status.normalize(node.get("status", 1))
parent_unit = mapping.get(_node_parent_id(node) or -1)
unit = existing.get(hub_id)
if unit is None:
unit = OrgUnit(name=name, code=code, hub_org_id=hub_id, status=status,
parent_id=parent_unit.id if parent_unit else None)
db.add(unit)
db.flush()
stats.org_created += 1
else:
if unit.name != name:
unit.name = name
if code and unit.code != code:
unit.code = code
unit.status = status
parent_id = parent_unit.id if parent_unit else None
if unit.parent_id != parent_id:
unit.parent_id = parent_id
stats.org_updated += 1
unit.short_name = str(node.get("short_name") or node.get("shortName") or unit.short_name or "")
unit.order_number = int(node.get("order_number") or node.get("sort") or unit.order_number or 0)
unit.hub_synced_at = datetime.now()
unit.is_deleted = False
mapping[hub_id] = unit
db.flush()
return mapping
def _person_id(node: dict[str, Any]) -> int | None:
for key in ("user_id", "userId", "id", "personId"):
value = node.get(key)
if value is not None and str(value).strip().isdigit():
return int(value)
return None
def _person_org_id(node: dict[str, Any]) -> int | None:
for key in ("organization_id", "org_id", "organizationId", "deptId", "dept_id"):
value = node.get(key)
if value is not None and str(value).strip().isdigit():
return int(value)
return None
def _sync_people(db: Session, users: list[dict[str, Any]], org_map: dict[int, OrgUnit],
stats: SyncStats) -> None:
existing = {
account.hub_user_id: account
for account in db.execute(
select(Account).where(Account.hub_user_id.isnot(None))
).scalars().all()
}
stats.account_total = len(users or [])
for node in users or []:
hub_id = _person_id(node)
if hub_id is None:
continue
account_name = str(node.get("account") or node.get("username") or node.get("userName") or "").strip()
display = str(node.get("display_name") or node.get("name") or node.get("realName") or "").strip()
unit = org_map.get(_person_org_id(node) or -1)
status = Status.normalize(node.get("status", 1))
account = existing.get(hub_id)
created = False
if account is None:
if not account_name:
stats.errors.append(f"Hub 用户 {hub_id} 没有账号名,已跳过")
continue
taken = db.execute(select(Account).where(Account.account == account_name)).scalars().first()
if taken is not None and taken.source != AccountSource.HUB:
# 本地已经有人用了这个账号名:不抢,改名后新建,避免把本地人的号夺走
account_name = f"{account_name}_hub{hub_id}"
stats.skipped_local += 1
if taken is not None and taken.source == AccountSource.HUB:
account = taken # 之前建的 hub 账号还没回填 hub_user_id,认领它而不是再建一个
else:
account = Account(account=account_name, password_hash="",
source=AccountSource.HUB, hub_user_id=hub_id)
created = True
stats.account_created += 1
db.add(account)
db.flush()
else:
if account.display_name != display and display:
account.display_name = display
if unit is not None and account.org_unit_id != unit.id:
account.org_unit_id = unit.id
account.status = status
stats.account_updated += 1
account.hub_user_id = hub_id
account.source = AccountSource.HUB
account.hub_synced_at = datetime.now()
account.display_name = display or account.display_name
account.emp_code = str(node.get("emp_code") or node.get("empCode") or account.emp_code or "")
account.telephone = str(node.get("telephone") or node.get("mobile") or account.telephone or "")
account.email = str(node.get("email") or node.get("company_email") or account.email or "")
if unit is not None:
account.org_unit_id = unit.id
account.is_deleted = False
db.flush()
_ensure_identity(db, account, unit, stats)
db.flush()
def _ensure_identity(db: Session, account: Account, unit: OrgUnit | None, stats: SyncStats) -> None:
if unit is None:
return
existing = db.execute(
select(AccountIdentity).where(
AccountIdentity.account_id == account.id, AccountIdentity.org_unit_id == unit.id
)
).scalars().first()
if existing is None:
others = db.execute(
select(AccountIdentity.id).where(AccountIdentity.account_id == account.id)
).scalars().all()
db.add(AccountIdentity(account_id=account.id, org_unit_id=unit.id, is_default=not list(others)))
db.flush()
def _disable_missing_units(db: Session, organizations: list[dict[str, Any]], stats: SyncStats) -> None:
seen = {_node_id(node) for node in _tree_nodes(organizations, SyncStats())}
seen.discard(None)
rows = db.execute(select(OrgUnit).where(OrgUnit.hub_org_id.isnot(None),
OrgUnit.is_deleted.is_(False))).scalars().all()
for unit in rows:
if unit.hub_org_id not in seen and unit.is_active:
unit.status = Status.DISABLED
stats.org_disabled += 1
def _disable_missing_accounts(db: Session, users: list[dict[str, Any]], stats: SyncStats) -> None:
seen = {_person_id(node) for node in (users or [])}
seen.discard(None)
rows = db.execute(
select(Account).where(Account.source == AccountSource.HUB, Account.is_deleted.is_(False))
).scalars().all()
for account in rows:
if account.hub_user_id not in seen and account.status == Status.ACTIVE:
account.status = Status.DISABLED
stats.account_disabled += 1
def _refresh_paths(db: Session) -> None:
"""重算 ``org_unit.path`` 与层级。同步改过 parent_id 之后必须跑一次。"""
units = {unit.id: unit for unit in db.execute(select(OrgUnit)).scalars().all()}
for unit in units.values():
chain: list[int] = []
cursor: OrgUnit | None = unit
guard = 0
while cursor is not None and guard < 32:
if cursor.id in chain: # 环形父子,截断
break
chain.append(cursor.id)
cursor = units.get(cursor.parent_id) if cursor.parent_id else None
guard += 1
unit.path = "/" + "/".join(str(item) for item in reversed(chain)) + "/"
unit.level = len(chain)
parent = units.get(unit.parent_id) if unit.parent_id else None
if parent and parent.path:
unit.path = parent.path + f"{unit.id}/"
unit.level = parent.level + 1
db.flush()
def _steps_of(run: HubSyncRun) -> list[Any]:
"""读 run.steps_json,容忍 None 与脏数据。"""
raw = getattr(run, "steps_json", None)
if not raw:
return []
try:
loaded = json.loads(raw)
except (json.JSONDecodeError, TypeError):
return []
return loaded if isinstance(loaded, list) else []
def serialize(run: HubSyncRun) -> dict[str, Any]:
data = {
"id": run.id,
"trigger": run.trigger,
"status": run.status,
"startedAt": run.started_at.isoformat(sep=" ", timespec="seconds") if run.started_at else "",
"finishedAt": run.finished_at.isoformat(sep=" ", timespec="seconds") if run.finished_at else "",
"orgTotal": run.org_total, "orgCreated": run.org_created,
"orgUpdated": run.org_updated, "orgDisabled": run.org_disabled,
"accountTotal": run.account_total, "accountCreated": run.account_created,
"accountUpdated": run.account_updated, "accountDisabled": run.account_disabled,
"skippedLocal": run.skipped_local,
"cursorAfter": run.cursor_after,
"error": run.error,
}
data["steps"] = _steps_of(run)
return data
def status_payload(db: Session) -> dict[str, Any]:
latest = db.execute(select(HubSyncRun).order_by(HubSyncRun.id.desc()).limit(1)).scalars().first()
return {
"enabled": settings.hub.enabled,
"configured": settings.hub.configured,
"ssoConfigured": settings.hub.sso_configured,
"baseUrl": settings.hub.base_url,
"syncIntervalMinutes": settings.hub.sync_interval_minutes,
"changesIntervalSeconds": settings.hub.changes_interval_seconds,
# 本地游标。0 表示"从没成功全量过",下一次定时任务会先补全量而不是空跑增量。
"cursor": local_cursor(db),
"autoSyncActive": bool(settings.hub.configured
and (settings.hub.changes_interval_seconds > 0
or settings.hub.sync_interval_minutes > 0)),
"latest": serialize(latest) if latest else None,
}