2168 lines
100 KiB
Python
2168 lines
100 KiB
Python
"""Organization helpers: people, units, groups, roles, agents.
|
||
|
||
组织模型原本照 O2OA 那套,一个人可以挂多个 *身份*(``部门\姓名\身份名``)。**这一层
|
||
不再认那套口径**:库里存"是谁"的字符串是登录账号,DN 由部门路径与姓名拼出来,
|
||
部门改名、挪层级、调岗都会让它漂,而它被当外键铺在了运行态数据上。账号是本部署对外
|
||
认人的业务键,唯一且不改。``oa_identity`` 那张"一人多身份"的档案副本表已经整张下线
|
||
(2026-10):它只在展示路径上被读,认人、算部门、派待办一处都不看它,却要在同步、
|
||
建号、改部门、删人时处处维护,还要在每个"问这批人是谁"的批量查询里多排一次队。
|
||
DN 这个字符串留着,只作展示与打印,改由 ``users`` + ``oa_unit`` 现算。
|
||
统一口径见 :mod:`app.service.personref`:**只认登录账号,也只存登录账号**。
|
||
|
||
这一层里凡是"算出一串人"的出口(:func:`resolve_identity_names`、:func:`expand_as`、
|
||
:func:`identities_for_unit`、:func:`leader_chain`、:func:`unit_manager_identity`……)
|
||
交出来的都是账号,**认不出的值不当成一个人**:由调用方按 unknown 报出去(设计器报红、
|
||
环节走配好的空审批人兜底),绝不派一份对不上人的待办。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import logging
|
||
import os
|
||
from dataclasses import dataclass
|
||
from datetime import datetime
|
||
from typing import Any, Callable, Iterable
|
||
|
||
from sqlalchemy import ColumnElement, and_, func, or_, select
|
||
from sqlalchemy.orm import Session
|
||
|
||
from .. import models, parallel, presence, readcache
|
||
from ..config import settings
|
||
from . import personref
|
||
|
||
logger = logging.getLogger("unisoa.org")
|
||
|
||
|
||
def system_account_names() -> tuple[str, ...]:
|
||
"""系统账号(内置管理员)的登录账号。
|
||
|
||
它是登录用的系统账号,不是公司里的一个员工:既不该在组织架构里占一个节点,
|
||
也不该为它补出一个部门。账号名以**数据库里的记录**为准(``config.admin_account_name``
|
||
读 ``system.admin_account``),配置文件与环境变量只在显式点名时负责给它改名;
|
||
被授予管理员角色的真人不在这里,他们照常出现在组织里。
|
||
"""
|
||
account = str(getattr(settings, "admin_account", "") or "").strip()
|
||
return (account,) if account else ()
|
||
|
||
|
||
def is_system_account(person: models.User | None) -> bool:
|
||
return person is not None and str(person.account or "").strip() in system_account_names()
|
||
|
||
|
||
def person_lock_reason(person: models.User | None) -> str:
|
||
"""这个账号在 OA 里不许编辑/停用时给出原因,允许改动就回空串。
|
||
|
||
两类账号只读,理由各不相同:
|
||
|
||
* **内置超管**(``[seed] admin_account``,本部署叫 ``localadmin``):它是应急入口,
|
||
也是按账号名认的系统账号。界面上改掉账号名就再没人能进应急通道,改状态或删掉
|
||
等于把自己锁在系统外 —— 账号名要改请改引导配置后重启,启动时会对齐。
|
||
* **统一身份平台自己的管理员**(``hub_sync_locked_accounts``,默认 ``admin``):
|
||
名称/部门/启停本来就归 Hub,改不动;这里再锁掉角色、密码与删除,免得有人把
|
||
管理员身份挪到别人身上,或者把 Hub 的账号名改成和 Hub 对不上的值。
|
||
|
||
只管界面上的改动:夜间同步照旧按 Hub 的话改这些人的资料(那是数据主人的权利),
|
||
Hub 判定停用也会跟着停用,这里不拦。
|
||
"""
|
||
if person is None:
|
||
return ""
|
||
return account_lock_reason(
|
||
str(person.account or ""), str(person.source or models.AccountSource.LOCAL), person
|
||
)
|
||
|
||
|
||
def account_lock_reason(account: str, source: str = models.AccountSource.LOCAL,
|
||
person: models.User | None = None) -> str:
|
||
"""按 账号名 + 归属 判断能不能在 OA 里改动,判据与 :func:`person_lock_reason` 同源。
|
||
|
||
建号时也要问一遍:只读名单上的名字要是先被本地占掉,等 Hub 把真人下发下来就认领不上
|
||
(本地这个号没有 ``hub_user_id``,同步又不许抢别人的账号名),最后剩下的就是一个
|
||
谁也对不上的假管理员。
|
||
"""
|
||
from .. import hubconfig
|
||
|
||
account = str(account or "").strip()
|
||
if not account:
|
||
return ""
|
||
if person is not None and is_system_account(person):
|
||
return _system_account_hint(account)
|
||
if person is None and account in system_account_names():
|
||
return _system_account_hint(account)
|
||
if (
|
||
str(source or models.AccountSource.LOCAL) == models.AccountSource.HUB
|
||
and account.lower() in hubconfig.get().locked_hub_accounts
|
||
):
|
||
return (
|
||
f"{account} 是统一身份平台自己的管理员:名称、部门、启停都跟着 Hub,"
|
||
"OA 里也不许改角色、重置密码或删除。要调整请在 Hub 侧改,"
|
||
"或到系统设置「组织人员同步 - 统一身份的管理员账号」里把它移出只读名单"
|
||
)
|
||
return ""
|
||
|
||
|
||
def account_reserved_reason(account: str) -> str:
|
||
"""这个账号名是不是被留给了只读账号,本地不该先建一个同名的。
|
||
|
||
与 :func:`account_lock_reason` 问的不是同一件事:那边问"这个人已有的账号能不能改"
|
||
(本地人碰巧叫 admin 不该被牵连),这里问"这个名字还能不能用"。名字先被本地占掉,
|
||
Hub 把真人下发下来时认领不上(本地这个号没有 ``hub_user_id``,同步又不许抢别人的
|
||
账号名),最后留下一个谁也对不上的假管理员。
|
||
"""
|
||
account = str(account or "").strip()
|
||
if not account:
|
||
return ""
|
||
if account in system_account_names():
|
||
return (
|
||
f"{account} 是内置超管(应急账号)占用的账号名:由 [seed] admin_account 决定,"
|
||
"不能在人员页另建同名的号"
|
||
)
|
||
from .. import hubconfig
|
||
|
||
if account.lower() in hubconfig.get().locked_hub_accounts:
|
||
return (
|
||
f"{account} 这个账号名留给了统一身份的管理员账号,等 Hub 下发这个人时会自动建号;"
|
||
"这里不能先占坑,否则真人下来就认领不上"
|
||
)
|
||
return ""
|
||
|
||
|
||
def _system_account_hint(account: str) -> str:
|
||
return (
|
||
f"{account} 是 UnisOA 内置超管(应急账号):不走统一身份,本地口令是唯一入口。"
|
||
"这里不许改名、改角色、停用或删除;要换账号名请改 [seed] admin_account 后重启,"
|
||
"启动时会自动对齐;要轮换应急口令请用本人「修改密码」"
|
||
)
|
||
|
||
|
||
def unit_path(unit: models.Unit | None) -> str:
|
||
if unit is None:
|
||
return ""
|
||
return unit.path or unit.name
|
||
|
||
|
||
def unit_order_by() -> list[ColumnElement]:
|
||
"""组织架构的统一排序口径:本地排序号 -> 统一身份的组织 id -> 名称。
|
||
|
||
只按 ``(order_number, name)`` 排是不可用的:``order_number`` 是本地字段,同步从不写、
|
||
界面上也没人填,于是整库清一色是 0,真正决定顺序的落到了 ``name`` 上 —— MySQL 按 utf8mb4
|
||
权重排中文,「总经理」会插进「交付运维科」和「协同营销事业部」中间,和统一身份那棵树
|
||
的读法完全对不上。
|
||
|
||
``hub_org_id`` 就是统一身份的 ``organization_id``:对方按建档先后发号,天然等于组织
|
||
架构的自然顺序(先董事长、总经理,再各事业部,再事业部下面的科),而且是唯一索引列,
|
||
顺序稳定、不随部门改名漂。
|
||
|
||
``order_number`` 留在最前:它是界面上唯一给管理员留的手工排序入口,非 0 就是明确
|
||
表达过的意图,不该被这次改动变成摆设。
|
||
|
||
``hub_org_id IS NULL`` 单独占一档,是为了把本地自建部门整体排在同步部门之后 ——
|
||
MySQL 的 ``ASC`` 把 NULL 排最前,直接 ``ORDER BY hub_org_id`` 会让没绑统一身份的部门
|
||
抢到整棵树顶上。这个写法在 MySQL 与 SQLite 上都成立;SQLAlchemy 的 ``nulls_last()``
|
||
会原样吐出 MySQL 不认的 ``NULLS LAST``,这里用不了。
|
||
"""
|
||
return [
|
||
models.Unit.order_number.asc(),
|
||
models.Unit.hub_org_id.is_(None).asc(),
|
||
models.Unit.hub_org_id.asc(),
|
||
models.Unit.name.asc(),
|
||
]
|
||
|
||
|
||
def dn_for(unit_path_: str, person_name: str, tail: str) -> str:
|
||
"""Compose an O2OA style distinguished name(``部门\姓名\尾巴``).
|
||
|
||
只剩展示用:组织树里选中一个人时下面那一行、以及历史报文里的 ``distinguished_name``。
|
||
尾巴一律给登录账号——它不再是 ``varchar(512)`` 列里的键,但下游仍按那个宽度处理,
|
||
所以这里照旧裁一次,别让一个超长部门路径把报文撑肥。
|
||
"""
|
||
parts = [part for part in [unit_path_, person_name, tail] if part]
|
||
return "\\".join(parts)[:512]
|
||
|
||
|
||
def identity_display_name(distinguished_name: str) -> str:
|
||
"""``a\\b\\person\\identity`` -> ``person`` (falling back to the tail)."""
|
||
if not distinguished_name:
|
||
return ""
|
||
parts = [p for p in distinguished_name.split("\\") if p]
|
||
if len(parts) >= 2:
|
||
return parts[-2]
|
||
return parts[-1] if parts else ""
|
||
|
||
|
||
def identity_unit(distinguished_name: str) -> str:
|
||
parts = [p for p in distinguished_name.split("\\") if p]
|
||
if len(parts) >= 3:
|
||
return "\\".join(parts[:-2])
|
||
return ""
|
||
|
||
|
||
# ``taskValues`` 里可选的审批人来源:静态的查组织,动态的等运行时才知道。
|
||
SELECTOR_KINDS = frozenset({"identity", "person", "role", "group", "unit", "post"})
|
||
#: 选择器来源类型的中文名,预览提示里要说清楚这一行按哪种口径解析。
|
||
SELECTOR_KIND_LABELS = {
|
||
"identity": "身份",
|
||
"person": "人员",
|
||
"role": "岗位角色",
|
||
"post": "岗位角色",
|
||
"group": "分组",
|
||
"unit": "部门",
|
||
}
|
||
#: 走组织层级的动态来源:发起人/上环节处理人的上级链与各级负责人。
|
||
#: 它们也要等运行时才定得下来,但设计器可以拿一个样例身份先试算一遍。
|
||
RELATION_KINDS = frozenset(
|
||
{
|
||
"creatorLeader",
|
||
"creatorLeaderChain",
|
||
"creatorUnitManager",
|
||
"creatorParentUnitManager",
|
||
"creatorTeamLeader",
|
||
"prevLeader",
|
||
"prevUnitManager",
|
||
"unitManager",
|
||
}
|
||
)
|
||
DYNAMIC_KINDS = frozenset({"creator", "prev", "prevunit", "form"}) | RELATION_KINDS
|
||
#: 老配置里的 ``type`` 全小写,新 kinds 用驼峰;读进来先归一,省得两处写法各写一半。
|
||
_KIND_LOOKUP = {kind.lower(): kind for kind in SELECTOR_KINDS | DYNAMIC_KINDS}
|
||
|
||
|
||
def normalize_kind(raw: object) -> str:
|
||
"""把配置里的 ``type`` 归一成模型里的写法(``unitmanager`` -> ``unitManager``)。"""
|
||
value = str(raw or "").strip()
|
||
return _KIND_LOOKUP.get(value.lower(), value)
|
||
|
||
|
||
#: 连续多级上级的层数上限,防呆:配成 999 会把整棵组织树的人拉进同一个环节。
|
||
MAX_LEADER_CHAIN = 10
|
||
|
||
|
||
@dataclass
|
||
class IdentityRef:
|
||
""""这串人员引用是谁"。
|
||
|
||
认人只认 ``account``(口径见 :mod:`app.service.personref`)。``distinguished_name``
|
||
是这个人当前档案上的那份身份 DN,只给展示与打印用,**不当键、也不写回库**;
|
||
多身份下线之后它会跟着走。
|
||
"""
|
||
|
||
distinguished_name: str
|
||
person: str
|
||
person_name: str
|
||
unit: str
|
||
unit_name: str
|
||
#: 登录账号:现在唯一可靠的认人依据。解析不到人时是空串。
|
||
account: str = ""
|
||
|
||
@property
|
||
def name(self) -> str:
|
||
"""给人看的姓名:能对人就用档案里的姓名,对不上才退回 DN 字面。"""
|
||
return self.person_name or identity_display_name(self.distinguished_name)
|
||
|
||
@property
|
||
def ref(self) -> str:
|
||
"""该往库里写回去的那个值:只有账号;对不上人就是空串(调用方自己决定怎么报错)。"""
|
||
return self.account
|
||
|
||
|
||
def path_prefix_pattern(path: str) -> str:
|
||
"""LIKE pattern matching ``path`` and everything below it.
|
||
|
||
Unit paths contain backslashes, and MySQL uses backslash as the default
|
||
LIKE escape character, so ``...\研发中心\%`` would match a literal percent
|
||
sign instead of a subtree. Doubling them makes the wildcards real again.
|
||
"""
|
||
separator = chr(92) # 单位路径的分隔符是反斜杠
|
||
return f"{path.replace(separator, separator * 2)}%"
|
||
|
||
|
||
def descendant_unit_ids(db: Session, unit_id: int | str) -> list[int]:
|
||
"""``unit_id`` plus every unit below it (uses the materialised path)."""
|
||
key = models.as_id(unit_id)
|
||
unit = db.get(models.Unit, key)
|
||
if unit is None:
|
||
return [key] if key is not None else []
|
||
prefix = unit.path or unit.name
|
||
rows = db.execute(
|
||
select(models.Unit).where(
|
||
or_(models.Unit.id == key, models.Unit.path.like(path_prefix_pattern(prefix)))
|
||
)
|
||
).scalars().all()
|
||
return [r.id for r in rows]
|
||
|
||
|
||
def resolve_identity_names(db: Session, selectors: list[str]) -> list[str]:
|
||
"""把一批混合选择器(账号 / 姓名 / 部门路径 / 岗位角色名 / 分组名)摊成**登录账号**清单。
|
||
|
||
认不出的那一条直接丢掉——它不是一个人。要把"认不出"这件事报出去请用
|
||
:func:`split_selectors`,它把 unknown 单独交回来。
|
||
|
||
Supported selector shapes (mirrors the O2OA ``values`` payload)::
|
||
|
||
{"type": "identity", "data": ["<account>", ...]}
|
||
{"type": "person", "data": ["<account|name>", ...]}
|
||
{"type": "unit", "data": ["<unit path>", ...], "containsSub": true}
|
||
{"type": "role", "data": ["<role name>", ...]}
|
||
{"type": "group", "data": ["<group name>", ...]}
|
||
"""
|
||
# 一串成员一次探完:五档全不命中的那几条,从每个值白问五趟变成合起来问一趟
|
||
probe_selectors(db, [str(raw).strip() for raw in selectors if isinstance(raw, str) and raw.strip()])
|
||
result: list[str] = []
|
||
for raw in selectors:
|
||
if not raw:
|
||
continue
|
||
value = str(raw).strip()
|
||
if not value:
|
||
continue
|
||
for dn in _expand(db, value):
|
||
if dn and dn not in result:
|
||
result.append(dn)
|
||
return result
|
||
|
||
|
||
def _find_units(db: Session, value: str) -> list[models.Unit]:
|
||
"""Match units by name or path; the stored path keeps a trailing separator.
|
||
|
||
除了本地的名称与 O2OA 路径,也认统一身份那边按 organization_id 拼的 id 路径
|
||
(``/1/8/10/``、``1/8/10``):那是 Hub 控制台上唯一能直接抄过来的部门标识,末段就是
|
||
这个组织本身,所以取末段按 ``hub_org_id`` 精确匹配。这样从 Hub 复制过来的 path
|
||
在本地照样指得向同一个部门;Hub 之后把这个组织挪到别处也不影响,因为 id 路径里
|
||
只有末段参与匹配。值里不含 ``/`` 的(比如纯数字的部门名)不走这条路。
|
||
"""
|
||
cleaned = _unit_key(value)
|
||
if not cleaned:
|
||
return []
|
||
raw = str(value or "").strip()
|
||
if "/" in raw:
|
||
pieces = [piece for piece in raw.strip("/").split("/") if piece]
|
||
if pieces and pieces[-1].isdigit():
|
||
by_hub_id = list(
|
||
db.execute(
|
||
select(models.Unit).where(models.Unit.hub_org_id == int(pieces[-1]))
|
||
).scalars().all()
|
||
)
|
||
if by_hub_id:
|
||
return by_hub_id
|
||
return list(
|
||
db.execute(
|
||
select(models.Unit).where(
|
||
or_(
|
||
models.Unit.name == cleaned,
|
||
models.Unit.path == cleaned,
|
||
models.Unit.path == f"{cleaned}\\",
|
||
)
|
||
)
|
||
).scalars().all()
|
||
)
|
||
|
||
|
||
#: 「一串名字 -> 账号」这条路会把这四张表都问一遍(人 -> 部门 -> 角色 -> 分组),
|
||
#: 于是 :mod:`app.readcache` 按这四张一起作废一次请求里的重复解析:写掉任何一张,
|
||
#: 解析结果立刻重来。宁可多作废,也不能漏一张让人读到旧名字。
|
||
_TABLES = ("users", "oa_unit", "oa_role", "oa_group")
|
||
#: 「这个人属于哪个部门」只看这两张。
|
||
_UNIT_TABLES = ("users", "oa_unit")
|
||
#: 「这串引用是谁」(姓名 / 部门 / DN)来自人员档案 + 所在部门两张表:改名、调岗、
|
||
#: 部门改名都要让这一份立刻作废——DN 与部门路径现在是从 ``oa_unit`` 现算的,
|
||
#: 漏掉这张表就会出现"部门改了名,引用里还是旧路径"。
|
||
_REF_TABLES = ("users", "oa_unit")
|
||
|
||
|
||
def _expand_identity(db: Session, value: str) -> list[str] | None:
|
||
"""「身份」这一类选择器按账号取一个人;对不上就回 ``None``。
|
||
|
||
交出来的是账号。以前这里还按精确 DN 认人,配置里那串 DN 一漂,环节就算不出审批人,
|
||
而且不报错;现在只有账号一个口径,配错就该看得见,不替谁兜底。
|
||
"""
|
||
account = personref.account_of(db, value)
|
||
if not account:
|
||
return None
|
||
# 认得出人还不够:停用的算"解析不到人",配置那一侧要看得见(口径见 live_refs)。
|
||
# 在职与否看共用那一份账号档案读,不再为一个人单捞一行整表
|
||
status = personref.account_status(db, [account]).get(account)
|
||
return [account] if status == models.UserStatus.ACTIVE else None
|
||
|
||
|
||
def _expand_person(db: Session, value: str) -> list[str] | None:
|
||
"""按账号或姓名取在职人员;库里没有这个人回 ``None``。
|
||
|
||
有账号但一个身份都挂不上(部门被删干净之类)交出去的还是账号——多身份已经不再是
|
||
本部署的口径,能不能派出活不再取决于身份表上还有没有行,只取决于人还在不在。
|
||
"""
|
||
persons = db.execute(select(models.User).where(_person_match(value))).scalars().all()
|
||
if not persons:
|
||
return None
|
||
return [personref.ref_of(person) for person in persons]
|
||
|
||
|
||
def _expand_unit(db: Session, value: str, *, contains_sub: bool = False) -> list[str] | None:
|
||
"""按部门路径或部门名取部门里的人。
|
||
|
||
``contains_sub`` 默认关:通用兜底口径历来只认这个部门的直属成员,
|
||
只有配置里显式写了 ``containsSub`` 的「部门」选择器才往下含子部门。
|
||
"""
|
||
units = _find_units(db, value)
|
||
if not units:
|
||
return None
|
||
return identities_for_unit(db, [unit.id for unit in units], contains_sub)
|
||
|
||
|
||
#: 岗位角色的成员清单在本 Session 里的缓存键(成员清单存在 ``oa_role.list_auth`` 那一列)。
|
||
_ROLE_KEY = "org.role_members"
|
||
|
||
|
||
def role_members(db: Session, name: str) -> list[str] | None:
|
||
"""岗位角色的成员清单(配置里存的那串原值);``None`` = 没有这个角色。
|
||
|
||
以前每解析一个角色名就单问一趟 ``oa_role``,而一行审批人配置里常常挂着好几个角色
|
||
(实测一次审批四个角色),光角色行就来回四趟。把"取成员清单"这一件事单独缓存,
|
||
:func:`prefetch_roles` 才并把成一条 ``IN`` 查询;改了角色(成员、改名、删角色)
|
||
立刻作废,口径见 :mod:`app.readcache`。
|
||
"""
|
||
key = str(name or "").strip()
|
||
return readcache.get(db, _TABLES, (_ROLE_KEY, key), lambda: _role_members_now(db, key))
|
||
|
||
|
||
def _role_members_now(db: Session, name: str) -> list[str] | None:
|
||
"""真正问库的那一步:只取成员那一列,``oa_role`` 上按唯一名取一行。"""
|
||
row = db.execute(select(models.Role.list_auth).where(models.Role.name == name)).first()
|
||
if row is None:
|
||
return None
|
||
return [str(item) for item in (row[0] or [])]
|
||
|
||
|
||
def prefetch_roles(db: Session, names: Iterable[str]) -> None:
|
||
"""一批角色名一次问完:成员清单合起来一条 ``IN``,成员的预探也合起来探一次。
|
||
|
||
只填缓存,不改判定:之后 :func:`_expand_role` 逐条解析时走的还是同一套代码,
|
||
这条 ``IN`` 没填到的名字(包括压根不存在的角色)照样按逐条口径处理。
|
||
批量查询问崩了就当没预取,退回逐个解析,结果不受影响。
|
||
"""
|
||
keys = list(dict.fromkeys(str(name or "").strip() for name in names if str(name or "").strip()))
|
||
todo = [key for key in keys if not readcache.peek(db, _TABLES, (_ROLE_KEY, key))[0]]
|
||
if not todo:
|
||
return
|
||
try:
|
||
rows = db.execute(
|
||
select(models.Role.name, models.Role.list_auth).where(models.Role.name.in_(todo))
|
||
).all()
|
||
except Exception: # noqa: BLE001 - 预取只是省时间,问不动就退回逐条
|
||
logger.warning("岗位角色批量预取失败,退回逐个解析", exc_info=True)
|
||
return
|
||
members = {str(row[0]): [str(item) for item in (row[1] or [])] for row in rows}
|
||
for key in todo:
|
||
readcache.put(db, _TABLES, (_ROLE_KEY, key), members.get(key))
|
||
# 成员清单到手了,五档预探也一次问完:逐个角色各探一遍等于同一批成员探好几遍
|
||
probe_selectors(db, [member for group in members.values() for member in group])
|
||
|
||
|
||
#: 本次请求已经批量取过哪张流程的角色清单(一个 Session 一张流程只并一次)。
|
||
_ROLE_SEED_KEY = "org.roles_seeded"
|
||
|
||
|
||
def row_list_has_roles(rows: object) -> bool:
|
||
"""这一批审批人来源里有没有「岗位角色」那一类;发起范围之类的行也用同一个形状。"""
|
||
for row in rows if isinstance(rows, list) else []:
|
||
if isinstance(row, dict) and normalize_kind(row.get("type")) == "role":
|
||
return True
|
||
return False
|
||
|
||
|
||
def _role_rows_of(config: object) -> list[object]:
|
||
rows = (config or {}).get("taskValues") if isinstance(config, dict) else None
|
||
return rows if isinstance(rows, list) else []
|
||
|
||
|
||
def prefetch_roles_of(db: Session, definition, config: object) -> None:
|
||
"""**当前这一环真的配了角色审批人时**,把整张流程配到的角色一次取回。
|
||
|
||
审批人爱按角色配,而一张单往往连着好几个环节各配一个角色(实测一次审批里五个环节
|
||
各问一趟 ``oa_role``)。流程定义这会儿已经加载在引擎手里,角色名全在里面,所以第一次
|
||
真要按角色找人时把这批名字一条 ``IN`` 取回,之后每个环节都吃缓存。
|
||
|
||
先问一句"这一环用得到角色吗"是必要的:发起那一刻往往一个角色都不解析,
|
||
无条件预取会白搭上一条 ``IN`` 和一趟成员预探(实测发起多两条语句)。
|
||
"""
|
||
if not row_list_has_roles(_role_rows_of(config)):
|
||
return
|
||
process_id = str(getattr(definition, "process_id", "") or "")
|
||
if not process_id:
|
||
return
|
||
seeded = db.info.setdefault(_ROLE_SEED_KEY, set())
|
||
if process_id in seeded:
|
||
return
|
||
seeded.add(process_id)
|
||
names: list[str] = []
|
||
for node in (getattr(definition, "activities", None) or {}).values():
|
||
for row in _role_rows_of(getattr(node, "config", None)):
|
||
if not isinstance(row, dict) or normalize_kind(row.get("type")) != "role":
|
||
continue
|
||
data = row.get("data") or []
|
||
if isinstance(data, str):
|
||
data = [data]
|
||
names.extend(str(item) for item in data if str(item or "").strip())
|
||
prefetch_roles(db, names)
|
||
|
||
|
||
def _expand_role(db: Session, value: str) -> list[str] | None:
|
||
"""按岗位角色名取成员;``None`` 是没有这个角色,空表是有这个角色但眼下没在职成员。"""
|
||
members = role_members(db, value)
|
||
if members is None:
|
||
return None
|
||
return live_identities(db, resolve_identity_names(db, members))
|
||
|
||
|
||
def _expand_group(db: Session, value: str) -> list[str] | None:
|
||
"""按分组名取成员;``None`` 是没有这个分组,空表是有分组但眼下没成员。"""
|
||
group = db.execute(select(models.Group).where(models.Group.name == value)).scalar_one_or_none()
|
||
if group is None:
|
||
return None
|
||
# list_identity 存的也是账号,同样得过一遍在职校验
|
||
members = live_identities(db, [str(v) for v in group.list_identity or []])
|
||
probe_selectors(db, [str(account) for account in group.list_person or [] if account])
|
||
for account in group.list_person or []:
|
||
# 这一份走的是通用兜底口径,账号 / 姓名都能认
|
||
members.extend(_expand(db, str(account)))
|
||
deduped: list[str] = []
|
||
for member in members:
|
||
if member and str(member) not in deduped:
|
||
deduped.append(str(member))
|
||
return deduped
|
||
|
||
|
||
def memberships_for(db: Session, accounts: Iterable[str]) -> dict[str, list[dict]]:
|
||
"""一批登录账号各自挂在哪些岗位角色 / 分组下("这个人有几个身份"那一问)。
|
||
|
||
正向那套(:func:`expand_as`、:func:`approver_directory`)答的是"这个角色有哪些人";
|
||
把一个人挂进第二个岗位之后,还得有个地方一眼看见他到底挂了几处,否则只能一个岗位
|
||
一个岗位点开翻。这一问是它的反向。
|
||
|
||
两处口径与正向逐字对齐,不然这两份会互相打脸:
|
||
|
||
* 成员值就是这个人的账号 -> 直接挂名,一条库都不必问(``direct``);
|
||
* 剩下的(部门 / 别的角色 / 分组 / 姓名)交给 :func:`expand_accounts_many` 那一份
|
||
批量阶梯,**认得出的才算他的岗位**:认不出的字符串不是一个人,不能因为字符串里
|
||
恰好带着他的姓名就把一个岗位算到他头上。
|
||
|
||
成本跟着配置形状走:成员全填账号时(现网这份配置就是)整趟两条语句——岗位表一条、
|
||
分组表一条,展开那一步被批量那一档整个吃掉。常驻门 ``check_memberships.py`` 钉的
|
||
正是"反查与正向解析逐字一致"与"全账号配置下就问两条"。
|
||
"""
|
||
wanted = {str(account).strip() for account in accounts if str(account or "").strip()}
|
||
result: dict[str, list[dict]] = {account: [] for account in wanted}
|
||
if not wanted:
|
||
return result
|
||
containers: list[tuple[str, str, list[str]]] = []
|
||
for name, members in db.execute(select(models.Role.name, models.Role.list_auth)):
|
||
values = [str(item) for item in (members or []) if str(item or "").strip()]
|
||
containers.append(("role", str(name), values))
|
||
# 分组那两列(list_identity / list_person)在口径上都是成员值,一起算
|
||
for name, identities, persons in db.execute(
|
||
select(models.Group.name, models.Group.list_identity, models.Group.list_person)
|
||
):
|
||
values = [str(item) for item in list(identities or []) + list(persons or []) if str(item or "").strip()]
|
||
containers.append(("group", str(name), list(dict.fromkeys(values))))
|
||
indirect = list(
|
||
dict.fromkeys(value for _kind, _name, members in containers for value in members if value not in wanted)
|
||
)
|
||
expanded = expand_accounts_many(db, indirect) if indirect else {}
|
||
for kind, name, members in containers:
|
||
for value in members:
|
||
if value in wanted:
|
||
hits, direct = [value], True
|
||
else:
|
||
hits = [account for account in expanded.get(value, []) if account in wanted]
|
||
direct = False
|
||
for account in hits:
|
||
rows = result[account]
|
||
# 同一个岗位从两列里各命中一次,只算一个身份;直挂名优先(排在前面)
|
||
if any(row["kind"] == kind and row["name"] == name for row in rows):
|
||
continue
|
||
rows.append({"kind": kind, "name": name, "via": value, "direct": direct})
|
||
for rows in result.values():
|
||
rows.sort(key=lambda row: (not row["direct"], row["kind"], row["name"]))
|
||
return result
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 「这个名字可能落在哪一档」探针
|
||
# ---------------------------------------------------------------------------
|
||
|
||
#: 通用兜底口径(:func:`_expand_uncached`)是一档一档试到底:账号 -> 人员(姓名)->
|
||
#: 部门 -> 岗位角色 -> 分组。配置里还压着历史 DN 的那类成员串五档全不命中,一个值就
|
||
#: 要白问五趟——实测一次审批里三个这种成员白问 15 趟,而库在另一台机器上,一趟十几毫秒。
|
||
#: "这一档到底能不能命中"其实一次问得完:把各档自己的判定条件拼成一条 SELECT 里的几个
|
||
#: EXISTS,一趟拿回答案,肯定不中的档就此跳掉。
|
||
#:
|
||
#: **判定留在库里做**(清一色 ``列 = :值``)。这一步不许挪到 Python 里比字符串:
|
||
#: ``users.account`` 是 ``utf8mb4_unicode_ci``,不分大小写,库里 ``account = 'ZhangSan'``
|
||
#: 认得 ``zhangsan``,Python 的 ``in`` 不认。探针只要比库里严一点点,就会把该试的档跳掉。
|
||
#:
|
||
#: 探针只用来**跳"肯定不中"的档**:说可能就去问库,只有说不可能才跳。所以各档的判定
|
||
#: 条件必须与它自己问库时用的是同一份 —— 见 :func:`_person_match`、
|
||
#: :func:`_unit_key` / :func:`_unit_probe_conds`,别在这一层另写一套。
|
||
#:
|
||
#: ``OA_SELECTOR_PROBE=off`` 整层关掉(A/B 与临时止损用);``=verify`` 是开发期的对照档:
|
||
#: 照常筛着解析一遍,再按完整口径走一遍比结果,不一致就报(慢一倍,只用于验收)。
|
||
_PROBE_CHUNK = 25
|
||
#: 答案在 :mod:`app.readcache` 里的键前缀,与 ``org._expand`` 那一份同进同退(四张表)。
|
||
_PROBE_KEY = "org.selector_probe"
|
||
#: 五档的名字,按试的顺序排;同时也是"探不出来"时的哨兵值(全都可能 = 没信息)。
|
||
_PROBE_KINDS = ("identity", "person", "unit", "role", "group")
|
||
_PROBE_RAW = os.environ.get("OA_SELECTOR_PROBE", "").strip().lower()
|
||
#: 这一层开不开。
|
||
PROBE_ENABLED = _PROBE_RAW not in ("0", "false", "no", "off")
|
||
#: 开发期对照档,口径见上面那段。
|
||
PROBE_VERIFY = _PROBE_RAW == "verify"
|
||
|
||
|
||
def _unit_key(value: str) -> str:
|
||
"""部门选择器洗成要去库里对的那个键:去掉首尾空白与结尾的路径分隔符。"""
|
||
separator = chr(92) # 部门路径的分隔符是反斜杠
|
||
return str(value or "").strip().rstrip(separator)
|
||
|
||
|
||
def _person_match(value: str) -> ColumnElement[bool]:
|
||
"""「按账号或姓名认得到在职的人吗」——:func:`_expand_person` 的判定条件。
|
||
|
||
单独拎出来是因为探针也要问同一件事:两处各写一份,早晚会不一样。
|
||
"""
|
||
return and_(
|
||
or_(models.User.account == value, models.User.display_name == value),
|
||
models.User.status == models.UserStatus.ACTIVE,
|
||
)
|
||
|
||
|
||
def _unit_probe_conds(value: str) -> list[ColumnElement[bool]]:
|
||
""":func:`_find_units` 那两条查询各自的"有没有行",任一条有行就算可能命中。
|
||
|
||
``_find_units`` 先按 Hub 的 id 路径认、认不到再退回名字与路径,两条都可能给出行,
|
||
所以这里问两个 EXISTS。真正交出的是先命中的那一条,这一层不管——探针只回答
|
||
"这一档要不要去试",不替它决定交出谁。
|
||
"""
|
||
cleaned = _unit_key(value)
|
||
if not cleaned:
|
||
return []
|
||
conds = [
|
||
select(models.Unit.id).where(
|
||
or_(
|
||
models.Unit.name == cleaned,
|
||
models.Unit.path == cleaned,
|
||
# 库里存的路径带结尾分隔符,两种写法都要认(与 _find_units 一致)
|
||
models.Unit.path == f"{cleaned}{chr(92)}",
|
||
)
|
||
).exists()
|
||
]
|
||
raw = str(value or "").strip()
|
||
if "/" in raw:
|
||
pieces = [piece for piece in raw.strip("/").split("/") if piece]
|
||
if pieces and pieces[-1].isdigit():
|
||
conds.append(
|
||
select(models.Unit.id).where(models.Unit.hub_org_id == int(pieces[-1])).exists()
|
||
)
|
||
return conds
|
||
|
||
|
||
def _probe_conds(value: str) -> list[tuple[str, ColumnElement[bool]]]:
|
||
"""这个值在每一档上的"可能命中"条件,与各档自己问库时一字不差。"""
|
||
conds: list[tuple[str, ColumnElement[bool]]] = [
|
||
("identity", select(models.User.id).where(models.User.account == value).exists()),
|
||
]
|
||
person_id = models.as_id(value)
|
||
if person_id is not None:
|
||
# 与 ``personref.account_of`` 同口径:``oa_task.person`` 那一类历史列里存的是 users.id
|
||
conds.append(
|
||
("identity", select(models.User.id).where(models.User.id == person_id).exists())
|
||
)
|
||
conds.append(("person", select(models.User.id).where(_person_match(value)).exists()))
|
||
conds.extend(("unit", cond) for cond in _unit_probe_conds(value))
|
||
conds.append(("role", select(models.Role.id).where(models.Role.name == value).exists()))
|
||
conds.append(("group", select(models.Group.id).where(models.Group.name == value).exists()))
|
||
return conds
|
||
|
||
|
||
def _probe_ask(db: Session, values: list[str]) -> dict[str, set[str]]:
|
||
"""一条语句问完一批值,交回 ``{值: {可能命中的档}}``;谁都不沾的就是空集。"""
|
||
hits: dict[str, set[str]] = {value: set() for value in values}
|
||
for start in range(0, len(values), _PROBE_CHUNK):
|
||
marks: list[tuple[str, str]] = []
|
||
conds: list[ColumnElement[bool]] = []
|
||
for value in values[start:start + _PROBE_CHUNK]:
|
||
for kind, cond in _probe_conds(value):
|
||
marks.append((value, kind))
|
||
conds.append(cond)
|
||
# 一条 SELECT 里并排上百个 EXISTS:走的都是索引点查,库里是微秒级的事,
|
||
# 省下来的是一趟一趟的网络往返(本部署一趟十几毫秒)。
|
||
row = db.execute(select(*conds)).one()
|
||
for (value, kind), hit in zip(marks, row):
|
||
if hit:
|
||
hits[value].add(kind)
|
||
return hits
|
||
|
||
|
||
def _probe_tuple(kinds: Iterable[str]) -> tuple[str, ...]:
|
||
"""按试的顺序排一份;空表是"五档都不沾",与"探不出来"(:data:`_PROBE_KINDS`)分开。"""
|
||
chosen = set(kinds)
|
||
return tuple(kind for kind in _PROBE_KINDS if kind in chosen)
|
||
|
||
|
||
def _probe_answers(db: Session, values: list[str]) -> dict[str, set[str]] | None:
|
||
"""一批值各可能落在哪几档:一条语句问完,答案顺手存进本 Session。
|
||
|
||
存进缓存这一笔是重点:后面谁再逐档解析这批值(:func:`_probe_kinds`)就直接跳档,
|
||
不再各问各的。问不动、或这一层整个关掉,交回 ``None``—— callers 各自退回自己的
|
||
逐条问库写法,答案不受影响。
|
||
"""
|
||
if not PROBE_ENABLED:
|
||
return None
|
||
named = list(dict.fromkeys(str(item) for item in values))
|
||
todo = [
|
||
value
|
||
for value in named
|
||
if value and not readcache.peek(db, _TABLES, (_PROBE_KEY, value))[0]
|
||
]
|
||
answers: dict[str, set[str]] = {}
|
||
if todo:
|
||
try:
|
||
answers = _probe_ask(db, todo)
|
||
except Exception: # noqa: BLE001 - 预探只是省时间,问不动就退回逐档,结果不受影响
|
||
logger.warning("选择器预探失败,这一批退回逐档解析", exc_info=True)
|
||
return None
|
||
for value in todo:
|
||
readcache.put(db, _TABLES, (_PROBE_KEY, value), _probe_tuple(answers.get(value, set())))
|
||
for value in named:
|
||
if not value:
|
||
continue
|
||
if value not in answers:
|
||
found, stored = readcache.peek(db, _TABLES, (_PROBE_KEY, value))
|
||
if not found:
|
||
return None # 整批答案缺了一块就别硬答,交给逐条问库
|
||
answers[value] = set(stored or ())
|
||
return answers
|
||
|
||
|
||
def probe_selectors(db: Session, values: Iterable[str]) -> None:
|
||
"""一批选择器一次探完,答案存进本 Session:逐档解析时白跑的那几档就此跳掉。
|
||
|
||
岗位角色与分组的成员清单是最典型的一批:一次审批里那一串成员每个都要走一遍通用
|
||
口径,五档全不命中就是每个值白问五趟;预探一次问完,五趟并成一趟。
|
||
"""
|
||
_probe_answers(db, list(values))
|
||
|
||
|
||
def _probe_kinds(db: Session, value: str, *, allow_query: bool) -> frozenset[str] | None:
|
||
"""这个值可能落在哪几档;交回 ``None`` 表示"探不出来,一档也别跳"。
|
||
|
||
答案存在本 Session 的读缓存里(依赖组织那四张表):同一串审批人在一次请求里会被
|
||
反复解析(每个环节到达都重算一遍),而写过其中任何一张表就立刻重探。
|
||
"""
|
||
if not PROBE_ENABLED:
|
||
return None
|
||
found, stored = readcache.peek(db, _TABLES, (_PROBE_KEY, value))
|
||
if not found:
|
||
if not allow_query:
|
||
return None
|
||
try:
|
||
stored = _probe_tuple(_probe_ask(db, [value]).get(value, set()))
|
||
except Exception: # noqa: BLE001 - 探针问崩了就照原样一档一档试
|
||
logger.warning("选择器探针查询失败,退回逐档解析:%r", value, exc_info=True)
|
||
stored = _PROBE_KINDS
|
||
readcache.put(db, _TABLES, (_PROBE_KEY, value), stored)
|
||
kinds = tuple(stored or ())
|
||
if kinds == _PROBE_KINDS:
|
||
# 五档全都可能:没有档可跳,与"探不出来"当成同一回事
|
||
return None
|
||
return frozenset(kinds)
|
||
|
||
|
||
#: 通用兜底口径要试的五档,顺序即优先级;探针筛的就是这里面的某几档。
|
||
_LADDER: tuple[tuple[str, Callable[[Session, str], list[str] | None]], ...] = (
|
||
("identity", _expand_identity),
|
||
("person", _expand_person),
|
||
("unit", lambda db, value: _expand_unit(db, value, contains_sub=False)),
|
||
("role", _expand_role),
|
||
("group", _expand_group),
|
||
)
|
||
|
||
|
||
def _ladder_run(
|
||
db: Session, value: str, rungs: tuple, possible: frozenset[str] | None
|
||
) -> list[str]:
|
||
"""按顺序试这几档;``possible`` 没点到的档直接跳过(``None`` = 全都试)。"""
|
||
for kind, expand in rungs:
|
||
if possible is not None and kind not in possible:
|
||
continue
|
||
hits = expand(db, value)
|
||
if hits:
|
||
return [str(account) for account in hits if account]
|
||
return []
|
||
|
||
|
||
def _expand_probe_first(db: Session, value: str) -> list[str]:
|
||
"""先按探针筛、再逐档试。
|
||
|
||
没预探过的值先照原样试账号那一档:账号是最常见的形状,为它多问一趟探针是白付。
|
||
预探过的值不走这条路——答案已在缓存里,五档一起筛,一个都不必多问。
|
||
"""
|
||
possible = _probe_kinds(db, value, allow_query=False)
|
||
if possible is not None:
|
||
return _ladder_run(db, value, _LADDER, possible)
|
||
hits = _expand_identity(db, value)
|
||
if hits:
|
||
return [str(account) for account in hits if account]
|
||
return _ladder_run(db, value, _LADDER[1:], _probe_kinds(db, value, allow_query=True))
|
||
|
||
|
||
#: 声明类型 -> 解析函数。``post``(岗位角色)与 ``role`` 同一个口径,配置里两种写法都有。
|
||
_KIND_EXPANDERS: dict[str, Any] = {
|
||
"identity": _expand_identity,
|
||
"person": _expand_person,
|
||
"role": _expand_role,
|
||
"post": _expand_role,
|
||
"group": _expand_group,
|
||
}
|
||
|
||
|
||
def resolve_as(
|
||
db: Session, kind: str, value: str, *, contains_sub: bool = True
|
||
) -> tuple[list[str], bool]:
|
||
"""按配置声明的类型解析一个选择器(带一次请求内的复用)。
|
||
|
||
一次单据流转里同一行来源会被反复解析(每个环节到达都重算一次审批人),而这三样
|
||
——类型、原值、含不含子部门——在一次请求里不会变。组织那四张表被写过就立刻重来。
|
||
"""
|
||
return readcache.get(
|
||
db,
|
||
_TABLES,
|
||
("org.resolve_as", kind, value, contains_sub),
|
||
lambda: _resolve_as_uncached(db, kind, value, contains_sub=contains_sub),
|
||
)
|
||
|
||
|
||
def _resolve_as_uncached(
|
||
db: Session, kind: str, value: str, *, contains_sub: bool = True
|
||
) -> tuple[list[str], bool]:
|
||
"""真正解析一个选择器,返回 ``(账号清单, 这类对象是否存在)``;口径见 :func:`resolve_as`。
|
||
|
||
两种「解析不出人」必须分开:对象根本不存在(多半是类型写错,可以退回通用口径再试),
|
||
和对象在但眼下派不出人(角色空着、部门没直属成员),后者要如实报出去,
|
||
不能拿同名的另一类对象顶上。未知类型回 ``([], False)``。
|
||
"""
|
||
if kind == "unit":
|
||
hits = _expand_unit(db, value, contains_sub=contains_sub)
|
||
else:
|
||
expander = _KIND_EXPANDERS.get(kind)
|
||
if expander is None:
|
||
return [], False
|
||
hits = expander(db, value)
|
||
if hits is None:
|
||
return [], False
|
||
return [str(dn) for dn in hits if dn], True
|
||
|
||
|
||
def expand_as(db: Session, kind: str, value: str, *, contains_sub: bool = True) -> list[str]:
|
||
"""**照配置里声明的类型**解析一个选择器;这类对象不存在就回空表。
|
||
|
||
通用口径 :func:`_expand` 是先部门后角色,于是「总经理」「财务经理」这种
|
||
部门和岗位角色重名的地方永远命中部门,角色里别的人被静静吞掉,配置的人完全看不出来。
|
||
配置既然写了 ``type=role``,这里就按 role 认,重名不再互相顶掉。
|
||
"""
|
||
return resolve_as(db, kind, value, contains_sub=contains_sub)[0]
|
||
|
||
|
||
#: 一个名字在某一类对象里"到底有没有"的复用键(随组织那四张表一起作废)。
|
||
_KIND_KEY = "org.selector_kind"
|
||
|
||
#: "它在哪一类"按试的顺序,交出的措辞与改造前一字不差。
|
||
_KIND_ORDER: tuple[tuple[str, str], ...] = (
|
||
("person", "人员"),
|
||
("unit", "部门"),
|
||
("role", "岗位角色"),
|
||
("group", "分组"),
|
||
)
|
||
|
||
#: 重名的三种组合(部门/岗位角色/分组 两两之间),口径与改造前同一条语句一样。
|
||
_KIND_CLASHES: tuple[tuple[str, str, str], ...] = (
|
||
("unit", "role", "部门与岗位角色"),
|
||
("unit", "group", "部门与分组"),
|
||
("role", "group", "岗位角色与分组"),
|
||
)
|
||
|
||
|
||
def warm_kind_probe(db: Session, values: Iterable[str]) -> None:
|
||
"""把一批名字的五档预探一次问完,之后逐类判存在时才能整批跳档。
|
||
|
||
一个环节上配三四个来源,每个名字都要问"它是哪一类"和"它同时还是哪一类",
|
||
逐条问库就是每个名字三四趟;预探是一条语句挂一批 ``EXISTS``。
|
||
|
||
``OA_READCACHE=off`` 时直接不探:预探的答案存在只读缓存里,那一层关掉之后
|
||
留不住答案,探一次就是白探一次,不如照老写法逐条问库。
|
||
"""
|
||
if not readcache.ENABLED:
|
||
return
|
||
probe_selectors(
|
||
db,
|
||
[text for text in (str(item or "").strip() for item in values) if text],
|
||
)
|
||
|
||
|
||
def _kind_exists(db: Session, value: str, kind: str) -> bool:
|
||
"""这一类对象里有没有这个名字(同一个请求里按「类 + 值」复用一次问库的结果)。
|
||
|
||
叠了两件事省往返,判定本身一句没改:
|
||
|
||
* 预探说过这一档不沾,就不发那条只会回空的查询——探针只用来跳档,从不替
|
||
"存在"下结论(:func:`probe_selectors`),没探到、探针整层关掉、探针问崩了,
|
||
都照原样去问库。
|
||
* 问出来的答案存进只读缓存:同一个名字被"它是哪一类"与"它和谁重名"各问一遍
|
||
的情况就此并成一次;写过组织那四张表任何一张,答案当场作废。
|
||
"""
|
||
key = (_KIND_KEY, kind, value)
|
||
found, stored = readcache.peek(db, _TABLES, key)
|
||
if found:
|
||
return bool(stored)
|
||
probed, kinds = readcache.peek(db, _TABLES, (_PROBE_KEY, value))
|
||
if probed and kind not in tuple(kinds or ()):
|
||
readcache.put(db, _TABLES, key, False) # 探针说这一档不沾:那条查询压根不用发
|
||
return False
|
||
if kind == "person":
|
||
hit = bool(db.execute(
|
||
select(models.User.id).where(
|
||
or_(models.User.account == value, models.User.display_name == value),
|
||
models.User.status == models.UserStatus.ACTIVE,
|
||
)
|
||
).first())
|
||
elif kind == "unit":
|
||
hit = bool(_find_units(db, value))
|
||
elif kind == "role":
|
||
# 角色的成员清单本来就按名字缓存着(:func:`role_members` 交回 ``None``
|
||
# 就是"没有这个角色"),存在性跟着它要,不必再单问一趟 oa_role
|
||
hit = role_members(db, value) is not None
|
||
elif kind == "group":
|
||
hit = bool(db.execute(select(models.Group.id).where(models.Group.name == value)).first())
|
||
else:
|
||
return False # 认不出这一类:不下结论,也不存
|
||
readcache.put(db, _TABLES, key, hit)
|
||
return hit
|
||
|
||
|
||
def selector_kinds_of(db: Session, values: Iterable[str]) -> dict[str, str]:
|
||
"""一批名字各实际存在于哪一类对象里;每个名字判的档与 :func:`selector_kind_of` 一样。"""
|
||
keys = [key for key in dict.fromkeys(str(item or "").strip() for item in values) if key]
|
||
warm_kind_probe(db, keys)
|
||
return {
|
||
key: next((label for kind, label in _KIND_ORDER if _kind_exists(db, key, kind)), "")
|
||
for key in keys
|
||
}
|
||
|
||
|
||
def selector_kind_of(db: Session, value: str) -> str:
|
||
"""这个名字实际存在于哪一类对象里(``身份`` / ``人员`` / ``部门`` / ``岗位角色`` / ``分组``)。
|
||
|
||
只给设计器预览用:配置声明的那一类解析不到时,一眼看出是名字写错了还是来源类型选错了,
|
||
而不是让「解析不到人」变成一条没头没尾的红字。
|
||
"""
|
||
return selector_kinds_of(db, [value]).get(str(value or "").strip(), "")
|
||
|
||
|
||
def selector_kind_conflicts(db: Session, values: Iterable[str]) -> dict[str, str]:
|
||
"""一批名字各自的"同时还是哪一类";判的档与 :func:`selector_kind_conflict` 一样。"""
|
||
keys = [key for key in dict.fromkeys(str(item or "").strip() for item in values) if key]
|
||
warm_kind_probe(db, keys)
|
||
out: dict[str, str] = {}
|
||
for key in keys:
|
||
out[key] = next(
|
||
(label for left, right, label in _KIND_CLASHES
|
||
if _kind_exists(db, key, left) and _kind_exists(db, key, right)),
|
||
"",
|
||
)
|
||
return out
|
||
|
||
|
||
def selector_kind_conflict(db: Session, value: str) -> str:
|
||
"""这个名字同时命中的另一类对象(``部门`` / ``岗位角色`` / ``分组``),没有重名回空串。
|
||
|
||
只给设计器预览当提醒用:重名本身是合法的组织架构,但解析口径必须让人看得见。
|
||
"""
|
||
return selector_kind_conflicts(db, [value]).get(str(value or "").strip(), "")
|
||
|
||
|
||
def _expand(db: Session, value: str) -> list[str]:
|
||
"""通用兜底口径(带一次请求内的复用):组织四张表没被写过,同一个值只解析一次。
|
||
|
||
键吃的是**原值**:下面几档里有的按精确名字比、根本不 strip(岗位角色那一档就是),
|
||
先把值洗一遍等于换了个解析口径。
|
||
"""
|
||
return readcache.get(db, _TABLES, ("org._expand", value), lambda: _expand_uncached(db, value))
|
||
|
||
|
||
def _expand_uncached(db: Session, value: str) -> list[str]:
|
||
#: 没声明类型时的通用兜底口径,优先级保持原样:账号 -> 人员(姓名)-> 部门 -> 角色 -> 分组。
|
||
#: 部门那一档只看直属成员(与加这个功能之前一字不差),配置要含子部门请声明 ``type=unit``。
|
||
#: 配置里写清了类型的选择器请走 :func:`expand_as`,别再依赖这个顺序。
|
||
#:
|
||
#: 认不出人回空表。一串对不上账号的字符串不是一个人:把它原样交回上游,等于让引擎
|
||
#: 给一个根本不存在的人派待办——流程静默卡在环节上,界面上一个错误都不报。要把
|
||
#: "这一条配置认不出人"如实报出去,用 :func:`split_selectors` 或
|
||
#: :func:`resolve_selector_row`,它们把 unknown 单独交回来。
|
||
result = _expand_probe_first(db, value)
|
||
if PROBE_VERIFY:
|
||
# 开发期对照:筛着走一遍、完整口径再走一遍,不一样就报。交出去的仍是完整口径,
|
||
# 这一档只负责把不一致喊出来,不改变任何解析结果。
|
||
full = _ladder_run(db, value, _LADDER, None)
|
||
if full != result:
|
||
logger.error("选择器探针口径不一致:%r 完整=%s 探针=%s", value, full, result)
|
||
return full
|
||
return result
|
||
|
||
|
||
def identities_for_unit(db: Session, unit_ids: list[int], contains_sub: bool = True) -> list[str]:
|
||
"""部门(可含下级)里的人,交出来是账号清单。
|
||
|
||
以前交的是身份 DN,于是数据范围白名单(``permissions.scope_identity_values``)
|
||
与部门选择器全都按 DN 过滤运行态数据:一次部门改名就把主管的历史单据整体看没了。
|
||
换成账号之后,同一份白名单扛得住改名、挪层级、调岗之后的重算。
|
||
|
||
**按人员表算,不按身份表算**:``users.organization_id`` 才是"这个人在哪个部门"的
|
||
当前口径,``oa_identity.unit_id`` 是它的派生副本(同步改部门时两份一起搬)。
|
||
挂不上身份行的人照样是部门成员,不该因为派生数据缺行就从部门里凭空消失。
|
||
"""
|
||
target = unit_ids
|
||
if contains_sub:
|
||
target = []
|
||
for uid in unit_ids:
|
||
for did in descendant_unit_ids(db, uid):
|
||
if did not in target:
|
||
target.append(did)
|
||
if not target:
|
||
return []
|
||
rows = db.execute(
|
||
select(models.User.account)
|
||
.where(models.User.organization_id.in_(target))
|
||
.order_by(models.User.id)
|
||
).scalars().all()
|
||
return [str(account) for account in rows if str(account or "")]
|
||
|
||
|
||
def _ref_of_person(person: models.User) -> IdentityRef:
|
||
"""人员行 -> 引用。部门就是 ``users.organization_id`` 那一份当前口径。
|
||
|
||
以前这里要挑一眼"这个人的默认身份",因为档案上的部门还有一份身份表里的副本;
|
||
那张表下线之后只剩一处真相,也就没有"挑哪一份"这件事了。
|
||
"""
|
||
unit_path = person.organization_path or ""
|
||
return IdentityRef(
|
||
distinguished_name=dn_for(unit_path, person.display_name, str(person.account or "")),
|
||
person=str(person.id),
|
||
person_name=person.display_name,
|
||
unit=unit_path,
|
||
unit_name=person.organization_name or "",
|
||
account=str(person.account or ""),
|
||
)
|
||
|
||
|
||
def _ref_missing(value: str) -> IdentityRef:
|
||
"""对不上人(人走了、手写错、这一条配置本来就没人):按字面给个名字,其余一律空。
|
||
|
||
空引用不替它编部门也不编姓名:调用方拿到的就是"这串字符串谁也不是",界面原样显示,
|
||
设计器据此报红,引擎按"没人可派"走环节上配好的空审批人兜底。
|
||
"""
|
||
return IdentityRef(
|
||
distinguished_name="",
|
||
person="",
|
||
person_name=str(value or ""),
|
||
unit="",
|
||
unit_name="",
|
||
)
|
||
|
||
|
||
def refs_for(db: Session, refs: Iterable[str]) -> dict[str, IdentityRef]:
|
||
"""一批人员引用一次查完:只认账号与 ``users.id``,返回 ``{原值: 引用}``。
|
||
|
||
流程引擎与设计器到处都在「按这串字符串问这个人是谁」,一串审批人就是一趟数据库来回;
|
||
这个库通常在另一台机器上,一次来回十几毫秒。口径与 :func:`ref_for` 一字不差,
|
||
只是把 N 趟并成一趟,顺序按调用方给的去重后的顺序。
|
||
|
||
两趟查询定生死:按 ``users.account`` 认人,剩下按主键试一次(``oa_task.person`` 那一类
|
||
历史列)。部门跟着人一起 JOIN 出来——展示与打印要读的那份部门路径就在 ``oa_unit`` 上,
|
||
不预载就等于在这批人身上长成 N+1。认不出的原样回一个 :func:`_ref_missing`,调用方
|
||
永远拿得到东西,不至于为一个人炸一整页。
|
||
|
||
按**人**存一份(认不出的也存):一次流转里同一批审批人被翻来覆去问好几遍——每到一个
|
||
环节重算审批人、拼标题、写日志都要问。缓存里存的是摊平后的六个字符串,谁也不许
|
||
隔着缓存改档案;``users`` 或 ``oa_unit`` 被写过,这一份立刻作废。
|
||
"""
|
||
wanted = [str(value).strip() for value in dict.fromkeys(refs) if str(value or "").strip()]
|
||
if not wanted:
|
||
return {}
|
||
hit: dict[str, IdentityRef] = {}
|
||
missing: list[str] = []
|
||
for value in wanted:
|
||
found, fields = readcache.peek(db, _REF_TABLES, ("org.refs_for", value))
|
||
if found:
|
||
hit[value] = _ref_of_fields(value, fields)
|
||
else:
|
||
missing.append(value)
|
||
if missing:
|
||
loaded = _refs_for_uncached(db, missing)
|
||
for value in missing:
|
||
hit[value] = put_ref(db, value, loaded.get(value) or _ref_missing(value))
|
||
# 顺序仍按调用方给的去重后的顺序:缓存里先命中的那几个不许插队。
|
||
return {value: hit[value] for value in wanted if value in hit}
|
||
|
||
|
||
def _ref_fields(ref: IdentityRef) -> tuple[str, ...]:
|
||
"""引用摊平成六个字符串再进缓存:缓存里不存可被人改写的对象。"""
|
||
return (ref.distinguished_name, ref.person, ref.person_name, ref.unit, ref.unit_name, ref.account)
|
||
|
||
|
||
def _ref_of_fields(value: str, fields: tuple[str, ...] | None) -> IdentityRef:
|
||
"""从缓存里那六个字符串还原引用;没存过的那一份按"认不出"给。"""
|
||
if not fields or len(fields) != 6:
|
||
return _ref_missing(value)
|
||
distinguished_name, person, person_name, unit, unit_name, account = fields
|
||
return IdentityRef(
|
||
distinguished_name=distinguished_name, person=person, person_name=person_name,
|
||
unit=unit, unit_name=unit_name, account=account,
|
||
)
|
||
|
||
|
||
def put_ref(db: Session, value: str, ref: IdentityRef) -> IdentityRef:
|
||
"""把一个人的引用存进本次请求的缓存,并交出一份新拷贝。"""
|
||
return _ref_of_fields(value, readcache.put(db, _REF_TABLES, ("org.refs_for", value), _ref_fields(ref)))
|
||
|
||
|
||
def _refs_for_uncached(db: Session, wanted: list[str]) -> dict[str, IdentityRef]:
|
||
"""真正问库的那一步:一到两趟查询定生死,口径见 :func:`refs_for`。
|
||
|
||
问库交给 :func:`app.service.personref.rows_for`:账号与 ``users.id`` 那两趟、部门
|
||
的 JOIN、"认不出也记一笔"的缓存,全站只有那一处。以前这里自己捞一遍 ``users``,
|
||
而同一次审批里 :func:`~app.service.personref.resolve` 与
|
||
:func:`~app.service.personref.account_status` 问的又是同一批行,各问各的就是三四趟
|
||
白排;并成一份之后,同一个人一次请求里只问一趟。
|
||
"""
|
||
rows = personref.rows_for(db, wanted)
|
||
return {
|
||
value: (_ref_of_person(rows[value]) if value in rows else _ref_missing(value))
|
||
for value in wanted
|
||
}
|
||
|
||
|
||
def display_names(db: Session, refs: Iterable[str]) -> dict[str, str]:
|
||
"""一批人员引用 -> 给人看的姓名,一次查完;认不出人的回原值,绝不回空串。
|
||
|
||
选人字段那一格里存的是账号,标题、打印、导出都要把它翻回姓名。直接摊账号给
|
||
终端用户看是不合格的("dsh_admin" 没人认得),按 DN 拆字符串又只能拆出历史姓名。
|
||
"""
|
||
wanted = [str(item) for item in dict.fromkeys(refs) if str(item or "").strip()]
|
||
found = refs_for(db, wanted)
|
||
return {value: (found[value].name or value) for value in wanted}
|
||
|
||
|
||
def display_name(db: Session, ref: str) -> str:
|
||
"""一个人的人员引用 -> 姓名;口径与 :func:`display_names` 一致。"""
|
||
return display_names(db, [ref]).get(str(ref or ""), str(ref or ""))
|
||
|
||
|
||
def ref_for(db: Session, ref: str) -> IdentityRef:
|
||
"""一个人的人员引用(账号,或历史列里的 ``users.id``)-> :class:`IdentityRef`。"""
|
||
text = str(ref or "")
|
||
return refs_for(db, [text]).get(text) or _ref_missing(text)
|
||
|
||
|
||
# --------------------------------------------------------------------------
|
||
# 审批人来源:岗位角色 / 分组 / 部门
|
||
# --------------------------------------------------------------------------
|
||
|
||
|
||
def live_refs(db: Session, refs: list[str]) -> list[str]:
|
||
"""只保留还能对上「在职人员」的那些引用,并一律换成账号,顺序不变。
|
||
|
||
岗位角色与分组的成员是按字符串存的:存过 DN 也好、存账号也好,人从统一身份里被
|
||
清掉之后字符串还留在配置里,照原样发给引擎就是把待办挂到一个已经不存在的人身上
|
||
——没有待办、没有报错,流程静静卡在环节上。设计器里也宁可看见「解析不到人」,
|
||
不要一个幽灵审批人。
|
||
|
||
交出来的是账号(认不出人的那条直接丢掉),所以下游拿到的人引用天然扛改名。
|
||
"""
|
||
wanted = [str(value) for value in refs if value]
|
||
if not wanted:
|
||
return []
|
||
mapped = personref.map_accounts(db, wanted)
|
||
if not mapped:
|
||
return []
|
||
# 在不在职问的就是上一行刚捞回来那批账号:同一行 users,不必再问一趟
|
||
# (共用那一份读见 personref.account_status,写了 users 当场作废)
|
||
alive = {
|
||
account
|
||
for account, status in personref.account_status(db, set(mapped.values())).items()
|
||
if status == models.UserStatus.ACTIVE
|
||
}
|
||
out: list[str] = []
|
||
for value in wanted:
|
||
account = mapped.get(value, "")
|
||
if account and account in alive and account not in out:
|
||
out.append(account)
|
||
return out
|
||
|
||
|
||
#: 旧名字留着:调用方读起来还是"把死掉的审批人筛掉",语义没变,只是交出来的形状变成账号。
|
||
live_identities = live_refs
|
||
|
||
|
||
def selector_exists(db: Session, value: str) -> bool:
|
||
"""Whether a configured selector names something that really exists."""
|
||
value = str(value or "").strip()
|
||
if not value:
|
||
return False
|
||
# 身份 DN 不再是一类"存在的对象":它由部门路径和姓名派生,当键用迟早出事
|
||
# 停用人员与 _expand 一样不再算命中,设计器里能直接看到这个人已经不在了
|
||
if db.execute(
|
||
select(models.User.id).where(
|
||
or_(models.User.account == value, models.User.display_name == value),
|
||
models.User.status == models.UserStatus.ACTIVE,
|
||
)
|
||
).first():
|
||
return True
|
||
if _find_units(db, value):
|
||
return True
|
||
if db.execute(select(models.Role.id).where(models.Role.name == value)).first():
|
||
return True
|
||
return bool(db.execute(select(models.Group.id).where(models.Group.name == value)).first())
|
||
|
||
|
||
#: "这一条配置认得出是一个对象吗"要认的四档。身份 DN 不算一档:库里存的人只有登录账号
|
||
#: 这一种写法(见 :mod:`app.service.personref`),探针里的 ``identity`` 那一档问的是
|
||
#: "这个账号/主键在不在 ``users`` 里",不看在职与否,与这里"认不认得出一个能审批的人"
|
||
#: 问的不是同一件事,所以照旧只认下面四档。
|
||
_EXIST_KINDS = frozenset({"person", "unit", "role", "group"})
|
||
|
||
|
||
def selectors_exist(db: Session, values: Iterable[str]) -> dict[str, bool]:
|
||
"""一批选择器的存在性一次问完。
|
||
|
||
一条语句就够:走 :func:`_probe_answers`(一条 SELECT 里并排五档 ``EXISTS``),答案
|
||
同时进本 Session 的缓存,后面展开成员时逐档解析直接跳档。存在与否只看
|
||
:data:`_EXIST_KINDS` 那四档。
|
||
|
||
三种情况退回 :func:`_selectors_exist_by_query`(人、部门、岗位角色、分组各一条批量
|
||
``IN``,与改造前一字不差):探针这一层被 ``OA_SELECTOR_PROBE=off`` 关掉、那条语句
|
||
问崩了、以及**一批值多过一条探针的容量**(``_PROBE_CHUNK``)——值一多,四条带 ``IN``
|
||
的批量查询才是对的工具,别把几百个 ``EXISTS`` 串成一条重语句去换一样多的往返。
|
||
|
||
口径与逐条 :func:`selector_exists` 一致。返回的键是**去掉首尾空格之后**的值,空值一律 ``False``。
|
||
"""
|
||
wanted = list(dict.fromkeys(str(value or "").strip() for value in values))
|
||
named = [value for value in wanted if value]
|
||
if not named:
|
||
return {value: False for value in wanted}
|
||
if len(named) <= _PROBE_CHUNK:
|
||
answers = _probe_answers(db, named)
|
||
if answers is not None:
|
||
return {value: bool(answers.get(value, set()) & _EXIST_KINDS) for value in wanted}
|
||
return _selectors_exist_by_query(db, wanted, named)
|
||
|
||
|
||
def _selectors_exist_by_query(db: Session, wanted: list[str], named: list[str]) -> dict[str, bool]:
|
||
"""逐类批量问库的那条老路:人、部门、岗位角色、分组各一条 ``IN``。
|
||
|
||
部门那一类要小心::func:`_find_units` 认部门名、认带/不带尾分隔符的路径,还认从 Hub
|
||
控制台抄来的 id 路径(``/1/8/10/`` 按末段 ``hub_org_id`` 命中)。这里三种写法各算各的,
|
||
少一种就会出现"逐条问说存在、批量问说不存在"。
|
||
"""
|
||
people = set(
|
||
db.execute(
|
||
select(models.User.account).where(
|
||
models.User.account.in_(named), models.User.status == models.UserStatus.ACTIVE
|
||
)
|
||
).scalars().all()
|
||
) | set(
|
||
db.execute(
|
||
select(models.User.display_name).where(
|
||
models.User.display_name.in_(named), models.User.status == models.UserStatus.ACTIVE
|
||
)
|
||
).scalars().all()
|
||
)
|
||
# 部门:名称 / 路径 / 带尾分隔符的路径三种写法一次捞,另算 Hub 那种 id 路径
|
||
unit_names: set[str] = set()
|
||
unit_paths: set[str] = set()
|
||
paths = {value.rstrip("\\") for value in named if value}
|
||
if paths:
|
||
for row in db.execute(
|
||
select(models.Unit.name, models.Unit.path).where(
|
||
or_(
|
||
models.Unit.name.in_(list(paths)),
|
||
models.Unit.path.in_(list(paths)),
|
||
models.Unit.path.in_([f"{path}\\" for path in paths]),
|
||
)
|
||
)
|
||
).all():
|
||
unit_names.add(str(row.name))
|
||
unit_paths.add(str(row.path or ""))
|
||
hub_ids: set[int] = set()
|
||
id_paths: dict[str, int] = {}
|
||
for value in named:
|
||
if "/" not in value:
|
||
continue
|
||
pieces = [piece for piece in value.strip("/").split("/") if piece]
|
||
if pieces and pieces[-1].isdigit():
|
||
id_paths[value] = int(pieces[-1])
|
||
if id_paths:
|
||
hub_ids = set(
|
||
db.execute(
|
||
select(models.Unit.hub_org_id).where(models.Unit.hub_org_id.in_(list(set(id_paths.values()))))
|
||
).scalars().all()
|
||
)
|
||
role_names = set(
|
||
db.execute(select(models.Role.name).where(models.Role.name.in_(named))).scalars().all()
|
||
)
|
||
group_names = set(
|
||
db.execute(select(models.Group.name).where(models.Group.name.in_(named))).scalars().all()
|
||
)
|
||
|
||
out: dict[str, bool] = {}
|
||
for value in wanted:
|
||
if not value:
|
||
out[value] = False
|
||
continue
|
||
cleaned = value.rstrip("\\")
|
||
exists = (
|
||
value in people
|
||
or cleaned in unit_names
|
||
or cleaned in unit_paths
|
||
or f"{cleaned}\\" in unit_paths
|
||
or (value in id_paths and id_paths[value] in hub_ids)
|
||
or value in role_names
|
||
or value in group_names
|
||
)
|
||
out[value] = bool(exists)
|
||
return out
|
||
|
||
|
||
def account_expands(db: Session, values: Iterable[str]) -> dict[str, list[str]]:
|
||
"""一批选择器里"账号那一档就能定人"的那些,一次批量认好,返回 ``{值: [账号]}``。
|
||
|
||
口径逐字照兜底阶梯的第一档 :func:`_expand_identity`:``account_of`` 认得出、
|
||
且那个人在职,就交出他一个账号。认不出的、认得出但停用的,**一律不进结果**——
|
||
那种值还要往下试姓名 / 部门 / 岗位角色 / 分组,交回逐条口径,这一层不替它决定。
|
||
|
||
为什么单独有这一层::func:`expand_accounts_many` 是一个值一条 Session 并发跑的,
|
||
每个 worker 都得自己为它那一个值问一趟 ``users``,十个成员就是十趟。这一层走
|
||
:func:`app.service.personref.rows_for` 一次问完(认不出也记一笔),把这些值从
|
||
并发里整个摘出去。岗位角色成员换成登录账号之后,设计器那份审批人目录就是这么从
|
||
18 条回到 8 条的。
|
||
"""
|
||
keys = list(dict.fromkeys(str(value or "") for value in values if str(value or "").strip()))
|
||
if not keys:
|
||
return {}
|
||
rows = personref.rows_for(db, keys)
|
||
accounts = [personref.ref_of(rows.get(key)) for key in keys]
|
||
statuses = personref.account_status(db, [a for a in accounts if a])
|
||
out: dict[str, list[str]] = {}
|
||
for key, account in zip(keys, accounts):
|
||
if account and statuses.get(account) == models.UserStatus.ACTIVE:
|
||
out[key] = [account]
|
||
return out
|
||
|
||
|
||
def expand_accounts_many(db: Session, values: list[str]) -> dict[str, list[str]]:
|
||
"""一批**已确认存在**的选择器各自展开成账号清单,值与值互不相干,并发跑。
|
||
|
||
每个值各查各的表(账号 / 姓名 / 部门成员 / 角色成员 / 分组成员),串起来就是
|
||
"值数 × 十几二十毫秒";交给 :func:`app.parallel.gather` 之后只剩一摞并排的往返。
|
||
关掉那一档时 gather 直接在调用方的 Session 上按原顺序跑,与逐条展开一字不差。
|
||
|
||
先被 :func:`account_expands` 批量认掉的那几个值不再进并发:它们的解析就是
|
||
"认账号 + 看在不在职",一次 ``IN`` 问得完,不必一人一条 Session 各问各的。
|
||
"""
|
||
if not values:
|
||
return {}
|
||
ready = account_expands(db, values)
|
||
rest = [value for value in values if value not in ready]
|
||
if not rest:
|
||
return {value: list(ready.get(value, [])) for value in values}
|
||
expanded = parallel.gather(
|
||
db,
|
||
{
|
||
value: (
|
||
lambda session, value=value: [
|
||
str(account) for account in _expand(session, value) if account
|
||
]
|
||
)
|
||
for value in rest
|
||
},
|
||
)
|
||
return {value: ready[value] if value in ready else expanded.get(value, [])
|
||
for value in values}
|
||
|
||
|
||
def _split_one(db: Session, value: str) -> tuple[list[str], bool]:
|
||
"""单个选择器的解析口径:认得回 ``(账号清单, True)``,认不回 ``([], False)``。
|
||
|
||
「存在」与「解析成谁」问的是同一批表,所以先探一次存在性再展开:配置里那条既不是人
|
||
也不是部门/角色/分组时,如实报成认不出,让设计器报红,而不是当成一个人派出去。
|
||
"""
|
||
if not selector_exists(db, value):
|
||
return [], False
|
||
return [str(account) for account in _expand(db, value) if account], True
|
||
|
||
|
||
def split_selectors(db: Session, values: list[str]) -> tuple[list[str], list[str]]:
|
||
"""把选择器摊成账号清单,认不出的那些单独交回来(设计器据此报红)。"""
|
||
resolved: list[str] = []
|
||
unknown: list[str] = []
|
||
probe_selectors(db, [str(raw).strip() for raw in values if raw])
|
||
for raw in values:
|
||
value = str(raw or "").strip()
|
||
if not value:
|
||
continue
|
||
accounts, recognised = _split_one(db, value)
|
||
if not recognised:
|
||
unknown.append(value)
|
||
continue
|
||
for account in accounts:
|
||
if account not in resolved:
|
||
resolved.append(account)
|
||
return resolved, unknown
|
||
|
||
|
||
def resolve_selector_row(
|
||
db: Session, kind: str, data: list[str], contains_sub: bool = True
|
||
) -> tuple[list[str], list[str]]:
|
||
"""Resolve one ``taskValues`` row into (accounts, unrecognised values).
|
||
|
||
``kind`` 是配置里声明的来源类型,这里就**只**照它解析:以前除了 ``unit`` 之外全丢给
|
||
:func:`split_selectors` 的通用口径,于是 ``type=role`` 的「总经理」被同名的
|
||
「总经理」部门顶掉,角色里另外的人一个都不派、也不报错。
|
||
这一类里根本没有这个名字时也不再换个类别接着找:只认这一行声明的那一类对象,其余
|
||
如实报成解析不到,由环节上明配的「空审批人」兜底接住。宁可这一环没人批、设计器报红,
|
||
也不能把待办派给配置里没写的人——身份 DN 那类"看着像人"的字符串同样不算人。
|
||
"""
|
||
values = [str(item).strip() for item in data if str(item or "").strip()]
|
||
if kind == "unit":
|
||
return _resolve_unit_row(db, values, contains_sub)
|
||
if kind == "role":
|
||
# 一行配置里的几个角色合起来问:角色行一条 IN,成员的预探一次
|
||
prefetch_roles(db, values)
|
||
if kind in SELECTOR_KINDS:
|
||
resolved: list[str] = []
|
||
unknown: list[str] = []
|
||
for value in values:
|
||
hits, known = resolve_as(db, kind, value, contains_sub=contains_sub)
|
||
if not known:
|
||
hits = _expand_identity(db, value) or []
|
||
if not hits:
|
||
unknown.append(value)
|
||
continue
|
||
for dn in hits:
|
||
if dn and dn not in resolved:
|
||
resolved.append(dn)
|
||
return resolved, unknown
|
||
return split_selectors(db, values)
|
||
|
||
|
||
def _resolve_unit_row(db: Session, values: list[str], contains_sub: bool) -> tuple[list[str], list[str]]:
|
||
"""按「部门」来源解析:整棵子树还是只认直属,看那一行的 ``containsSub``。"""
|
||
unit_ids: list[str] = []
|
||
unknown: list[str] = []
|
||
for value in values:
|
||
units = _find_units(db, value)
|
||
if not units:
|
||
unknown.append(value)
|
||
continue
|
||
for unit in units:
|
||
if unit.id not in unit_ids:
|
||
unit_ids.append(unit.id)
|
||
return identities_for_unit(db, unit_ids, contains_sub), unknown
|
||
|
||
|
||
def member_briefs(db: Session, refs: Iterable[str]) -> list[dict]:
|
||
"""一批人员引用(账号)-> 可直接展示的轻量成员,一次查完,不逐个问库。"""
|
||
mapping = refs_for(db, refs)
|
||
return [member_brief(mapping.get(str(value)) or _ref_missing(str(value))) for value in refs]
|
||
|
||
|
||
def member_brief(ref: IdentityRef) -> dict:
|
||
"""成员行的形状:设计器、发起范围、审批人目录共用这一份定义。
|
||
|
||
``account`` 是配置与前端之间往来的那个值(存进 ``taskValues`` / 发起范围的就是它);
|
||
``distinguished_name`` 只剩展示老数据用,别再拿它当键。两个都给是为了让改造期间
|
||
前后端各改一半时界面不至于立刻点不动人。
|
||
"""
|
||
return {
|
||
"account": ref.account,
|
||
"distinguished_name": ref.distinguished_name,
|
||
"name": ref.name,
|
||
"person_name": ref.person_name,
|
||
"unit_name": ref.unit_name,
|
||
}
|
||
|
||
|
||
def preview_selectors(db: Session, rows: list[dict], as_identity: str = "", script: str = "") -> dict:
|
||
"""设计器预览:这批审批人配置现在会解析成谁,哪些名字认不出来。
|
||
|
||
上级/负责人这类来源要拿一个样例身份才能试算,默认用 ``as_identity``
|
||
(设计器传当前登录人),并把它同时当成发起人和上一环节处理人。
|
||
``script`` 是环节上的找人脚本,一起试算:脚本找人最容易写错,等流程跑起来
|
||
才发现找不到人,代价是已经发出去的一堆待办。
|
||
"""
|
||
identities: list[str] = []
|
||
unknown: list[str] = []
|
||
dynamic: list[str] = []
|
||
notes: list[str] = []
|
||
sample = str(as_identity or "").strip()
|
||
context = {
|
||
"creator_identity": sample,
|
||
"prev_task_identity_list": [sample] if sample else [],
|
||
}
|
||
# 每一行下面都要问"这个名字是哪一类"和"它同时还是哪一类":整批先探一次档,
|
||
# 探不沾的那一档就地跳过(省的全是只会回空的那种往返)
|
||
probe_values: list[str] = []
|
||
for item in rows:
|
||
if not isinstance(item, dict) or normalize_kind(item.get("type")) not in SELECTOR_KINDS:
|
||
continue
|
||
row_data = item.get("data") or []
|
||
if isinstance(row_data, str):
|
||
row_data = [row_data]
|
||
probe_values.extend(str(value) for value in row_data)
|
||
warm_kind_probe(db, probe_values)
|
||
for item in rows:
|
||
if not isinstance(item, dict):
|
||
continue
|
||
kind = normalize_kind(item.get("type"))
|
||
data = item.get("data") or []
|
||
if isinstance(data, str):
|
||
data = [data]
|
||
if kind in SELECTOR_KINDS:
|
||
resolved, missed = resolve_selector_row(
|
||
db, kind, [str(d) for d in data], bool(item.get("containsSub", True))
|
||
)
|
||
identities.extend(dn for dn in resolved if dn and dn not in identities)
|
||
unknown.extend(name for name in missed if name not in unknown)
|
||
# 按声明类型解析不到:说清这一行是按什么解析的、这个名字在哪一类里,
|
||
# 别让人以为系统会自己去别一类找一个(它不会)
|
||
for value in [str(d) for d in data]:
|
||
if value not in missed:
|
||
continue
|
||
label = SELECTOR_KIND_LABELS.get(kind, kind)
|
||
elsewhere = selector_kind_of(db, value)
|
||
note = (
|
||
f"「{value}」不是{label}"
|
||
+ (f",它是{elsewhere}:要派{elsewhere}里的人就把这一行的来源换成{elsewhere}" if elsewhere else "")
|
||
+ f"。严格按配置解析,不会拿别的类型顶上来"
|
||
)
|
||
if note not in notes:
|
||
notes.append(note)
|
||
# 部门与岗位角色重名是合法的组织架构,但「配的是角色、派的是部门里的人」
|
||
# 这种错位光看名单看不出来,得在设计器预览里当场说一句。
|
||
for value in [str(d) for d in data]:
|
||
clash = selector_kind_conflict(db, value)
|
||
if clash:
|
||
note = (
|
||
f"「{value}」同时是{clash}:现在按配置的「{SELECTOR_KIND_LABELS.get(kind, kind)}」"
|
||
f"解析出 {len(resolved)} 人,改口径请换这一行的来源类型"
|
||
)
|
||
if note not in notes:
|
||
notes.append(note)
|
||
elif kind in RELATION_KINDS:
|
||
if not sample:
|
||
dynamic.append(kind)
|
||
notes.append(f"{RELATION_LABELS.get(kind, kind)}:需要先选一个试算身份才能预览")
|
||
continue
|
||
resolved, note = resolve_relations(db, kind, [str(d) for d in data], context)
|
||
identities.extend(dn for dn in resolved if dn and dn not in identities)
|
||
if note:
|
||
notes.append(f"{RELATION_LABELS.get(kind, kind)}:{note}")
|
||
elif kind in DYNAMIC_KINDS:
|
||
dynamic.append(kind)
|
||
|
||
if str(script or "").strip():
|
||
from ..engine import expressions # 延迟导入,避免 service 与 engine 相互引用成环
|
||
|
||
try:
|
||
produced = expressions.run_identity_script(str(script), {"data": {}, "creator_identity": sample})
|
||
except Exception as exc: # 预览不该因为一段跑不通的脚本而报错
|
||
produced = []
|
||
notes.append(f"找人脚本:执行失败({exc})")
|
||
resolved, missed = split_selectors(db, [str(v) for v in produced])
|
||
identities.extend(dn for dn in resolved if dn and dn not in identities)
|
||
if not resolved and missed:
|
||
unknown.extend(name for name in missed if name not in unknown)
|
||
notes.append("找人脚本:现在解析不到还在职的人,运行时会按兜底设置处理")
|
||
|
||
as_ref = ref_for(db, sample) if sample else None
|
||
return {
|
||
"identities": member_briefs(db, identities),
|
||
"unknown": unknown,
|
||
"dynamic": sorted(set(dynamic)),
|
||
"notes": notes,
|
||
"as_identity": sample,
|
||
"as_identity_name": as_ref.person_name if as_ref else "",
|
||
}
|
||
|
||
|
||
def approver_directory(db: Session) -> dict:
|
||
"""设计器选审批人用的岗位角色 / 分组 / 部门清单,各自带解析后的成员。"""
|
||
role_rows = list(db.execute(select(models.Role).order_by(models.Role.name)).scalars().all())
|
||
group_rows = list(db.execute(select(models.Group).order_by(models.Group.name)).scalars().all())
|
||
# 选择器先统统收集起来:同一个值这一次调用里只解析一遍。以前是每个角色、每个分组
|
||
# 各解析各的,实测这份目录要 49 个数据库来回。
|
||
selectors: list[str] = []
|
||
for row in role_rows:
|
||
selectors.extend(row.list_auth or [])
|
||
for row in group_rows:
|
||
selectors.extend(list(row.list_identity or []) + list(row.list_person or []))
|
||
# 存在性按"类"问(四条),确认存在的再并发展开:这两个值数相乘的账不该按值排队
|
||
values = list(dict.fromkeys(value for value in (str(item or "").strip() for item in selectors) if value))
|
||
exists = selectors_exist(db, values)
|
||
expanded = expand_accounts_many(db, [value for value in values if exists.get(value)])
|
||
memo: dict[str, tuple[list[str], bool]] = {
|
||
value: (expanded.get(value, []), True) if exists.get(value) else ([], False)
|
||
for value in values
|
||
}
|
||
|
||
def split(values: Iterable[object]) -> tuple[list[str], list[str]]:
|
||
resolved: list[str] = []
|
||
unknown: list[str] = []
|
||
for raw in values:
|
||
value = str(raw or "").strip()
|
||
if not value:
|
||
continue
|
||
if value not in memo:
|
||
memo[value] = _split_one(db, value)
|
||
accounts, recognised = memo[value]
|
||
if not recognised:
|
||
unknown.append(value)
|
||
continue
|
||
resolved.extend(accounts)
|
||
return list(dict.fromkeys(resolved)), unknown
|
||
|
||
role_entries = [(row, split(row.list_auth or [])) for row in role_rows]
|
||
group_entries = [
|
||
(row, split(list(row.list_identity or []) + list(row.list_person or []))) for row in group_rows
|
||
]
|
||
# 成员卡片上的姓名与部门:这批 DN 也是一次查完
|
||
refs = refs_for(db, [dn for _, (dns, _unknown) in role_entries + group_entries for dn in dns])
|
||
|
||
def cards(dns: list[str]) -> list[dict]:
|
||
return [member_brief(refs.get(dn) or _ref_missing(dn)) for dn in dns]
|
||
|
||
roles = [
|
||
{
|
||
"name": row.name,
|
||
"description": row.description,
|
||
"unit": row.unit,
|
||
"members": cards(dns),
|
||
"unknown": unknown,
|
||
}
|
||
for row, (dns, unknown) in role_entries
|
||
]
|
||
groups = [
|
||
{
|
||
"name": row.name,
|
||
"description": row.description,
|
||
"unit": row.unit,
|
||
"members": cards(dns),
|
||
"unknown": unknown,
|
||
}
|
||
for row, (dns, unknown) in group_entries
|
||
]
|
||
# 人数按人员表数:``users.organization_id`` 才是"谁在这个部门"的当前口径,
|
||
# 身份表是它的派生副本,派生数据缺行不该让设计器里的部门少几个人
|
||
counts: dict[str, int] = dict(
|
||
db.execute(
|
||
select(models.User.organization_id, func.count(models.User.id))
|
||
.where(models.User.organization_id.is_not(None))
|
||
.group_by(models.User.organization_id)
|
||
).all()
|
||
)
|
||
unit_rows = list(db.execute(select(models.Unit).order_by(models.Unit.path)).scalars().all())
|
||
manager_ids = sorted({int(row.manager_person_id) for row in unit_rows if row.manager_person_id})
|
||
managers = {
|
||
person.id: person
|
||
for person in (
|
||
db.execute(select(models.User).where(models.User.id.in_(manager_ids))).scalars().all()
|
||
if manager_ids
|
||
else ()
|
||
)
|
||
}
|
||
units: list[dict] = []
|
||
for row in unit_rows:
|
||
path = (row.path or row.name).rstrip("\\")
|
||
manager = managers.get(row.manager_person_id) if row.manager_person_id else None
|
||
units.append(
|
||
{
|
||
"id": row.id,
|
||
"name": row.name,
|
||
"path": path,
|
||
"description": row.description,
|
||
"person_count": counts.get(row.id, 0),
|
||
# 设计器里选部门时要能一眼看出这个部门的负责人是谁,配「部门负责人」审批才不会瞎选。
|
||
"manager_person_id": str(row.manager_person_id) if row.manager_person_id else None,
|
||
"manager_name": manager.display_name if manager else "",
|
||
# 部门停用(含统一身份同步下线)后仍可能被老配置引用,设计器要能看见这层状态。
|
||
"status": int(row.status),
|
||
"status_label": models.UnitStatus.label(row.status),
|
||
}
|
||
)
|
||
return {"roles": roles, "groups": groups, "units": units}
|
||
|
||
|
||
# --------------------------------------------------------------------------
|
||
# 上下级:直属上级 / 部门负责人 / 逐级向上兜底
|
||
# --------------------------------------------------------------------------
|
||
|
||
|
||
def person_by_identity(db: Session, ref: str) -> models.User | None:
|
||
"""人员引用(登录账号,或历史列里的 ``users.id``)-> 人员;认不出回 ``None``。
|
||
|
||
口径就是 :func:`app.service.personref.account_of` 那两条,不再按姓名或 DN 猜:
|
||
这条路算的是"审批发给谁""发起人是谁",认错人的代价是把别人的单子、别人的部门主管
|
||
派出去,比没人收到待办严重得多。要按姓名找人,请在配置里用显式的 ``person`` 来源。
|
||
"""
|
||
return personref.resolve(db, str(ref or "").strip())
|
||
|
||
|
||
def unit_by_identity(db: Session, ref: str) -> models.Unit | None:
|
||
"""人员引用 -> 所在部门:只读 ``users.organization_id``。
|
||
|
||
那一列才是"这个人在哪个部门"的当前口径。以前先查身份表、再按 DN 的部门前缀反查:
|
||
身份行是派生数据,同步漏建或部门重挂之后就指到旧部门去了,配「部门负责人」审批的人
|
||
就这么派错了上级。认不出人就没有部门可给——不猜。
|
||
"""
|
||
text = str(ref or "").strip()
|
||
if not text:
|
||
return None
|
||
return readcache.get(db, _UNIT_TABLES, ("org.unit_by_identity", text), lambda: _unit_by_ref(db, text))
|
||
|
||
|
||
def _unit_by_ref(db: Session, text: str) -> models.Unit | None:
|
||
"""真正问库的那一步:认人,再按人身上那一列取部门。"""
|
||
person = personref.resolve(db, text)
|
||
return _person_unit(db, person) if person is not None else None
|
||
|
||
|
||
def person_ref(db: Session, person: models.User | None) -> str:
|
||
"""人员 -> 库里认人用的那个字符串(登录账号)。
|
||
|
||
以前这条路返回默认身份 DN,于是"上级是谁""部门负责人是谁"发出去的都是 DN,部门一
|
||
改名这些待办就找不到人。现在不看身份表:账号就是账号,人还在、账号没变,待办就发得出去。
|
||
"""
|
||
return personref.ref_of(person)
|
||
|
||
|
||
#: 旧名字留给还没跟上的调用方与脚本;新代码一律用 :func:`person_ref`。
|
||
identity_of_person = person_ref
|
||
|
||
|
||
def person_account(db: Session, value: object) -> str:
|
||
"""选人字段给的那个值 -> 登录账号;认不出来回空串。
|
||
|
||
口径只有一份,在 :func:`app.service.personref.account_of`;这里留个名字是给取数
|
||
配置那两侧用的(``{account:form.x}``,见 :mod:`app.service.mapping`),措辞与
|
||
分寸都在那边写清了:不看停用、不按姓名猜。
|
||
|
||
``type: user`` 那一格交出来的**就是**账号,这一层翻译是幂等的直通;留着它是因为
|
||
历史列里还可能有 ``users.id`` 写法,而 ``oa_bank_account``、财务导出模板、上游系统的
|
||
"员工编码"认的从来都是 ``users.account``。身份 DN 换不出账号——它不是引用口径。
|
||
"""
|
||
return personref.account_of(db, value)
|
||
|
||
|
||
#: 设计器下拉里的中文名;后端只负责解析,展示文案前端另有一份 i18n。
|
||
RELATION_LABELS = {
|
||
"creatorLeader": "发起人直属上级",
|
||
"creatorLeaderChain": "发起人连续多级上级",
|
||
"creatorUnitManager": "发起人部门负责人",
|
||
"creatorParentUnitManager": "发起人上级部门负责人",
|
||
"creatorTeamLeader": "发起人本级负责人(组长)",
|
||
"prevLeader": "上一环节处理人直属上级",
|
||
"prevUnitManager": "上一环节处理人部门负责人",
|
||
"unitManager": "指定部门负责人",
|
||
}
|
||
|
||
|
||
def unit_manager_person(db: Session, unit: models.Unit | None) -> models.User | None:
|
||
"""部门登记在册的负责人;没配置或人停了就返回 None(调用方决定是否向上兜底)。"""
|
||
if unit is None or not unit.manager_person_id:
|
||
return None
|
||
person = db.get(models.User, unit.manager_person_id)
|
||
if person is None or person.status != models.UserStatus.ACTIVE:
|
||
return None
|
||
return person
|
||
|
||
|
||
def manager_unit_upward(
|
||
db: Session, unit: models.Unit | None, *, include_self: bool = True
|
||
) -> models.Unit | None:
|
||
"""从 ``unit`` 出发逐级向上,返回第一个设了负责人的部门。
|
||
|
||
「部门负责人审批」在真实组织里经常落在上级部门头上(小组没设负责人),这是给那种
|
||
口径留的;``include_self=False`` 用于「上级部门负责人」。**默认口径不从这里走**——
|
||
开着「严格按配置找人」(:func:`strict_approvers`,默认开)时配了什么部门就只认那个
|
||
部门自己登记的负责人,只有显式关掉那一项,环节找负责人才会回到这里逐级向上找。
|
||
"""
|
||
current = unit if include_self else (db.get(models.Unit, unit.parent_id) if unit and unit.parent_id else None)
|
||
guard = 0
|
||
while current is not None and guard < 30:
|
||
if unit_manager_person(db, current) is not None:
|
||
return current
|
||
current = db.get(models.Unit, current.parent_id) if current.parent_id else None
|
||
guard += 1
|
||
return None
|
||
|
||
|
||
def strict_approvers() -> bool:
|
||
"""审批人是不是「配置里写什么就照什么解析」。
|
||
|
||
开着(默认)的时候,平台不替配置多走一步:「部门负责人」只认这个部门自己登记的负责人,
|
||
不逐级向上找;「直属上级」只认登记过的直属上级,不拿部门负责人顶替。解析不到人不是
|
||
解析错人——环节上明配的「空审批人」兜底会接住它,设计器预览也当场报不出来的是谁。
|
||
关掉这一项恢复老口径(逐级向上找、直属上级退回部门负责人),见 ``dbconfig`` 里
|
||
``approver_strict`` 那一项。
|
||
"""
|
||
from .. import dbconfig # 延迟导入:dbconfig 读库,别在模块导入期就把它拽进来
|
||
|
||
return bool(dbconfig.value("approver_strict", True))
|
||
|
||
|
||
def unit_manager_identity(
|
||
db: Session, unit: models.Unit | None, *, upward: bool | None = None
|
||
) -> str:
|
||
"""部门负责人 -> 身份 DN。
|
||
|
||
``upward`` 是「这一级没登记负责人就逐级向上找」:留空跟着「严格按配置找人」那一项走
|
||
(默认不向上),显式传值就是这个环节自己说了算;``upward=False`` 就是
|
||
「本级最小组织负责人」(组长)。
|
||
"""
|
||
climb = (not strict_approvers()) if upward is None else bool(upward)
|
||
target = manager_unit_upward(db, unit, include_self=True) if climb else unit
|
||
if target is None:
|
||
return ""
|
||
person = unit_manager_person(db, target)
|
||
return identity_of_person(db, person) if person else ""
|
||
|
||
|
||
def explicit_leader(db: Session, person: models.User | None) -> models.User | None:
|
||
"""只看显式登记的直属上级(``users.leader_id``),不做部门兜底。"""
|
||
if person is None or not person.leader_id:
|
||
return None
|
||
leader = db.get(models.User, person.leader_id)
|
||
if leader is None or leader.status != models.UserStatus.ACTIVE or leader.id == person.id:
|
||
return None
|
||
return leader
|
||
|
||
|
||
def leader_person(db: Session, person: models.User | None) -> models.User | None:
|
||
"""直属上级:只认 ``users.leader_id`` 上登记的那个人。
|
||
|
||
关掉「严格按配置找人」之后,没登记直属上级的人退回所在部门(含逐级向上)的负责人——
|
||
只维护了组织架构、没逐个维护直属上级的公司要的就是这一步。开着的时候这里就回空:
|
||
「上级审批」的环节解析不到人,比把部门负责人当成直属上级派出去更容易查。
|
||
"""
|
||
if person is None:
|
||
return None
|
||
if strict_approvers():
|
||
return explicit_leader(db, person)
|
||
if person.leader_id:
|
||
leader = db.get(models.User, person.leader_id)
|
||
if leader is not None and leader.status == models.UserStatus.ACTIVE and leader.id != person.id:
|
||
return leader
|
||
manager = unit_manager_person(db, manager_unit_upward(db, _person_unit(db, person)))
|
||
return manager if manager is not None and manager.id != person.id else None
|
||
|
||
|
||
def _person_unit(db: Session, person: models.User | None) -> models.Unit | None:
|
||
if person is None or not person.organization_id:
|
||
return None
|
||
return db.get(models.Unit, person.organization_id)
|
||
|
||
|
||
def leader_chain(db: Session, person: models.User | None, depth: int) -> list[str]:
|
||
"""连续 N 级上级(直属上级 → 上级的人 …),自动去重并跳过自己。
|
||
|
||
只沿显式登记的 ``leader_id`` 往上走:兜底到部门负责人会让链条横着拐弯
|
||
(总经理 → 隔壁综合管理部负责人),逐级找部门负责人的需求请用「发起人部门负责人」。
|
||
"""
|
||
out: list[str] = []
|
||
current = person
|
||
seen: set[int] = {person.id} if person else set()
|
||
for _ in range(max(0, min(int(depth or 1), MAX_LEADER_CHAIN))):
|
||
current = explicit_leader(db, current)
|
||
if current is None or current.id in seen:
|
||
break
|
||
seen.add(current.id)
|
||
dn = identity_of_person(db, current)
|
||
if dn and dn not in out:
|
||
out.append(dn)
|
||
return out
|
||
|
||
|
||
def _chain_depth(data: list[str]) -> int:
|
||
for value in data:
|
||
try:
|
||
return max(1, min(int(float(value)), MAX_LEADER_CHAIN))
|
||
except (TypeError, ValueError):
|
||
continue
|
||
return 2
|
||
|
||
|
||
def _relation_note(kind: str, data: list[str]) -> str:
|
||
"""没解析出人时说清楚为什么,别让设计器只留一个空名单,也别让人猜是不是又向上兜底了。"""
|
||
strict = strict_approvers()
|
||
if kind == "creatorLeaderChain":
|
||
return "发起人的直属上级链断开(中间有人没登记直属上级)"
|
||
if kind in {"creatorLeader", "prevLeader"}:
|
||
return (
|
||
"没有登记直属上级(严格按配置找人,不拿部门负责人顶替;"
|
||
"系统设置里关掉「严格按配置找人」才会退回部门负责人)"
|
||
if strict
|
||
else "未设置直属上级,且所在部门(含上级部门)未设负责人"
|
||
)
|
||
if kind in {"creatorUnitManager", "creatorParentUnitManager", "prevUnitManager"}:
|
||
return (
|
||
"对应的部门自己没登记负责人(严格按配置找人,不向上级部门找;"
|
||
"要找上级部门负责人就换成「上级部门负责人」这一项)"
|
||
if strict
|
||
else "所在部门及其上级部门都没有设置负责人"
|
||
)
|
||
if kind == "creatorTeamLeader":
|
||
return "所在部门(本级)没有设置负责人,本项不向上级兜底"
|
||
if kind == "unitManager":
|
||
return (
|
||
"所选部门自己没登记负责人(严格按配置找人,不向上级部门找)"
|
||
if strict
|
||
else "所选部门及其上级部门没有设置负责人"
|
||
)
|
||
return ""
|
||
|
||
|
||
def resolve_relations(
|
||
db: Session, kind: str, data: list[str], context: dict
|
||
) -> tuple[list[str], str]:
|
||
"""按组织层级解析一个动态审批人来源,返回(身份 DN,未解析原因)。"""
|
||
creator = context_creator_identity(context)
|
||
prev = context_prev_identities(context)
|
||
out: list[str] = []
|
||
|
||
def push(value: str) -> None:
|
||
if value and value not in out:
|
||
out.append(value)
|
||
|
||
if kind == "creatorLeader":
|
||
push(identity_of_person(db, leader_person(db, person_by_identity(db, creator))))
|
||
elif kind == "creatorLeaderChain":
|
||
for dn in leader_chain(db, person_by_identity(db, creator), _chain_depth(data)):
|
||
push(dn)
|
||
elif kind == "creatorUnitManager":
|
||
push(unit_manager_identity(db, unit_by_identity(db, creator)))
|
||
elif kind == "creatorParentUnitManager":
|
||
unit = unit_by_identity(db, creator)
|
||
parent = db.get(models.Unit, unit.parent_id) if unit and unit.parent_id else None
|
||
push(unit_manager_identity(db, parent))
|
||
elif kind == "creatorTeamLeader":
|
||
push(unit_manager_identity(db, unit_by_identity(db, creator), upward=False))
|
||
elif kind in {"prevLeader", "prevUnitManager"}:
|
||
for dn in prev:
|
||
if kind == "prevLeader":
|
||
push(identity_of_person(db, leader_person(db, person_by_identity(db, dn))))
|
||
else:
|
||
push(unit_manager_identity(db, unit_by_identity(db, dn)))
|
||
elif kind == "unitManager":
|
||
for value in data:
|
||
push(unit_manager_identity(db, _first(_find_units(db, str(value)))))
|
||
if not out and not data:
|
||
return [], "还没有选择部门"
|
||
else:
|
||
return [], ""
|
||
|
||
return out, ("" if out else _relation_note(kind, data))
|
||
|
||
|
||
def _first(rows: list) -> object | None:
|
||
return rows[0] if rows else None
|
||
|
||
|
||
def has_enabled_agent(db: Session) -> bool:
|
||
"""库里还有没有启用的流程代理(:mod:`app.presence` 的那一个探针)。"""
|
||
return db.execute(
|
||
select(models.Agent.id).where(models.Agent.enabled.is_(True)).limit(1)
|
||
).first() is not None
|
||
|
||
|
||
def apply_agents(db: Session, process_id: str, identities: list[str], now: datetime) -> dict[str, str]:
|
||
"""Return ``{original_dn: delivered_dn}`` honouring active 流程代理."""
|
||
if not identities:
|
||
return {}
|
||
# 一条启用的代理都没有时连库都不问(口径与作废规则见 :mod:`app.presence`)
|
||
if not presence.any_row(db, "oa_agent", has_enabled_agent):
|
||
return {}
|
||
rows = db.execute(
|
||
select(models.Agent).where(
|
||
models.Agent.enabled.is_(True),
|
||
models.Agent.from_identity.in_(identities),
|
||
(models.Agent.process == "") | (models.Agent.process == process_id),
|
||
)
|
||
).scalars().all()
|
||
mapping: dict[str, tuple[str, datetime | None, datetime | None]] = {}
|
||
for agent in rows:
|
||
if agent.enable_time and agent.enable_time > now:
|
||
continue
|
||
if agent.expire_time and agent.expire_time < now:
|
||
continue
|
||
current = mapping.get(agent.from_identity)
|
||
if current is None or (current[1] is None) or (
|
||
agent.enable_time and current[1] and agent.enable_time > current[1]
|
||
):
|
||
mapping[agent.from_identity] = (agent.identity, agent.enable_time, agent.expire_time)
|
||
return {k: v[0] for k, v in mapping.items()}
|
||
|
||
|
||
def context_creator_identity(context: dict) -> str:
|
||
"""引擎上下文里的发起人身份。
|
||
|
||
``_context`` 把这些值挂在 ``work`` 下面,老代码却按顶层键读,``creator`` 这一类
|
||
来源于是靠「解析不出人就退回发起人」的兜底才没露馅;两种写法都认一遍。
|
||
"""
|
||
work = context.get("work") if isinstance(context.get("work"), dict) else {}
|
||
return str(context.get("creator_identity") or (work or {}).get("creator_identity") or "")
|
||
|
||
|
||
def context_prev_identities(context: dict) -> list[str]:
|
||
return [str(dn) for dn in (context.get("prev_task_identity_list") or []) if dn]
|
||
|
||
|
||
def resolve_task_identities(
|
||
db: Session,
|
||
process_id: str,
|
||
config: dict,
|
||
context: dict,
|
||
) -> list[str]:
|
||
"""Resolve the ``taskValues`` / ``taskScript`` of a manual activity.
|
||
|
||
``context`` exposes ``data`` (form data), ``work`` and ``creator`` so that
|
||
scripts can compute approvers dynamically.
|
||
"""
|
||
from ..engine import expressions # local import to avoid a cycle
|
||
|
||
identities: list[str] = []
|
||
for item in config.get("taskValues") or []:
|
||
if not isinstance(item, dict):
|
||
continue
|
||
kind = normalize_kind(item.get("type"))
|
||
data = item.get("data") or []
|
||
if isinstance(data, str):
|
||
data = [data]
|
||
if kind in SELECTOR_KINDS:
|
||
resolved, unknown = resolve_selector_row(
|
||
db, kind, [str(d) for d in data], bool(item.get("containsSub", True))
|
||
)
|
||
identities.extend(resolved)
|
||
# unknown 不进清单:对不上账号的字符串不是一个人。给它派待办等于把流程悄悄
|
||
# 卡死在这一环(那个"人"的待办列表里永远不会出现这条),宁可让环节按配好的
|
||
# emptyApprover 兜底,并由设计器的审批体检把它报出来
|
||
elif kind == "creator":
|
||
identities.append(context_creator_identity(context))
|
||
elif kind == "prev":
|
||
identities.extend(context_prev_identities(context))
|
||
elif kind == "prevunit":
|
||
# 「上一环节处理人所在部门」要展开成部门里的人:先按账号认到人,再读他的部门
|
||
# (口径与「部门」来源一致,取直属成员)。以前是从人员引用字符串里切部门前缀,
|
||
# 换成账号之后那一段根本不存在,切出来只会是个查不到东西的部门路径。
|
||
unit_ids: list[int] = []
|
||
for account in context_prev_identities(context):
|
||
unit = unit_by_identity(db, account)
|
||
if unit is not None and unit.id not in unit_ids:
|
||
unit_ids.append(unit.id)
|
||
identities.extend(identities_for_unit(db, unit_ids, False))
|
||
elif kind in RELATION_KINDS:
|
||
resolved, _ = resolve_relations(db, kind, [str(d) for d in data], context)
|
||
identities.extend(resolved)
|
||
elif kind == "form":
|
||
values: list[str] = []
|
||
for path in data:
|
||
values.extend(_read_form_values(context.get("data") or {}, str(path)))
|
||
identities.extend(resolve_identity_names(db, values))
|
||
script = (config.get("taskScript") or "").strip()
|
||
if script:
|
||
for value in expressions.run_identity_script(script, context):
|
||
identities.extend(resolve_identity_names(db, [str(value)]))
|
||
|
||
deduped: list[str] = []
|
||
for dn in identities:
|
||
if dn and dn not in deduped:
|
||
deduped.append(dn)
|
||
# 到了要派活的地步,只认还在职的人:配置里写错的、部门里已停用的
|
||
# 成员都在这一步挡掉;剩下真没人时交给 emptyToCreator 兜底。
|
||
kept = live_identities(db, deduped)
|
||
dropped = [dn for dn in deduped if dn not in set(kept)]
|
||
if dropped:
|
||
logger.warning(
|
||
"环节找人解析出 %d 个已失效身份,已跳过:%s",
|
||
len(dropped),
|
||
"、".join(dropped[:5]) + ("…" if len(dropped) > 5 else ""),
|
||
)
|
||
return kept
|
||
|
||
|
||
def _unit_names_to_ids(db: Session, names: list[str]) -> list[str]:
|
||
ids: list[str] = []
|
||
for name in names:
|
||
for unit in _find_units(db, name):
|
||
if unit.id not in ids:
|
||
ids.append(unit.id)
|
||
return ids
|
||
|
||
|
||
def _read_form_values(data: dict, path: str) -> list[str]:
|
||
"""Read ``a.b.c`` (or ``a[].b``) out of the form payload."""
|
||
current: object = data
|
||
for part in path.replace("[", ".[").split("."):
|
||
if part in ("", "."):
|
||
continue
|
||
if part.startswith("[") and part.endswith("]"):
|
||
if not isinstance(current, list):
|
||
return []
|
||
idx = part[1:-1]
|
||
if idx == "":
|
||
return [v for item in current for v in _flatten_strings(item)]
|
||
try:
|
||
current = current[int(idx)]
|
||
except (ValueError, IndexError):
|
||
return []
|
||
elif isinstance(current, dict):
|
||
current = current.get(part)
|
||
else:
|
||
return []
|
||
return _flatten_strings(current)
|
||
|
||
|
||
def _flatten_strings(value: object) -> list[str]:
|
||
if value is None:
|
||
return []
|
||
if isinstance(value, list):
|
||
out: list[str] = []
|
||
for item in value:
|
||
out.extend(_flatten_strings(item))
|
||
return out
|
||
if isinstance(value, dict):
|
||
out = []
|
||
for key in ("distinguishedName", "identity", "value", "name", "account"):
|
||
if key in value:
|
||
out.extend(_flatten_strings(value[key]))
|
||
return out
|
||
return [str(value)]
|
||
|
||
|
||
def count_persons(db: Session) -> int:
|
||
"""在册人数:只数 ``users.status = 1`` 的在职账号。
|
||
|
||
``users.status`` 是 0/1/2/3 四态,停用与待审核的人都还在表里;按行数算会把
|
||
Hub 夜间同步下线掉的人继续算成在职人数。
|
||
"""
|
||
return int(
|
||
db.execute(
|
||
select(func.count(models.User.id)).where(models.User.status == models.UserStatus.ACTIVE)
|
||
).scalar()
|
||
or 0
|
||
)
|