695 lines
31 KiB
Python
695 lines
31 KiB
Python
"""组织架构与系统账号。"""
|
||
|
||
from __future__ import annotations
|
||
|
||
from datetime import datetime
|
||
from typing import Any
|
||
|
||
from fastapi import APIRouter, Query
|
||
from pydantic import BaseModel, Field
|
||
from sqlalchemy import delete, func, or_, select
|
||
|
||
from ..deps import DbSession, PrincipalOf
|
||
from ..envelope import conflict, forbidden, not_found, ok, page
|
||
from ..models import (
|
||
Account,
|
||
AccountIdentity,
|
||
AccountSource,
|
||
OrgUnit,
|
||
PermAccountRole,
|
||
PermRole,
|
||
Position,
|
||
Status,
|
||
)
|
||
from ..security import hash_password, password_policy_error
|
||
from ..service.org_sync import sync_all, sync_changes
|
||
|
||
router = APIRouter(prefix="/org", tags=["org"])
|
||
|
||
|
||
class UnitBody(BaseModel):
|
||
name: str = Field(min_length=1, max_length=255)
|
||
code: str = ""
|
||
shortName: str = ""
|
||
parentId: int | None = None
|
||
managerId: int | None = None
|
||
orderNumber: int = 0
|
||
status: int = Status.ACTIVE
|
||
remark: str = ""
|
||
|
||
|
||
class PositionBody(BaseModel):
|
||
code: str = Field(min_length=1, max_length=64)
|
||
name: str = Field(min_length=1, max_length=128)
|
||
rank: int = 100
|
||
orderNumber: int = 0
|
||
enabled: bool = True
|
||
remark: str = ""
|
||
|
||
|
||
class AccountBody(BaseModel):
|
||
account: str = Field(min_length=1, max_length=190)
|
||
displayName: str = ""
|
||
password: str = ""
|
||
empCode: str = ""
|
||
telephone: str = ""
|
||
email: str = ""
|
||
orgUnitId: int | None = None
|
||
positionId: int | None = None
|
||
leaderId: int | None = None
|
||
status: int = Status.ACTIVE
|
||
#: None 表示"这次不动它"。编辑弹窗少传一个字段就把超管降成普通人,是没人能接受的
|
||
isSystemAdmin: bool | None = None
|
||
roleIds: list[int] = Field(default_factory=list)
|
||
workLocation: str = ""
|
||
remark: str = ""
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 组织
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
@router.get("/units")
|
||
def unit_tree(db: DbSession, keyword: str = "", includeDisabled: bool = False) -> dict[str, Any]:
|
||
statement = select(OrgUnit).where(OrgUnit.is_deleted.is_(False))
|
||
if keyword:
|
||
statement = statement.where(or_(OrgUnit.name.like(f"%{keyword}%"), OrgUnit.code.like(f"%{keyword}%")))
|
||
if not includeDisabled:
|
||
statement = statement.where(OrgUnit.status == Status.ACTIVE)
|
||
units = db.execute(statement.order_by(OrgUnit.order_number, OrgUnit.id)).scalars().all()
|
||
|
||
manager_ids = {unit.manager_id for unit in units if unit.manager_id}
|
||
names = {}
|
||
if manager_ids:
|
||
names = dict(db.execute(
|
||
select(Account.id, Account.display_name).where(Account.id.in_(manager_ids))
|
||
).all())
|
||
counts = dict(db.execute(
|
||
select(Account.org_unit_id, func.count(Account.id)).where(Account.is_deleted.is_(False))
|
||
.group_by(Account.org_unit_id)
|
||
).all())
|
||
|
||
nodes = {
|
||
unit.id: {
|
||
"id": unit.id, "name": unit.name, "code": unit.code, "shortName": unit.short_name,
|
||
"parentId": unit.parent_id, "level": unit.level, "path": unit.path,
|
||
"status": unit.status, "statusLabel": Status.label(unit.status),
|
||
"managerId": unit.manager_id, "managerName": names.get(unit.manager_id, ""),
|
||
"orderNumber": unit.order_number, "isHub": unit.is_hub,
|
||
"userCount": counts.get(unit.id, 0), "children": [],
|
||
}
|
||
for unit in units
|
||
}
|
||
roots: list[dict[str, Any]] = []
|
||
for node in nodes.values():
|
||
parent = nodes.get(node["parentId"]) if node["parentId"] else None
|
||
(parent["children"] if parent else roots).append(node)
|
||
return ok(roots)
|
||
|
||
|
||
@router.post("/units")
|
||
def create_unit(body: UnitBody, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||
if not current.permission.can("org:unit:edit"):
|
||
raise forbidden("缺少权限:org:unit:edit")
|
||
unit = OrgUnit(
|
||
name=body.name, code=body.code, short_name=body.shortName, parent_id=body.parentId,
|
||
manager_id=body.managerId, order_number=body.orderNumber, status=body.status, remark=body.remark,
|
||
)
|
||
db.add(unit)
|
||
db.flush()
|
||
_recompute_path(db, unit)
|
||
db.commit()
|
||
return ok({"id": unit.id})
|
||
|
||
|
||
@router.put("/units/{unit_id}")
|
||
def update_unit(unit_id: int, body: UnitBody, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||
if not current.permission.can("org:unit:edit"):
|
||
raise forbidden("缺少权限:org:unit:edit")
|
||
unit = db.get(OrgUnit, unit_id)
|
||
if unit is None or unit.is_deleted:
|
||
raise not_found("部门不存在")
|
||
# Hub 接管的部门:名称/编码/状态/上级由同步说了算,本地只让改负责人、简称与排序
|
||
if not unit.is_hub:
|
||
unit.name = body.name
|
||
unit.code = body.code
|
||
unit.status = body.status
|
||
unit.parent_id = body.parentId
|
||
unit.short_name = body.shortName
|
||
unit.manager_id = body.managerId
|
||
unit.order_number = body.orderNumber
|
||
unit.remark = body.remark
|
||
_recompute_path(db, unit)
|
||
db.commit()
|
||
return ok({"id": unit.id})
|
||
|
||
|
||
@router.delete("/units/{unit_id}")
|
||
def delete_unit(unit_id: int, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||
if not current.permission.can("org:unit:edit"):
|
||
raise forbidden("缺少权限:org:unit:edit")
|
||
unit = db.get(OrgUnit, unit_id)
|
||
if unit is None or unit.is_deleted:
|
||
raise not_found("部门不存在")
|
||
if unit.is_hub:
|
||
raise conflict("hub_managed", "该部门由统一身份接管,请到统一身份平台调整")
|
||
if unit.children:
|
||
raise conflict("has_children", "请先删除下级部门")
|
||
headcount = db.execute(
|
||
select(func.count(Account.id)).where(Account.org_unit_id == unit_id, Account.is_deleted.is_(False))
|
||
).scalar() or 0
|
||
if headcount:
|
||
raise conflict("has_accounts", f"部门下还有 {headcount} 个账号")
|
||
unit.is_deleted = True
|
||
db.commit()
|
||
return ok({"deleted": True})
|
||
|
||
|
||
def _recompute_path(db, unit: OrgUnit) -> None:
|
||
"""重算本节点及以下所有节点的路径与层级。"""
|
||
units = {item.id: item for item in db.execute(select(OrgUnit).where(OrgUnit.is_deleted.is_(False))).scalars().all()}
|
||
|
||
def path_of(target: OrgUnit, depth: int = 0) -> tuple[str, int]:
|
||
if depth > 32:
|
||
return f"/{target.id}/", 1
|
||
parent = units.get(target.parent_id) if target.parent_id else None
|
||
if parent is None or parent.id == target.id:
|
||
return f"/{target.id}/", 1
|
||
parent_path, parent_level = path_of(parent, depth + 1)
|
||
return f"{parent_path}{target.id}/", parent_level + 1
|
||
|
||
affected = db.execute(
|
||
select(OrgUnit).where(OrgUnit.id.in_(list(units.keys())))
|
||
).scalars().all()
|
||
for item in affected:
|
||
item.path, item.level = path_of(item)
|
||
db.flush()
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 岗位
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
@router.get("/positions")
|
||
def list_positions(db: DbSession) -> dict[str, Any]:
|
||
rows = db.execute(select(Position).where(Position.is_deleted.is_(False))
|
||
.order_by(Position.rank, Position.order_number, Position.id)).scalars().all()
|
||
return ok([{"id": row.id, "code": row.code, "name": row.name, "rank": row.rank,
|
||
"orderNumber": row.order_number, "enabled": row.enabled, "remark": row.remark} for row in rows])
|
||
|
||
|
||
@router.post("/positions")
|
||
def create_position(body: PositionBody, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||
if not current.permission.can("org:position:edit"):
|
||
raise forbidden("缺少权限:org:position:edit")
|
||
if db.execute(select(Position).where(Position.code == body.code)).scalars().first():
|
||
raise conflict("duplicated_code", "岗位编码已存在")
|
||
row = Position(code=body.code, name=body.name, rank=body.rank, order_number=body.orderNumber,
|
||
enabled=body.enabled, remark=body.remark)
|
||
db.add(row)
|
||
db.commit()
|
||
return ok({"id": row.id})
|
||
|
||
|
||
@router.put("/positions/{position_id}")
|
||
def update_position(position_id: int, body: PositionBody, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||
if not current.permission.can("org:position:edit"):
|
||
raise forbidden("缺少权限:org:position:edit")
|
||
row = db.get(Position, position_id)
|
||
if row is None or row.is_deleted:
|
||
raise not_found("岗位不存在")
|
||
row.name, row.rank, row.order_number, row.enabled, row.remark = (
|
||
body.name, body.rank, body.orderNumber, body.enabled, body.remark)
|
||
db.commit()
|
||
return ok({"id": row.id})
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 账号
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
@router.get("/accounts")
|
||
def list_accounts(
|
||
db: DbSession,
|
||
current: PrincipalOf,
|
||
keyword: str = "",
|
||
orgUnitId: int | None = None,
|
||
includeChildren: bool = True,
|
||
positionId: int | None = None,
|
||
roleId: int | None = None,
|
||
status: int | None = None,
|
||
source: str = "",
|
||
unassigned: bool = False,
|
||
pageNo: int = Query(1, ge=1),
|
||
pageSize: int = Query(20, ge=1, le=200),
|
||
) -> dict[str, Any]:
|
||
if not current.permission.can_any(("org:person:view", "org:person:edit")):
|
||
raise forbidden("缺少权限:org:person:view")
|
||
|
||
statement = _account_filters(
|
||
db, keyword=keyword, orgUnitId=orgUnitId, includeChildren=includeChildren,
|
||
positionId=positionId, roleId=roleId, status=status, source=source, unassigned=unassigned)
|
||
total = db.execute(select(func.count()).select_from(statement.subquery())).scalar() or 0
|
||
rows = db.execute(statement.order_by(Account.org_unit_id, Account.id)
|
||
.offset((pageNo - 1) * pageSize).limit(pageSize)).scalars().all()
|
||
|
||
roles_by_account = _roles_by_account(db, [row.id for row in rows])
|
||
positions = dict(db.execute(select(Position.id, Position.name)).all())
|
||
items = [_account_view(row, roles_by_account.get(row.id, []), positions) for row in rows]
|
||
return page(items, total, pageNo, pageSize)
|
||
|
||
|
||
def _account_filters(db, *, cols: tuple = (Account,), keyword: str = "",
|
||
orgUnitId: int | None = None,
|
||
includeChildren: bool = True, positionId: int | None = None,
|
||
roleId: int | None = None, status: int | None = None,
|
||
source: str = "", unassigned: bool = False):
|
||
"""账号列表的筛选口径。
|
||
|
||
抽出来是因为「批量分配角色」要能按"当前筛选结果"圈人:列表里看到 98 个未分配,
|
||
批量就该作用在这 98 个人身上,两处各写一遍筛选迟早会算出两个数。
|
||
"""
|
||
statement = select(*cols).where(Account.is_deleted.is_(False))
|
||
if keyword:
|
||
like = f"%{keyword}%"
|
||
statement = statement.where(or_(Account.account.like(like), Account.display_name.like(like),
|
||
Account.emp_code.like(like), Account.telephone.like(like)))
|
||
if orgUnitId:
|
||
from ..service.data_scope import descendant_unit_ids
|
||
|
||
ids = descendant_unit_ids(db, [orgUnitId]) if includeChildren else [orgUnitId]
|
||
# 兼岗的人也要出现在部门下面,所以按身份表判定,而不是只看主部门
|
||
statement = statement.where(
|
||
Account.id.in_(select(AccountIdentity.account_id).where(AccountIdentity.org_unit_id.in_(ids)))
|
||
)
|
||
if positionId:
|
||
statement = statement.where(Account.position_id == positionId)
|
||
if roleId:
|
||
statement = statement.where(Account.id.in_(
|
||
select(PermAccountRole.account_id).where(PermAccountRole.role_id == roleId)))
|
||
if unassigned:
|
||
# 同步刚跑完时最容易用:一整批人挂进来、一个角色都没有,得先把他们挑出来
|
||
statement = statement.where(
|
||
~Account.id.in_(select(PermAccountRole.account_id).join(
|
||
PermRole, PermRole.id == PermAccountRole.role_id).where(
|
||
PermRole.is_deleted.is_(False))))
|
||
if status is not None:
|
||
statement = statement.where(Account.status == status)
|
||
if source:
|
||
statement = statement.where(Account.source == source)
|
||
return statement
|
||
|
||
|
||
def _roles_by_account(db, account_ids: list[int]) -> dict[int, list[dict[str, Any]]]:
|
||
if not account_ids:
|
||
return {}
|
||
rows = db.execute(
|
||
select(PermAccountRole.account_id, PermRole.id, PermRole.name, PermRole.code)
|
||
.join(PermRole, PermRole.id == PermAccountRole.role_id)
|
||
.where(PermAccountRole.account_id.in_(account_ids), PermRole.is_deleted.is_(False))
|
||
).all()
|
||
out: dict[int, list[dict[str, Any]]] = {}
|
||
for account_id, role_id, role_name, role_code in rows:
|
||
out.setdefault(account_id, []).append({"id": role_id, "name": role_name, "code": role_code})
|
||
return out
|
||
|
||
|
||
def _account_view(row: Account, roles: list[dict[str, Any]], positions: dict[int, str]) -> dict[str, Any]:
|
||
return {
|
||
"id": row.id, "account": row.account, "displayName": row.display_name or row.account,
|
||
"empCode": row.emp_code, "email": row.email, "telephone": row.telephone,
|
||
"orgUnitId": row.org_unit_id, "orgUnitName": row.org_unit_name,
|
||
"positionId": row.position_id, "positionName": positions.get(row.position_id or 0, ""),
|
||
"leaderId": row.leader_id, "status": row.status, "statusLabel": Status.label(row.status),
|
||
"source": row.source, "sourceLabel": AccountSource.label(row.source),
|
||
"isSystemAdmin": row.is_system_admin, "roles": roles,
|
||
"workLocation": row.work_location, "remark": row.remark,
|
||
"lastLoginAt": row.last_login_at.isoformat(sep=" ", timespec="seconds") if row.last_login_at else "",
|
||
"canLoginLocally": bool(row.password_hash),
|
||
}
|
||
|
||
|
||
@router.get("/accounts/options")
|
||
def account_options(db: DbSession, current: PrincipalOf, keyword: str = "") -> dict[str, Any]:
|
||
"""人员选择器用的精简列表:只要 id + 姓名,不分页。
|
||
|
||
之前三处选择器都拿 pageSize=300 去请求分页接口,一是撞 le=200 直接 422,
|
||
二是人多的时候会静默截断,选不到靠后的人。必须在 /accounts/{account_id}
|
||
之前声明,否则 "options" 会被当成 account_id。
|
||
"""
|
||
allowed = (
|
||
"org:person:view", "org:person:edit",
|
||
"workbench:delegates", "system:datapermission:edit", "approval:flow:edit",
|
||
)
|
||
if not current.permission.can_any(allowed):
|
||
raise forbidden("缺少权限:org:person:view")
|
||
# org_unit_name 是关系推导出来的属性,不是列,所以这里显式 join 出来
|
||
statement = (
|
||
select(Account.id, Account.account, Account.display_name,
|
||
OrgUnit.name.label("org_unit_name"))
|
||
.outerjoin(OrgUnit, OrgUnit.id == Account.org_unit_id)
|
||
.where(Account.is_deleted.is_(False), Account.status == Status.ACTIVE)
|
||
.order_by(Account.org_unit_id, Account.id)
|
||
.limit(2000)
|
||
)
|
||
if keyword:
|
||
like = f"%{keyword}%"
|
||
statement = statement.where(or_(Account.account.like(like), Account.display_name.like(like)))
|
||
return ok([
|
||
{"id": row.id, "account": row.account,
|
||
"displayName": row.display_name or row.account, "orgUnitName": row.org_unit_name}
|
||
for row in db.execute(statement).all()
|
||
])
|
||
|
||
|
||
@router.get("/accounts/role-options")
|
||
def account_role_options(db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||
"""给人挂角色时要的候选角色清单。
|
||
|
||
单独开一条而不复用 ``/system/roles``:能管人(``org:person:view``)就该看得见能给人
|
||
挂哪几个角色,这是配人的下限;看得见的应该是"这个角色叫什么、有多少人挂着",
|
||
至于角色里具体勾了哪些权限点,那才归 ``system:role:view`` 管。
|
||
顺手把成员数带上,界面能一眼看出哪些角色还没人用。
|
||
"""
|
||
if not current.permission.can_any(("org:person:view", "org:person:edit")):
|
||
raise forbidden("缺少权限:org:person:view")
|
||
rows = db.execute(select(PermRole).where(PermRole.is_deleted.is_(False))
|
||
.order_by(PermRole.order_number, PermRole.id)).scalars().all()
|
||
counts = dict(db.execute(
|
||
select(PermAccountRole.role_id, func.count())
|
||
.where(PermAccountRole.role_id.in_([row.id for row in rows] or [0]))
|
||
.group_by(PermAccountRole.role_id)).all()) if rows else {}
|
||
return ok([{
|
||
"id": row.id, "code": row.code, "name": row.name, "builtin": bool(row.builtin),
|
||
# 停用的角色也带回来,但带着标记:界面据此只让人摘、不让人新挂
|
||
"enabled": bool(row.enabled), "remark": row.remark,
|
||
"memberCount": counts.get(row.id, 0),
|
||
} for row in rows])
|
||
|
||
|
||
@router.get("/accounts/{account_id}")
|
||
def get_account(account_id: int, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||
if not current.permission.can_any(("org:person:view", "org:person:edit")):
|
||
raise forbidden("缺少权限:org:person:view")
|
||
row = db.get(Account, account_id)
|
||
if row is None or row.is_deleted:
|
||
raise not_found("账号不存在")
|
||
roles = _roles_by_account(db, [account_id]).get(account_id, [])
|
||
positions = dict(db.execute(select(Position.id, Position.name)).all())
|
||
identities = db.execute(
|
||
select(AccountIdentity, OrgUnit.name, Position.name)
|
||
.join(OrgUnit, OrgUnit.id == AccountIdentity.org_unit_id)
|
||
.outerjoin(Position, Position.id == AccountIdentity.position_id)
|
||
.where(AccountIdentity.account_id == account_id)
|
||
).all()
|
||
data = _account_view(row, roles, positions)
|
||
data["identities"] = [
|
||
{"id": identity.id, "orgUnitId": identity.org_unit_id, "orgUnitName": org_name,
|
||
"positionName": position_name or "", "isDefault": identity.is_default, "kind": identity.kind}
|
||
for identity, org_name, position_name in identities
|
||
]
|
||
return ok(data)
|
||
|
||
|
||
@router.post("/accounts")
|
||
def create_account(body: AccountBody, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||
if not current.permission.can("org:person:edit"):
|
||
raise forbidden("缺少权限:org:person:edit")
|
||
if db.execute(select(Account).where(Account.account == body.account,
|
||
Account.is_deleted.is_(False))).scalars().first():
|
||
raise conflict("duplicated_account", "登录账号已存在")
|
||
password = body.password or ""
|
||
if password:
|
||
problem = password_policy_error(password)
|
||
if problem:
|
||
raise forbidden(problem)
|
||
row = Account(
|
||
account=body.account, display_name=body.displayName or body.account,
|
||
password_hash=hash_password(password) if password else "",
|
||
emp_code=body.empCode, telephone=body.telephone, email=body.email,
|
||
org_unit_id=body.orgUnitId, position_id=body.positionId, leader_id=body.leaderId,
|
||
status=body.status, is_system_admin=bool(body.isSystemAdmin), work_location=body.workLocation,
|
||
remark=body.remark, source=AccountSource.LOCAL,
|
||
)
|
||
db.add(row)
|
||
db.flush()
|
||
_sync_roles(db, row.id, body.roleIds)
|
||
_sync_identities(db, row.id, body.orgUnitId)
|
||
db.commit()
|
||
return ok({"id": row.id, "hasPassword": bool(password)})
|
||
|
||
|
||
@router.put("/accounts/{account_id}")
|
||
def update_account(account_id: int, body: AccountBody, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||
if not current.permission.can("org:person:edit"):
|
||
raise forbidden("缺少权限:org:person:edit")
|
||
row = db.get(Account, account_id)
|
||
if row is None or row.is_deleted:
|
||
raise not_found("账号不存在")
|
||
if row.is_hub and (body.orgUnitId or 0) not in (0, row.org_unit_id):
|
||
raise conflict("hub_managed", "统一身份账号的部门由同步维护,本地不能改")
|
||
if body.isSystemAdmin is not None and bool(body.isSystemAdmin) != bool(row.is_system_admin):
|
||
if not current.permission.is_system_admin:
|
||
raise forbidden("只有系统管理员能授予或收回「系统管理员」标记")
|
||
if not body.isSystemAdmin and _remaining_system_admins(db, exclude_id=row.id) == 0:
|
||
raise conflict("last_admin", "至少要保留一个系统管理员,否则没人再进得了系统管理")
|
||
if body.password:
|
||
problem = password_policy_error(body.password)
|
||
if problem:
|
||
raise forbidden(problem)
|
||
row.password_hash = hash_password(body.password)
|
||
row.password_updated_at = datetime.now()
|
||
row.display_name = body.displayName or row.display_name
|
||
row.emp_code, row.telephone, row.email = body.empCode, body.telephone, body.email
|
||
row.position_id, row.leader_id = body.positionId, body.leaderId
|
||
if body.isSystemAdmin is not None:
|
||
row.is_system_admin = bool(body.isSystemAdmin)
|
||
row.work_location, row.remark = body.workLocation, body.remark
|
||
if not row.is_hub:
|
||
row.org_unit_id = body.orgUnitId
|
||
row.status = body.status
|
||
_sync_roles(db, row.id, body.roleIds)
|
||
_sync_identities(db, row.id, row.org_unit_id)
|
||
db.commit()
|
||
return ok({"id": row.id})
|
||
|
||
|
||
class AccountRoleBody(BaseModel):
|
||
roleIds: list[int] = Field(default_factory=list)
|
||
|
||
|
||
@router.put("/accounts/{account_id}/roles")
|
||
def set_account_roles(account_id: int, body: AccountRoleBody, db: DbSession,
|
||
current: PrincipalOf) -> dict[str, Any]:
|
||
"""只换角色,别动档案。
|
||
|
||
统一身份同步过来的人,姓名部门口令都归 Hub,本地要给他开权限,动的本来就只有角色;
|
||
为这件事把整份档案表单填一遍既难用,也很容易顺手把 Hub 管的字段带歪。
|
||
"""
|
||
if not current.permission.can("org:person:edit"):
|
||
raise forbidden("缺少权限:org:person:edit")
|
||
row = db.get(Account, account_id)
|
||
if row is None or row.is_deleted:
|
||
raise not_found("账号不存在")
|
||
|
||
wanted = list(dict.fromkeys(int(item) for item in body.roleIds or []))
|
||
existing = set(db.execute(select(PermAccountRole.role_id).where(
|
||
PermAccountRole.account_id == row.id)).scalars().all())
|
||
if wanted:
|
||
found = {item.id: item for item in db.execute(
|
||
select(PermRole).where(PermRole.id.in_(wanted),
|
||
PermRole.is_deleted.is_(False))).scalars()}
|
||
unknown = [item for item in wanted if item not in found]
|
||
if unknown:
|
||
raise conflict("unknown_role", f"角色不存在:{unknown}")
|
||
# 停用的角色不许新挂,但原本就挂着、这次只是照样留着的不算新挂
|
||
disabled = [found[item].name for item in wanted
|
||
if item not in existing and not found[item].enabled]
|
||
if disabled:
|
||
raise conflict("role_disabled", "角色已停用,先启用再分配:" + "、".join(disabled))
|
||
|
||
_sync_roles(db, row.id, wanted)
|
||
db.commit()
|
||
return ok({"id": row.id,
|
||
"roles": _roles_by_account(db, [row.id]).get(row.id, [])})
|
||
|
||
|
||
#: 一次批量最多动多少人。批量是把双刃剑:一个手滑的筛选能把全公司的角色改掉。
|
||
BATCH_LIMIT = 500
|
||
|
||
|
||
class AccountRoleTargetBody(BaseModel):
|
||
"""批量分配的目标人群之二:照抄账号列表的筛选条件圈人。"""
|
||
|
||
keyword: str = ""
|
||
orgUnitId: int | None = None
|
||
includeChildren: bool = True
|
||
positionId: int | None = None
|
||
roleId: int | None = None
|
||
status: int | None = None
|
||
source: str = ""
|
||
unassigned: bool = False
|
||
|
||
|
||
class BatchRoleBody(BaseModel):
|
||
accountIds: list[int] = Field(default_factory=list)
|
||
target: AccountRoleTargetBody | None = None
|
||
#: append=在各自原有的基础上加;remove=只摘这几个角色;replace=整份换成这些(空数组=清空)
|
||
mode: str = "append"
|
||
roleIds: list[int] = Field(default_factory=list)
|
||
|
||
|
||
@router.post("/accounts/roles/batch")
|
||
def batch_assign_roles(body: BatchRoleBody, db: DbSession,
|
||
current: PrincipalOf) -> dict[str, Any]:
|
||
"""一批人一起改角色。
|
||
|
||
统一身份一次同步进来上百人,一个个点开分配不现实:要么勾几页,要么直接按
|
||
当前筛选结果整批处理("只看未分配角色" + 追加一个角色,就是同步后的第一步)。
|
||
"""
|
||
if not current.permission.can("org:person:edit"):
|
||
raise forbidden("缺少权限:org:person:edit")
|
||
if bool(body.accountIds) == bool(body.target):
|
||
raise conflict("pick_target", "要么点名(accountIds),要么按筛选条件(target)圈人,只能选一种")
|
||
if body.mode not in ("append", "remove", "replace"):
|
||
raise conflict("invalid_mode", "分配方式只能是追加、移除或覆盖")
|
||
if body.mode in ("append", "remove") and not body.roleIds:
|
||
# 覆盖 + 空列表是"清空",那是一句有意义的话;追加和移除空列表只是客户端漏传
|
||
raise conflict("empty_roles", "要" + ("追加" if body.mode == "append" else "移除")
|
||
+ "哪几个角色?想清空就把方式换成「覆盖」并且一个都不选")
|
||
|
||
if body.target is not None:
|
||
account_ids = list(db.execute(
|
||
_account_filters(db, cols=(Account.id,), **body.target.model_dump())).scalars().all())
|
||
else:
|
||
account_ids = list(dict.fromkeys(int(item) for item in body.accountIds))
|
||
found = set(db.execute(select(Account.id).where(
|
||
Account.id.in_(account_ids), Account.is_deleted.is_(False))).scalars().all())
|
||
unknown = [item for item in account_ids if item not in found]
|
||
if unknown:
|
||
raise conflict("unknown_account", f"账号不存在:{unknown[:5]}")
|
||
if not account_ids:
|
||
raise conflict("empty_target", "这批人里一个都没有,先换个筛选条件")
|
||
if len(account_ids) > BATCH_LIMIT:
|
||
raise conflict("too_many", f"一次最多处理 {BATCH_LIMIT} 人,这次圈到 {len(account_ids)} 人")
|
||
|
||
wanted = set(int(item) for item in body.roleIds or [])
|
||
if wanted:
|
||
found_roles = {row.id: row for row in db.execute(select(PermRole).where(
|
||
PermRole.id.in_(wanted), PermRole.is_deleted.is_(False))).scalars()}
|
||
missing = [item for item in wanted if item not in found_roles]
|
||
if missing:
|
||
raise conflict("unknown_role", f"角色不存在:{missing}")
|
||
# 停用的角色不许整批新挂;移除一个停用角色是清理,照样让做
|
||
if body.mode in ("append", "replace"):
|
||
disabled = [found_roles[item].name for item in wanted if not found_roles[item].enabled]
|
||
if disabled:
|
||
raise conflict("role_disabled", "角色已停用,先启用再分配:" + "、".join(disabled))
|
||
|
||
existing: dict[int, set[int]] = {account_id: set() for account_id in account_ids}
|
||
for account_id, role_id in db.execute(select(PermAccountRole.account_id, PermAccountRole.role_id)
|
||
.where(PermAccountRole.account_id.in_(account_ids))).all():
|
||
existing.setdefault(account_id, set()).add(role_id)
|
||
|
||
to_add: dict[int, list[int]] = {}
|
||
to_remove: dict[int, list[int]] = {}
|
||
affected = 0
|
||
for account_id in account_ids:
|
||
before = existing.get(account_id, set())
|
||
if body.mode == "append":
|
||
after = before | wanted
|
||
elif body.mode == "remove":
|
||
after = before - wanted
|
||
else:
|
||
after = set(wanted)
|
||
if after == before:
|
||
continue
|
||
affected += 1
|
||
for role_id in before - after:
|
||
to_remove.setdefault(role_id, []).append(account_id)
|
||
for role_id in after - before:
|
||
to_add.setdefault(role_id, []).append(account_id)
|
||
|
||
for role_id, targets in to_remove.items():
|
||
db.execute(delete(PermAccountRole).where(
|
||
PermAccountRole.role_id == role_id, PermAccountRole.account_id.in_(targets)))
|
||
for role_id, targets in to_add.items():
|
||
db.add_all([PermAccountRole(account_id=account_id, role_id=role_id) for account_id in targets])
|
||
db.commit()
|
||
return ok({"accounts": len(account_ids), "affected": affected,
|
||
"added": sum(len(items) for items in to_add.values()),
|
||
"removed": sum(len(items) for items in to_remove.values())})
|
||
|
||
|
||
def _remaining_system_admins(db, exclude_id: int | None = None) -> int:
|
||
"""还剩几个能进系统管理的账号(``exclude_id`` 用来把正在被改的那个先摘出去)。"""
|
||
statement = select(func.count()).select_from(Account).where(
|
||
Account.is_deleted.is_(False), Account.is_system_admin.is_(True),
|
||
Account.status == Status.ACTIVE)
|
||
if exclude_id:
|
||
statement = statement.where(Account.id != exclude_id)
|
||
return db.execute(statement).scalar() or 0
|
||
|
||
|
||
def _sync_roles(db, account_id: int, role_ids: list[int]) -> None:
|
||
existing = set(db.execute(
|
||
select(PermAccountRole.role_id).where(PermAccountRole.account_id == account_id)
|
||
).scalars().all())
|
||
wanted = set(role_ids or [])
|
||
for role_id in existing - wanted:
|
||
for row in db.execute(select(PermAccountRole).where(
|
||
PermAccountRole.account_id == account_id, PermAccountRole.role_id == role_id)).scalars():
|
||
db.delete(row)
|
||
for role_id in wanted - existing:
|
||
db.add(PermAccountRole(account_id=account_id, role_id=role_id))
|
||
db.flush()
|
||
|
||
|
||
def _sync_identities(db, account_id: int, org_unit_id: int | None) -> None:
|
||
if not org_unit_id:
|
||
return
|
||
exists = db.execute(select(AccountIdentity).where(
|
||
AccountIdentity.account_id == account_id, AccountIdentity.org_unit_id == org_unit_id
|
||
)).scalars().first()
|
||
if exists:
|
||
return
|
||
total = db.execute(select(func.count(AccountIdentity.id)).where(
|
||
AccountIdentity.account_id == account_id)).scalar() or 0
|
||
db.add(AccountIdentity(account_id=account_id, org_unit_id=org_unit_id, is_default=total == 0))
|
||
db.flush()
|
||
|
||
|
||
@router.post("/hub/sync")
|
||
def trigger_sync(db: DbSession, current: PrincipalOf, mode: str = "full") -> dict[str, Any]:
|
||
"""手动触发一次统一身份同步。``mode=full`` 全量镜像,``mode=changes`` 只蹭游标。
|
||
|
||
默认全量:手动点按钮的人要的是"把现在Hub里的样子搬过来",增量只补事件,
|
||
补不了那些压根没发事件的变化(人员资料调整就不发)。界面上的"立即同步"走全量,
|
||
增量留给定时任务。
|
||
"""
|
||
if not current.permission.can("org:sync:run"):
|
||
raise forbidden("缺少权限:org:sync:run")
|
||
from ..service.org_sync import serialize
|
||
|
||
if mode == "changes":
|
||
run = sync_changes(db, trigger="manual")
|
||
else:
|
||
run = sync_all(db, trigger="manual")
|
||
db.commit()
|
||
return ok(serialize(run))
|
||
|
||
|
||
@router.get("/hub/sync/changes")
|
||
def poll_changes(db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||
"""手动拉一次增量。给没开定时轮询的环境(开发档)留个手动手。"""
|
||
if not current.permission.can("org:sync:run"):
|
||
raise forbidden("缺少权限:org:sync:run")
|
||
from ..service.org_sync import serialize
|
||
|
||
run = sync_changes(db, trigger="manual")
|
||
db.commit()
|
||
return ok(serialize(run))
|