1275 lines
54 KiB
Python
1275 lines
54 KiB
Python
"""Organization helpers: identities, groups, roles, agents.
|
||
|
||
Mirrors the O2OA organization model where a *person* owns one or more
|
||
*identities* (``unit\\sub-unit\\person\\identity``) and approvals are always
|
||
addressed to an identity, never to a bare person.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import logging
|
||
from dataclasses import dataclass
|
||
from datetime import datetime
|
||
from typing import Any
|
||
|
||
from sqlalchemy import ColumnElement, func, or_, select
|
||
from sqlalchemy.orm import Session
|
||
|
||
from .. import models
|
||
from ..config import settings
|
||
|
||
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, identity_name: str) -> str:
|
||
"""Compose an O2OA style distinguished name.
|
||
|
||
DN 落在 ``varchar(512)`` 里,而它是由部门路径 + 姓名 + 身份名拼出来的,三段各自
|
||
都没超列宽时拼起来照样可能超;这里做最后一道闸门,宁可裁尾巴也不能让写库报错。
|
||
"""
|
||
parts = [p for p in [unit_path_, person_name, identity_name] if p]
|
||
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:
|
||
distinguished_name: str
|
||
person: str
|
||
person_name: str
|
||
unit: str
|
||
unit_name: str
|
||
|
||
@property
|
||
def name(self) -> str:
|
||
return identity_display_name(self.distinguished_name)
|
||
|
||
|
||
def default_identity(db: Session, person_id: int | str) -> models.Identity | None:
|
||
rows = db.execute(
|
||
select(models.Identity)
|
||
.where(models.Identity.person_id == models.as_id(person_id))
|
||
.order_by(models.Identity.is_default.desc(), models.Identity.id)
|
||
).scalars().all()
|
||
return rows[0] if rows else None
|
||
|
||
|
||
def person_identities(db: Session, person_id: int | str) -> list[models.Identity]:
|
||
return list(
|
||
db.execute(
|
||
select(models.Identity)
|
||
.where(models.Identity.person_id == models.as_id(person_id))
|
||
.order_by(models.Identity.is_default.desc(), models.Identity.id)
|
||
).scalars().all()
|
||
)
|
||
|
||
|
||
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]:
|
||
"""Expand a mixed list of distinguished names / person names / unit paths /
|
||
role names / group names into concrete identity distinguished names.
|
||
|
||
Supported selector shapes (mirrors the O2OA ``values`` payload)::
|
||
|
||
{"type": "identity", "data": ["<dn>", ...]}
|
||
{"type": "person", "data": ["<account|name>", ...]}
|
||
{"type": "unit", "data": ["<unit path>", ...], "containsSub": true}
|
||
{"type": "role", "data": ["<role name>", ...]}
|
||
{"type": "group", "data": ["<group name>", ...]}
|
||
"""
|
||
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 = str(value or "").strip().rstrip("\\")
|
||
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()
|
||
)
|
||
|
||
|
||
def _expand_identity(db: Session, value: str) -> list[str] | None:
|
||
"""按精确 DN 取一个身份;这不是一个 DN 就回 ``None``。"""
|
||
identity = db.execute(
|
||
select(models.Identity).where(models.Identity.distinguished_name == value)
|
||
).scalar_one_or_none()
|
||
return [identity.distinguished_name] if identity else None
|
||
|
||
|
||
def _expand_person(db: Session, value: str) -> list[str] | None:
|
||
"""按账号或姓名取在职人员的身份;库里没有这个人回 ``None``。
|
||
|
||
有账号但一个身份都挂不上(部门被删干净之类)回空表——那属于「人还在、派不出活」,
|
||
和「根本没有这个人」要分开报,前者是配置该修,后者多半是写错了对象类型。
|
||
"""
|
||
persons = db.execute(
|
||
select(models.User).where(
|
||
or_(models.User.account == value, models.User.display_name == value),
|
||
models.User.status == models.UserStatus.ACTIVE,
|
||
)
|
||
).scalars().all()
|
||
if not persons:
|
||
return None
|
||
out: list[str] = []
|
||
for person in persons:
|
||
out.extend(i.distinguished_name for i in person_identities(db, person.id))
|
||
return out
|
||
|
||
|
||
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)
|
||
|
||
|
||
def _expand_role(db: Session, value: str) -> list[str] | None:
|
||
"""按岗位角色名取成员;``None`` 是没有这个角色,空表是有这个角色但眼下没在职成员。"""
|
||
role = db.execute(select(models.Role).where(models.Role.name == value)).scalar_one_or_none()
|
||
if role is None:
|
||
return None
|
||
return live_identities(db, resolve_identity_names(db, list(role.list_auth or [])))
|
||
|
||
|
||
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 存的是 DN 字符串,同样得过一遍在职校验
|
||
members = live_identities(db, [str(v) for v in group.list_identity or []])
|
||
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
|
||
|
||
|
||
#: 声明类型 -> 解析函数。``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]:
|
||
"""按配置声明的类型解析一个选择器,返回 ``(身份 DN 清单, 这类对象是否存在)``。
|
||
|
||
两种「解析不出人」必须分开:对象根本不存在(多半是类型写错,可以退回通用口径再试),
|
||
和对象在但眼下派不出人(角色空着、部门没直属成员),后者要如实报出去,
|
||
不能拿同名的另一类对象顶上。未知类型回 ``([], 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]
|
||
|
||
|
||
def selector_kind_of(db: Session, value: str) -> str:
|
||
"""这个名字实际存在于哪一类对象里(``身份`` / ``人员`` / ``部门`` / ``岗位角色`` / ``分组``)。
|
||
|
||
只给设计器预览用:配置声明的那一类解析不到时,一眼看出是名字写错了还是来源类型选错了,
|
||
而不是让「解析不到人」变成一条没头没尾的红字。
|
||
"""
|
||
text = str(value or "").strip()
|
||
if not text:
|
||
return ""
|
||
if db.execute(select(models.Identity.id).where(models.Identity.distinguished_name == text)).first():
|
||
return "身份"
|
||
if db.execute(
|
||
select(models.User.id).where(
|
||
or_(models.User.account == text, models.User.display_name == text),
|
||
models.User.status == models.UserStatus.ACTIVE,
|
||
)
|
||
).first():
|
||
return "人员"
|
||
if _find_units(db, text):
|
||
return "部门"
|
||
if db.execute(select(models.Role.id).where(models.Role.name == text)).first():
|
||
return "岗位角色"
|
||
if db.execute(select(models.Group.id).where(models.Group.name == text)).first():
|
||
return "分组"
|
||
return ""
|
||
|
||
|
||
def selector_kind_conflict(db: Session, value: str) -> str:
|
||
"""这个名字同时命中的另一类对象(``部门`` / ``岗位角色`` / ``分组``),没有重名回空串。
|
||
|
||
只给设计器预览当提醒用:重名本身是合法的组织架构,但解析口径必须让人看得见。
|
||
"""
|
||
text = str(value or "").strip()
|
||
if not text:
|
||
return ""
|
||
has_unit = bool(_find_units(db, text))
|
||
has_role = bool(
|
||
db.execute(select(models.Role.id).where(models.Role.name == text)).first()
|
||
)
|
||
has_group = bool(
|
||
db.execute(select(models.Group.id).where(models.Group.name == text)).first()
|
||
)
|
||
if has_unit and has_role:
|
||
return "部门与岗位角色"
|
||
if has_unit and has_group:
|
||
return "部门与分组"
|
||
if has_role and has_group:
|
||
return "岗位角色与分组"
|
||
return ""
|
||
|
||
|
||
def _expand(db: Session, value: str) -> list[str]:
|
||
#: 没声明类型时的通用兜底口径,优先级保持原样:DN -> 人员 -> 部门 -> 角色 -> 分组。
|
||
#: 部门那一档只看直属成员(与加这个功能之前一字不差),配置要含子部门请声明 ``type=unit``。
|
||
#: 配置里写清了类型的选择器请走 :func:`expand_as`,别再依赖这个顺序。
|
||
for expand in (
|
||
lambda: _expand_identity(db, value),
|
||
lambda: _expand_person(db, value),
|
||
lambda: _expand_unit(db, value, contains_sub=False),
|
||
lambda: _expand_role(db, value),
|
||
lambda: _expand_group(db, value),
|
||
):
|
||
hits = expand()
|
||
if hits:
|
||
return [str(dn) for dn in hits if dn]
|
||
|
||
# unknown -> keep as-is so manual overrides still work
|
||
return [value]
|
||
|
||
|
||
def identities_for_unit(db: Session, unit_ids: list[int], contains_sub: bool = True) -> list[str]:
|
||
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)
|
||
rows = db.execute(
|
||
select(models.Identity).where(models.Identity.unit_id.in_(target or [-1]))
|
||
).scalars().all()
|
||
return [r.distinguished_name for r in rows]
|
||
|
||
|
||
def ref_for(db: Session, distinguished_name: str) -> IdentityRef:
|
||
identity = db.execute(
|
||
select(models.Identity).where(models.Identity.distinguished_name == distinguished_name)
|
||
).scalar_one_or_none()
|
||
if identity:
|
||
return IdentityRef(
|
||
distinguished_name=identity.distinguished_name,
|
||
person=str(identity.person_id),
|
||
person_name=identity.person_name,
|
||
unit=identity.unit_path or identity.unit_name,
|
||
unit_name=identity.unit_name,
|
||
)
|
||
return IdentityRef(
|
||
distinguished_name=distinguished_name,
|
||
person="",
|
||
person_name=identity_display_name(distinguished_name),
|
||
unit=identity_unit(distinguished_name),
|
||
unit_name=identity_unit(distinguished_name).split("\\")[-1],
|
||
)
|
||
|
||
|
||
# --------------------------------------------------------------------------
|
||
# 审批人来源:岗位角色 / 分组 / 部门
|
||
# --------------------------------------------------------------------------
|
||
|
||
|
||
def live_identities(db: Session, distinguished_names: list[str]) -> list[str]:
|
||
"""只保留还能对上「在职人员」的身份 DN,顺序不变。
|
||
|
||
岗位角色与分组的成员是按 DN 字符串存的。人从统一身份里被清掉之后,字符串还留在
|
||
配置里,照原样发给引擎就是把待办挂到一个已经不存在的人身上:没有待办、没有报错,
|
||
流程静静卡在环节上。设计器里也宁可看见「解析不到人」,不要一个幽灵审批人。
|
||
"""
|
||
wanted = [str(dn) for dn in distinguished_names if dn]
|
||
if not wanted:
|
||
return []
|
||
rows = db.execute(
|
||
select(models.Identity.distinguished_name, models.User.status)
|
||
.join(models.User, models.User.id == models.Identity.person_id)
|
||
.where(models.Identity.distinguished_name.in_(wanted))
|
||
).all()
|
||
alive = {dn for dn, status in rows if int(status or 0) == int(models.UserStatus.ACTIVE)}
|
||
return [dn for dn in wanted if dn in alive]
|
||
|
||
|
||
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
|
||
if db.execute(
|
||
select(models.Identity.id).where(models.Identity.distinguished_name == value)
|
||
).first():
|
||
return True
|
||
# 停用人员与 _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())
|
||
|
||
|
||
def split_selectors(db: Session, values: list[str]) -> tuple[list[str], list[str]]:
|
||
"""Expand selector names into identity DNs, keeping the unrecognised ones aside."""
|
||
resolved: list[str] = []
|
||
unknown: list[str] = []
|
||
for raw in values:
|
||
value = str(raw or "").strip()
|
||
if not value:
|
||
continue
|
||
if not selector_exists(db, value):
|
||
unknown.append(value)
|
||
continue
|
||
for dn in _expand(db, value):
|
||
if dn and dn not in resolved:
|
||
resolved.append(dn)
|
||
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 (identity DNs, 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 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, distinguished_names: list[str]) -> list[dict]:
|
||
"""Identity DNs -> 可直接展示的轻量成员。"""
|
||
rows: list[dict] = []
|
||
for dn in distinguished_names:
|
||
ref = ref_for(db, dn)
|
||
rows.append(
|
||
{
|
||
"distinguished_name": ref.distinguished_name,
|
||
"name": ref.name,
|
||
"person_name": ref.person_name,
|
||
"unit_name": ref.unit_name,
|
||
}
|
||
)
|
||
return rows
|
||
|
||
|
||
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 [],
|
||
}
|
||
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:
|
||
"""设计器选审批人用的岗位角色 / 分组 / 部门清单,各自带解析后的成员。"""
|
||
roles: list[dict] = []
|
||
for row in db.execute(select(models.Role).order_by(models.Role.name)).scalars().all():
|
||
members, unknown = split_selectors(db, list(row.list_auth or []))
|
||
roles.append(
|
||
{
|
||
"name": row.name,
|
||
"description": row.description,
|
||
"unit": row.unit,
|
||
"members": member_briefs(db, members),
|
||
"unknown": unknown,
|
||
}
|
||
)
|
||
groups: list[dict] = []
|
||
for row in db.execute(select(models.Group).order_by(models.Group.name)).scalars().all():
|
||
members, unknown = split_selectors(
|
||
db, [str(v) for v in list(row.list_identity or []) + list(row.list_person or [])]
|
||
)
|
||
groups.append(
|
||
{
|
||
"name": row.name,
|
||
"description": row.description,
|
||
"unit": row.unit,
|
||
"members": member_briefs(db, members),
|
||
"unknown": unknown,
|
||
}
|
||
)
|
||
counts: dict[str, int] = dict(
|
||
db.execute(
|
||
select(models.Identity.unit_id, func.count(models.Identity.id)).group_by(
|
||
models.Identity.unit_id
|
||
)
|
||
).all()
|
||
)
|
||
managers = {row.id: row for row in db.execute(select(models.User)).scalars().all()}
|
||
units: list[dict] = []
|
||
for row in db.execute(select(models.Unit).order_by(models.Unit.path)).scalars().all():
|
||
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, distinguished_name: str) -> models.User | None:
|
||
"""身份 DN -> 人员;身份表查不到就按 DN 里的姓名/账号回退匹配。"""
|
||
dn = str(distinguished_name or "").strip()
|
||
if not dn:
|
||
return None
|
||
identity = db.execute(
|
||
select(models.Identity).where(models.Identity.distinguished_name == dn)
|
||
).scalar_one_or_none()
|
||
if identity:
|
||
return db.get(models.User, identity.person_id)
|
||
person_part = identity_display_name(dn)
|
||
rows = db.execute(
|
||
select(models.User).where(
|
||
or_(models.User.account == person_part, models.User.display_name == person_part),
|
||
models.User.status == models.UserStatus.ACTIVE,
|
||
)
|
||
).scalars().all()
|
||
return rows[0] if rows else None
|
||
|
||
|
||
def unit_by_identity(db: Session, distinguished_name: str) -> models.Unit | None:
|
||
"""身份 DN -> 所在部门;身份表没记录时按 DN 前缀(部门路径)反查。"""
|
||
dn = str(distinguished_name or "").strip()
|
||
if not dn:
|
||
return None
|
||
identity = db.execute(
|
||
select(models.Identity).where(models.Identity.distinguished_name == dn)
|
||
).scalar_one_or_none()
|
||
if identity and identity.unit_id:
|
||
unit = db.get(models.Unit, identity.unit_id)
|
||
if unit:
|
||
return unit
|
||
unit_part = identity_unit(dn)
|
||
if not unit_part:
|
||
return None
|
||
rows = db.execute(
|
||
select(models.Unit).where(
|
||
or_(models.Unit.path == f"{unit_part}\\", models.Unit.path == unit_part)
|
||
)
|
||
).scalars().all()
|
||
return rows[0] if rows else None
|
||
|
||
|
||
def identity_of_person(db: Session, person: models.User | None) -> str:
|
||
"""人员 -> 默认身份 DN(没有身份记录时按部门路径拼一个,保证任务发得出去)。"""
|
||
if person is None:
|
||
return ""
|
||
identity = default_identity(db, person.id)
|
||
if identity:
|
||
return identity.distinguished_name
|
||
return dn_for(person.organization_path, person.display_name, person.account)
|
||
|
||
|
||
#: 设计器下拉里的中文名;后端只负责解析,展示文案前端另有一份 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 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 {}
|
||
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)
|
||
# 认不出的值原样保留,手工写进去的历史身份串仍然能用
|
||
identities.extend(unknown)
|
||
elif kind == "creator":
|
||
identities.append(context_creator_identity(context))
|
||
elif kind == "prev":
|
||
identities.extend(context_prev_identities(context))
|
||
elif kind == "prevunit":
|
||
# 「上一环节处理人所在部门」要展开成部门里的人。直接把部门路径当身份用,
|
||
# 任务会挂在一个既查不到人员也查不到身份的行上,谁的待办里都不会出现,
|
||
# 流程等于悄悄卡死;口径与「部门」来源一致,取该部门直属成员。
|
||
for path in {identity_unit(p) for p in context_prev_identities(context)}:
|
||
for unit in _find_units(db, path):
|
||
identities.extend(identities_for_unit(db, [unit.id], 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
|
||
)
|