792 lines
33 KiB
Python
792 lines
33 KiB
Python
"""Organization management: units, persons, roles, groups, agents, handover."""
|
||
|
||
from __future__ import annotations
|
||
|
||
from datetime import datetime
|
||
|
||
from fastapi import APIRouter, Depends, Query
|
||
from sqlalchemy import func, or_, select
|
||
from sqlalchemy.orm import Session, selectinload
|
||
|
||
from .. import models, permissions, schemas, serializers
|
||
from ..db import get_db
|
||
from ..deps import CurrentUser, current_user, require_permission
|
||
from ..envelope import bad_request, not_found, ok
|
||
from ..security import hash_password
|
||
from ..service import hub, hub_refs, org
|
||
|
||
router = APIRouter(prefix="/org", tags=["organization"])
|
||
|
||
|
||
def _unit_paths(db: Session, unit: models.Unit, parent: models.Unit | None) -> None:
|
||
unit.parent_name = parent.name if parent else ""
|
||
unit.path = f"{parent.path}{unit.name}\\" if parent else f"{unit.name}\\"
|
||
unit.distinguished_name = f"o={unit.path[:-1]}"
|
||
unit.short_name = unit.name
|
||
|
||
|
||
def _repropagate(db: Session, parent_id: int | None) -> None:
|
||
parent = db.get(models.Unit, parent_id) if parent_id else None
|
||
children = db.execute(select(models.Unit).where(models.Unit.parent_id == parent_id)).scalars().all()
|
||
for child in children:
|
||
_unit_paths(db, child, parent)
|
||
_sync_unit_identities(db, child.id)
|
||
_repropagate(db, child.id)
|
||
|
||
|
||
def _sync_unit_identities(db: Session, unit_id: int | None) -> None:
|
||
unit = db.get(models.Unit, unit_id)
|
||
if unit is None:
|
||
return
|
||
rows = db.execute(select(models.Identity).where(models.Identity.unit_id == unit_id)).scalars().all()
|
||
for row in rows:
|
||
row.unit_name = unit.name
|
||
row.unit_path = unit.path[:-1]
|
||
row.distinguished_name = org.dn_for(unit.path[:-1], row.person_name, row.name)
|
||
|
||
|
||
def _managers_by_id(db: Session) -> dict[int, models.User]:
|
||
"""``users.id -> 人员``,给部门列表补负责人姓名用(一次查全量,不在循环里查库)。"""
|
||
return {row.id: row for row in db.execute(select(models.User)).scalars().all()}
|
||
|
||
|
||
def _resolve_person_ref(value: str | None, *, field: str, db: Session) -> int | None:
|
||
"""把「负责人 / 直属上级」这种人员引用换成主键,选不到就当场报错。"""
|
||
person_id = models.as_id(value)
|
||
if person_id is None:
|
||
return None
|
||
person = db.get(models.User, person_id)
|
||
if person is None:
|
||
raise bad_request(f"{field}不存在,请重新选择")
|
||
if person.status != models.UserStatus.ACTIVE:
|
||
raise bad_request(f"{field}{person.display_name}已停用,请重新选择")
|
||
return person.id
|
||
|
||
|
||
@router.get("/tree", dependencies=[Depends(require_permission("org:unit"))])
|
||
def unit_tree(db: Session = Depends(get_db), user: CurrentUser = Depends(current_user)) -> dict:
|
||
# 部门树跟着数据范围走:部门负责人只看到自己那一支,超级管理员看到全公司。
|
||
unit_stmt = permissions.scoped(
|
||
select(models.Unit), user, models.Unit.id, permissions.scope_unit_ids(db, user)
|
||
)
|
||
person_stmt = permissions.scoped(
|
||
select(models.User).options(selectinload(models.User.unit)).where(
|
||
models.User.status == models.UserStatus.ACTIVE,
|
||
# 内置管理员是登录用的系统账号,不是组织架构里的一个员工,别让它挂在部门树上;
|
||
# 被授予管理员角色的真人不受这条影响,人员管理页也照常能管到系统账号。
|
||
models.User.account.not_in(org.system_account_names()),
|
||
),
|
||
user,
|
||
models.User.id,
|
||
permissions.scope_person_ids(db, user),
|
||
)
|
||
units = db.execute(unit_stmt.order_by(*org.unit_order_by())).scalars().all()
|
||
persons = db.execute(
|
||
person_stmt.order_by(models.User.display_name, models.User.id)
|
||
).scalars().all()
|
||
identities = db.execute(select(models.Identity)).scalars().all()
|
||
by_person: dict[int, list[models.Identity]] = {}
|
||
for item in identities:
|
||
by_person.setdefault(item.person_id, []).append(item)
|
||
|
||
managers = _managers_by_id(db)
|
||
nodes = {
|
||
u.id: {
|
||
**serializers.unit(u, managers.get(u.manager_person_id) if u.manager_person_id else None),
|
||
"type": "unit",
|
||
"children": [],
|
||
}
|
||
for u in units
|
||
}
|
||
roots: list[dict] = []
|
||
for unit in units:
|
||
node = nodes[unit.id]
|
||
if unit.parent_id and unit.parent_id in nodes:
|
||
nodes[unit.parent_id]["children"].append(node)
|
||
else:
|
||
roots.append(node)
|
||
for person in persons:
|
||
owner = None
|
||
if person.organization_id and person.organization_id in nodes:
|
||
owner = nodes[person.organization_id]
|
||
person_node = {
|
||
"id": str(person.id),
|
||
"type": "person",
|
||
"display_name": person.display_name,
|
||
"account": person.account,
|
||
"organization_id": str(person.organization_id) if person.organization_id else "",
|
||
"distinguished_name": (by_person.get(person.id) or [None])[0].distinguished_name
|
||
if by_person.get(person.id)
|
||
else org.dn_for(person.organization_path, person.display_name, person.account),
|
||
"identities": [serializers.identity(i) for i in by_person.get(person.id, [])],
|
||
"children": [],
|
||
}
|
||
if owner:
|
||
owner["children"].append(person_node)
|
||
else:
|
||
roots.append(person_node)
|
||
return ok(roots)
|
||
|
||
|
||
@router.get("/units", dependencies=[Depends(require_permission("org:unit"))])
|
||
def list_units(db: Session = Depends(get_db), user: CurrentUser = Depends(current_user)) -> dict:
|
||
stmt = permissions.scoped(
|
||
select(models.Unit), user, models.Unit.id, permissions.scope_unit_ids(db, user)
|
||
)
|
||
rows = db.execute(stmt.order_by(*org.unit_order_by())).scalars().all()
|
||
managers = _managers_by_id(db)
|
||
return ok(
|
||
[
|
||
serializers.unit(r, managers.get(r.manager_person_id) if r.manager_person_id else None)
|
||
for r in rows
|
||
]
|
||
)
|
||
|
||
|
||
def _check_unit_code_length(code: str) -> None:
|
||
"""``oa_unit.code`` 是 varchar(190),超长要在写库前挡掉,别抛数据库错误。"""
|
||
if len(str(code or "")) > 190:
|
||
raise bad_request("组织编码长度不能超过 190 个字符")
|
||
|
||
|
||
@router.post("/units", dependencies=[Depends(require_permission("org:unit"))])
|
||
def create_unit(body: schemas.UnitBody, db: Session = Depends(get_db)) -> dict:
|
||
parent_id = models.as_id(body.parent_id)
|
||
if not models.UnitStatus.is_known(body.status):
|
||
raise bad_request("部门状态取值不合法")
|
||
_check_unit_code_length(body.code)
|
||
unit = models.Unit(
|
||
name=body.name, code=body.code, alias=body.alias, description=body.description,
|
||
parent_id=parent_id, order_number=body.order_number, status=body.status,
|
||
manager_person_id=_resolve_person_ref(body.manager_person_id, field="部门负责人", db=db),
|
||
)
|
||
parent = db.get(models.Unit, parent_id) if parent_id else None
|
||
_unit_paths(db, unit, parent)
|
||
db.add(unit)
|
||
db.commit()
|
||
return ok(serializers.unit(unit, db.get(models.User, unit.manager_person_id) if unit.manager_person_id else None))
|
||
|
||
|
||
#: 部门绑了 Hub 组织(``hub_org_id`` 非空)之后由对方说了算的字段。
|
||
#: 界面上改这些会被当场挡下来——放过去也只是让下一趟同步盖回来,
|
||
#: 不如一开始就说清楚"要自己管就先解绑"。负责人、排序、说明、简称是本地字段,随便改。
|
||
def _hub_owned_changes(unit: models.Unit, body: schemas.UnitBody) -> list[str]:
|
||
blocked: list[str] = []
|
||
if unit.name != body.name:
|
||
blocked.append("名称")
|
||
if (unit.code or "") != (body.code or ""):
|
||
blocked.append("组织编码")
|
||
if int(unit.status) != int(body.status):
|
||
blocked.append("状态")
|
||
if models.as_id(body.parent_id) != unit.parent_id:
|
||
blocked.append("上级部门")
|
||
return blocked
|
||
|
||
|
||
def _subtree_units(db: Session, unit_id: int) -> dict[int, str]:
|
||
"""``{部门 id: 当时的 path}``。改完再取一次路径就能拼出"旧路径 -> 新路径"。"""
|
||
out: dict[int, str] = {}
|
||
pending = [unit_id]
|
||
guard = 0
|
||
while pending and guard < 5000:
|
||
current = pending.pop()
|
||
unit = db.get(models.Unit, current)
|
||
if unit is None:
|
||
continue
|
||
out[unit.id] = unit.path or ""
|
||
pending.extend(
|
||
child.id
|
||
for child in db.execute(
|
||
select(models.Unit).where(models.Unit.parent_id == unit.id)
|
||
).scalars().all()
|
||
)
|
||
guard += 1
|
||
return out
|
||
|
||
|
||
def _subtree_dns(db: Session, unit_ids: list[int]) -> dict[str, str]:
|
||
"""这批部门下面每个人的身份 DN 现值,改完之后用来算"旧 DN -> 新 DN"。"""
|
||
if not unit_ids:
|
||
return {}
|
||
return {
|
||
str(row.id): row.distinguished_name
|
||
for row in db.execute(
|
||
select(models.Identity).where(models.Identity.unit_id.in_(unit_ids))
|
||
).scalars().all()
|
||
}
|
||
|
||
|
||
def _carry_unit_renames(db: Session, before_units: dict[int, str], before_dns: dict[str, str]) -> None:
|
||
"""部门改了名或挪了层级,把审批岗位、共享名单里那些按路径/身份 DN 存的引用搬走。
|
||
|
||
跟统一身份同步用的是同一套搬运逻辑(见 ``service/hub_refs.py``):手工挪部门和
|
||
Hub 把部门挪走,对流程配置的杀伤力是一模一样的。
|
||
"""
|
||
db.flush() # Session 关了 autoflush,先落一落再读新路径
|
||
path_map: dict[str, str] = {}
|
||
for unit_id, old_path in before_units.items():
|
||
unit = db.get(models.Unit, unit_id)
|
||
if unit is not None and old_path and unit.path != old_path:
|
||
path_map[old_path] = unit.path
|
||
dn_map: dict[str, str] = {}
|
||
if before_dns:
|
||
for row in db.execute(
|
||
select(models.Identity).where(models.Identity.id.in_(list(before_dns)))
|
||
).scalars().all():
|
||
old = before_dns.get(str(row.id), "")
|
||
if old and row.distinguished_name != old:
|
||
dn_map[old] = row.distinguished_name
|
||
maps = hub_refs.build_maps(path_map=path_map, dn_map=dn_map)
|
||
if not maps.empty:
|
||
hub_refs.rewrite(db, maps)
|
||
|
||
|
||
@router.put("/units/{unit_id}", dependencies=[Depends(require_permission("org:unit"))])
|
||
def update_unit(unit_id: int, body: schemas.UnitBody, db: Session = Depends(get_db)) -> dict:
|
||
unit = db.get(models.Unit, unit_id)
|
||
if unit is None:
|
||
raise not_found("部门不存在")
|
||
if not models.UnitStatus.is_known(body.status):
|
||
raise bad_request("部门状态取值不合法")
|
||
_check_unit_code_length(body.code)
|
||
if unit.hub_org_id:
|
||
blocked = _hub_owned_changes(unit, body)
|
||
if blocked:
|
||
raise bad_request(
|
||
f"「{'、'.join(blocked)}」由统一身份同步接管,这里改不动(改了下一趟同步也会被 Hub 盖回来)。"
|
||
"要自己管这个部门,先点「解绑统一身份」;只改负责人、排序、说明、简称不用解绑。"
|
||
)
|
||
parent_id = models.as_id(body.parent_id)
|
||
moved = parent_id != unit.parent_id
|
||
name_changed = unit.name != body.name
|
||
# 改名/挪层级会连带改掉整棵子树的路径和下面所有人的身份 DN,
|
||
# 先记下现值,收尾时好把按这些字符串存的审批岗位与共享名单一起搬走。
|
||
before_units = _subtree_units(db, unit_id) if (moved or name_changed) else {}
|
||
before_dns = _subtree_dns(db, list(before_units)) if before_units else {}
|
||
unit.name = body.name
|
||
unit.code = body.code
|
||
unit.alias = body.alias
|
||
unit.description = body.description
|
||
unit.order_number = body.order_number
|
||
unit.status = body.status
|
||
unit.manager_person_id = _resolve_person_ref(body.manager_person_id, field="部门负责人", db=db)
|
||
if moved and _is_descendant(db, unit_id, parent_id):
|
||
raise bad_request("不能把部门移动到自己的下级")
|
||
if moved:
|
||
unit.parent_id = parent_id
|
||
_unit_paths(db, unit, db.get(models.Unit, parent_id) if parent_id else None)
|
||
_sync_unit_identities(db, unit.id)
|
||
_repropagate(db, unit.id)
|
||
elif name_changed:
|
||
_unit_paths(db, unit, db.get(models.Unit, unit.parent_id) if unit.parent_id else None)
|
||
_sync_unit_identities(db, unit.id)
|
||
_repropagate(db, unit.id)
|
||
if before_units:
|
||
_carry_unit_renames(db, before_units, before_dns)
|
||
db.commit()
|
||
return ok(serializers.unit(unit, db.get(models.User, unit.manager_person_id) if unit.manager_person_id else None))
|
||
|
||
|
||
def _is_descendant(db: Session, ancestor_id: int, candidate_id: int) -> bool:
|
||
current: int | None = candidate_id
|
||
guard = 0
|
||
while current and guard < 50:
|
||
if current == ancestor_id:
|
||
return True
|
||
node = db.get(models.Unit, current)
|
||
current = node.parent_id if node else None
|
||
guard += 1
|
||
return False
|
||
|
||
|
||
@router.delete("/units/{unit_id}", dependencies=[Depends(require_permission("org:unit"))])
|
||
def delete_unit(unit_id: int, db: Session = Depends(get_db)) -> dict:
|
||
unit = db.get(models.Unit, unit_id)
|
||
if unit is None:
|
||
raise not_found("部门不存在")
|
||
if db.execute(select(func.count(models.Unit.id)).where(models.Unit.parent_id == unit_id)).scalar():
|
||
raise bad_request("请先删除下级部门")
|
||
if unit.hub_org_id:
|
||
raise bad_request(
|
||
f"这个部门来自统一身份(Hub 组织 {unit.hub_org_id}),删掉就再也对不回对方那个组织:"
|
||
"下一趟同步只会新建一个空部门,负责人和按部门配的流程权限都会丢。"
|
||
"要让它在系统里消失,请在 Hub 那边停用,本系统会自动跟着停用;"
|
||
"确实要变成本地部门自己管,先解绑统一身份再删。"
|
||
)
|
||
if db.execute(select(func.count(models.User.id)).where(models.User.organization_id == unit_id)).scalar():
|
||
raise bad_request("部门下仍有人员")
|
||
db.delete(unit)
|
||
db.commit()
|
||
return ok({"success": True})
|
||
|
||
|
||
@router.post("/units/{unit_id}/hub-binding", dependencies=[Depends(require_permission("org:unit"))])
|
||
def bind_unit_hub(unit_id: int, body: schemas.UnitHubBindBody, db: Session = Depends(get_db)) -> dict:
|
||
"""把本地自建部门手工认成 Hub 的某个组织。
|
||
|
||
同步本来会按组织编码自动认领(``hub_sync_bind_local_by_code``),这一条是给编码对不上、
|
||
但确实是同一个部门的情况用的:绑上之后部门主键不变,挂在它身上的流程权限原样保留,
|
||
名称与层级从此跟着 Hub 走。
|
||
"""
|
||
unit = db.get(models.Unit, unit_id)
|
||
if unit is None:
|
||
raise not_found("部门不存在")
|
||
hub_org_id = models.as_id(body.hub_org_id)
|
||
if not hub_org_id or hub_org_id <= 0:
|
||
raise bad_request("Hub 组织 id 要填一个正整数")
|
||
if unit.hub_org_id:
|
||
raise bad_request(f"这个部门已经对应 Hub 组织 {unit.hub_org_id},要先解绑再改绑")
|
||
clash = db.execute(
|
||
select(models.Unit).where(models.Unit.hub_org_id == hub_org_id)
|
||
).scalars().first()
|
||
if clash is not None:
|
||
raise bad_request(f"Hub 组织 {hub_org_id} 已经对应到部门「{clash.name}」,一个组织只能对一个部门")
|
||
unit.hub_org_id = hub_org_id
|
||
db.commit()
|
||
return ok(
|
||
serializers.unit(unit, db.get(models.User, unit.manager_person_id) if unit.manager_person_id else None),
|
||
"已绑定统一身份,此后名称与层级由 Hub 接管",
|
||
)
|
||
|
||
|
||
@router.delete("/units/{unit_id}/hub-binding", dependencies=[Depends(require_permission("org:unit"))])
|
||
def unbind_unit_hub(unit_id: int, db: Session = Depends(get_db)) -> dict:
|
||
"""解绑统一身份:部门变成本地自建部门,从此同步不再管它。
|
||
|
||
这是唯一会清空 ``hub_org_id`` 的入口,而且是故意的——组织架构、部门负责人、按部门配的
|
||
权限全靠这一列长期对上号。解绑之后 Hub 里那个组织会被当成"本地没有的部门"重新建一个,
|
||
所以只有真的要自己管一个部门时才用它。
|
||
"""
|
||
unit = db.get(models.Unit, unit_id)
|
||
if unit is None:
|
||
raise not_found("部门不存在")
|
||
if not unit.hub_org_id:
|
||
raise bad_request("这个部门本来就是本地自建部门,没有绑定统一身份")
|
||
unit.hub_org_id = None
|
||
db.commit()
|
||
return ok(
|
||
serializers.unit(unit, db.get(models.User, unit.manager_person_id) if unit.manager_person_id else None),
|
||
"已解绑统一身份,这个部门改由本地维护",
|
||
)
|
||
|
||
|
||
# ------------------------------- persons --------------------------------
|
||
|
||
|
||
@router.get("/persons")
|
||
def list_persons(
|
||
db: Session = Depends(get_db),
|
||
user: CurrentUser = Depends(require_permission("org:person")),
|
||
keyword: str = Query(""),
|
||
organization_id: str = Query(""),
|
||
status: str = Query(""),
|
||
role: str = Query(""),
|
||
page: int = Query(1, ge=1),
|
||
page_size: int = Query(20, ge=1, le=200),
|
||
) -> dict:
|
||
stmt = permissions.scoped(
|
||
select(models.User).options(selectinload(models.User.unit)),
|
||
user,
|
||
models.User.id,
|
||
permissions.scope_person_ids(db, user),
|
||
)
|
||
if keyword:
|
||
like = f"%{keyword}%"
|
||
stmt = stmt.where(
|
||
or_(
|
||
models.User.display_name.like(like),
|
||
models.User.account.like(like),
|
||
models.User.email.like(like),
|
||
)
|
||
)
|
||
if organization_id:
|
||
target = models.as_id(organization_id)
|
||
stmt = stmt.where(models.User.organization_id.in_(org.descendant_unit_ids(db, target)))
|
||
if status:
|
||
status_value = models.as_id(status)
|
||
if status_value is None or not models.UserStatus.is_known(status_value):
|
||
raise bad_request("状态取值不合法")
|
||
stmt = stmt.where(models.User.status == status_value)
|
||
if role:
|
||
stmt = stmt.where(models.User.role == role)
|
||
total = int(db.execute(select(func.count()).select_from(stmt.subquery())).scalar() or 0)
|
||
rows = db.execute(
|
||
stmt.order_by(models.User.display_name, models.User.id)
|
||
.offset((page - 1) * page_size)
|
||
.limit(page_size)
|
||
).scalars().all()
|
||
items = []
|
||
for row in rows:
|
||
items.append(serializers.person(row, org.person_identities(db, row.id)))
|
||
return ok(serializers.page(items, total, page, page_size))
|
||
|
||
|
||
@router.get("/persons/simple")
|
||
def simple_persons(
|
||
db: Session = Depends(get_db), _: CurrentUser = Depends(current_user), keyword: str = Query("")
|
||
) -> dict:
|
||
stmt = select(models.User).options(selectinload(models.User.unit)).where(
|
||
models.User.status == models.UserStatus.ACTIVE
|
||
)
|
||
if keyword:
|
||
like = f"%{keyword}%"
|
||
stmt = stmt.where(or_(models.User.display_name.like(like), models.User.account.like(like)))
|
||
rows = db.execute(stmt.order_by(models.User.display_name, models.User.id).limit(500)).scalars().all()
|
||
identities = db.execute(select(models.Identity)).scalars().all()
|
||
by_person: dict[int, list[str]] = {}
|
||
for item in identities:
|
||
by_person.setdefault(item.person_id, []).append(item.distinguished_name)
|
||
return ok(
|
||
[
|
||
{
|
||
"id": str(r.id),
|
||
"account": r.account,
|
||
"display_name": r.display_name,
|
||
"organization_name": r.organization_name,
|
||
"identities": by_person.get(r.id, []),
|
||
}
|
||
for r in rows
|
||
]
|
||
)
|
||
|
||
|
||
@router.get("/units/simple")
|
||
def simple_units(
|
||
db: Session = Depends(get_db), _: CurrentUser = Depends(current_user), keyword: str = Query("")
|
||
) -> dict:
|
||
"""表单「部门选择」字段用的轻量部门清单,普通登录用户就能取。"""
|
||
stmt = select(models.Unit).where(models.Unit.status == models.UnitStatus.ACTIVE)
|
||
if keyword:
|
||
stmt = stmt.where(models.Unit.name.like(f"%{keyword}%"))
|
||
rows = db.execute(stmt.order_by(*org.unit_order_by()).limit(500)).scalars().all()
|
||
managers = _managers_by_id(db)
|
||
return ok(
|
||
[
|
||
{
|
||
"id": str(row.id),
|
||
"name": row.name,
|
||
"path": (row.path or row.name).rstrip("\\"),
|
||
"manager_name": (managers.get(row.manager_person_id).display_name if managers.get(row.manager_person_id) else "") or "",
|
||
}
|
||
for row in rows
|
||
]
|
||
)
|
||
|
||
|
||
@router.post("/persons", dependencies=[Depends(require_permission("org:person"))])
|
||
def create_person(body: schemas.PersonBody, db: Session = Depends(get_db)) -> dict:
|
||
# 只读账号名不许先在本地占坑:等 Hub 把人下发下来才有 hub_user_id,
|
||
# 本地先建一个同名号只会让认领对不上,或者冒出一个没有锚点的假管理员。
|
||
reserved = org.account_reserved_reason(body.account)
|
||
if reserved:
|
||
raise bad_request(reserved)
|
||
if db.execute(select(models.User).where(models.User.account == body.account)).scalar_one_or_none():
|
||
raise bad_request("账号已存在")
|
||
organization_id = models.as_id(body.organization_id)
|
||
unit = db.get(models.Unit, organization_id) if organization_id else None
|
||
if organization_id and unit is None:
|
||
raise bad_request("部门不存在")
|
||
if not models.UserStatus.is_known(body.status):
|
||
raise bad_request("状态取值不合法")
|
||
person = models.User(
|
||
account=body.account,
|
||
display_name=body.display_name,
|
||
password_hash=hash_password(body.password or "123456"),
|
||
email=body.email,
|
||
avatar_url=body.avatar_url,
|
||
organization_id=unit.id if unit else None,
|
||
leader_id=_resolve_person_ref(body.leader_id, field="直属上级", db=db),
|
||
role=body.role,
|
||
status=body.status,
|
||
# 手工建的账号永远归 local,Hub 夜间同步不会碰它。
|
||
source=models.AccountSource.LOCAL,
|
||
)
|
||
db.add(person)
|
||
db.flush()
|
||
names = body.identity_names or [body.display_name]
|
||
for index, identity_name in enumerate(dict.fromkeys(names)):
|
||
db.add(
|
||
models.Identity(
|
||
name=identity_name, person_id=person.id, person_name=person.display_name,
|
||
unit_id=unit.id if unit else None, unit_name=unit.name if unit else "",
|
||
unit_path=(unit.path[:-1] if unit else ""),
|
||
distinguished_name=org.dn_for(unit.path[:-1] if unit else "", person.display_name, identity_name),
|
||
is_default=index == 0,
|
||
)
|
||
)
|
||
db.commit()
|
||
return ok(serializers.person(person, org.person_identities(db, person.id)))
|
||
|
||
|
||
@router.put("/persons/{person_id}", dependencies=[Depends(require_permission("org:person"))])
|
||
def update_person(person_id: int, body: schemas.PersonBody, db: Session = Depends(get_db)) -> dict:
|
||
person = db.get(models.User, person_id)
|
||
if person is None:
|
||
raise not_found("人员不存在")
|
||
reason = org.person_lock_reason(person)
|
||
if reason:
|
||
raise bad_request(reason)
|
||
if not models.UserStatus.is_known(body.status):
|
||
raise bad_request("状态取值不合法")
|
||
person.display_name = body.display_name
|
||
person.role = body.role
|
||
person.email = body.email
|
||
person.avatar_url = body.avatar_url
|
||
person.status = body.status
|
||
leader_id = _resolve_person_ref(body.leader_id, field="直属上级", db=db)
|
||
# 自己当自己的上级会让「上级审批」变成自批,这条必须在写库前挡住。
|
||
if leader_id == person_id:
|
||
raise bad_request("直属上级不能是本人")
|
||
person.leader_id = leader_id
|
||
if body.password:
|
||
hub.ensure_local_password_settable(person)
|
||
person.password_hash = hash_password(body.password)
|
||
organization_id = models.as_id(body.organization_id)
|
||
if organization_id and organization_id != person.organization_id:
|
||
unit = db.get(models.Unit, organization_id)
|
||
if unit is None:
|
||
raise bad_request("部门不存在")
|
||
person.organization_id = unit.id
|
||
for identity_row in org.person_identities(db, person.id):
|
||
identity_row.unit_id = unit.id
|
||
identity_row.unit_name = unit.name
|
||
identity_row.unit_path = unit.path[:-1]
|
||
identity_row.distinguished_name = org.dn_for(unit.path[:-1], person.display_name, identity_row.name)
|
||
db.commit()
|
||
return ok(serializers.person(person, org.person_identities(db, person.id)))
|
||
|
||
|
||
@router.delete("/persons/{person_id}", dependencies=[Depends(require_permission("org:person"))])
|
||
def delete_person(person_id: int, force: bool = False, db: Session = Depends(get_db)) -> dict:
|
||
"""删除人员。绑过统一身份的账号默认删不掉,要删得显式带 ``force=true``。
|
||
|
||
跟「Hub 部门不许删」是同一个道理:``hub_user_id`` 是本地与 Hub 之间唯一的锚点,
|
||
行一删锚点就跟着没了,之后 Hub 那边改名、停用、启用、重新启用都再也对不回本地 ——
|
||
管理员在界面上删完人再同步,看到的就是「什么都没发生」。停用才是常态操作;
|
||
真要删(比如误认领了别人的账号),带 force 删完,只要 Hub 清单里还有这个人,
|
||
下一趟同步会按自动建号重建一条**新主键**的记录,权限与共享名单需要重新配。
|
||
"""
|
||
person = db.get(models.User, person_id)
|
||
if person is None:
|
||
raise not_found("人员不存在")
|
||
reason = org.person_lock_reason(person)
|
||
if reason:
|
||
raise bad_request(reason + "。删除就更不行了:删完连本地这个入口/管理员身份都没了")
|
||
if person.hub_user_id and not force:
|
||
raise bad_request(
|
||
f"该账号绑定统一身份(user_id={person.hub_user_id}),删除后与 Hub 的对应关系会一起消失,"
|
||
"之后 Hub 改名、停用、重新启用都同步不到这个人。请改用「停用」;"
|
||
"确认要删除请带 force=true(Hub 清单里还有他时,下趟同步会重建一条新记录)"
|
||
)
|
||
if db.execute(select(func.count(models.Task.id)).where(models.Task.person == str(person_id))).scalar():
|
||
raise bad_request("该人员仍有待办,请先交接或办结")
|
||
# oa_unit.manager_person_id 没有外键(见 models.Unit),删人要顺手把负责人引用清掉,
|
||
# 否则部门会一直显示一个已经不存在的负责人。
|
||
for unit_row in db.execute(
|
||
select(models.Unit).where(models.Unit.manager_person_id == person_id)
|
||
).scalars().all():
|
||
unit_row.manager_person_id = None
|
||
for identity_row in db.execute(
|
||
select(models.Identity).where(models.Identity.person_id == person_id)
|
||
).scalars().all():
|
||
db.delete(identity_row)
|
||
db.delete(person)
|
||
db.commit()
|
||
return ok({"success": True})
|
||
|
||
|
||
# -------------------------------- role / group ---------------------------
|
||
|
||
|
||
@router.get("/roles", dependencies=[Depends(require_permission("org:role"))])
|
||
def list_roles(db: Session = Depends(get_db), _: CurrentUser = Depends(current_user)) -> dict:
|
||
rows = db.execute(select(models.Role).order_by(models.Role.name)).scalars().all()
|
||
return ok([serializers.role(r) for r in rows])
|
||
|
||
|
||
@router.post("/roles", dependencies=[Depends(require_permission("org:role"))])
|
||
def upsert_role(body: schemas.RoleBody, db: Session = Depends(get_db)) -> dict:
|
||
row = db.execute(select(models.Role).where(models.Role.name == body.name)).scalar_one_or_none()
|
||
if row is None:
|
||
row = models.Role(name=body.name)
|
||
db.add(row)
|
||
row.description = body.description
|
||
row.list_auth = body.list_auth
|
||
row.unit = body.unit
|
||
db.commit()
|
||
return ok(serializers.role(row))
|
||
|
||
|
||
@router.delete("/roles/{role_id}", dependencies=[Depends(require_permission("org:role"))])
|
||
def delete_role(role_id: str, db: Session = Depends(get_db)) -> dict:
|
||
row = db.get(models.Role, role_id)
|
||
if row is None:
|
||
raise not_found("角色不存在")
|
||
db.delete(row)
|
||
db.commit()
|
||
return ok({"success": True})
|
||
|
||
|
||
@router.get("/groups", dependencies=[Depends(require_permission("org:role"))])
|
||
def list_groups(db: Session = Depends(get_db), _: CurrentUser = Depends(current_user)) -> dict:
|
||
rows = db.execute(select(models.Group).order_by(models.Group.name)).scalars().all()
|
||
return ok([serializers.group(r) for r in rows])
|
||
|
||
|
||
@router.post("/groups", dependencies=[Depends(require_permission("org:role"))])
|
||
def upsert_group(body: schemas.GroupBody, db: Session = Depends(get_db)) -> dict:
|
||
row = db.execute(select(models.Group).where(models.Group.name == body.name)).scalar_one_or_none()
|
||
if row is None:
|
||
row = models.Group(name=body.name)
|
||
db.add(row)
|
||
row.description = body.description
|
||
row.list_identity = body.list_identity
|
||
row.list_person = body.list_person
|
||
row.unit = body.unit
|
||
db.commit()
|
||
return ok(serializers.group(row))
|
||
|
||
|
||
@router.delete("/groups/{group_id}", dependencies=[Depends(require_permission("org:role"))])
|
||
def delete_group(group_id: str, db: Session = Depends(get_db)) -> dict:
|
||
row = db.get(models.Group, group_id)
|
||
if row is None:
|
||
raise not_found("分组不存在")
|
||
db.delete(row)
|
||
db.commit()
|
||
return ok({"success": True})
|
||
|
||
|
||
# --------------------------------- agent ---------------------------------
|
||
|
||
|
||
@router.get("/agents", dependencies=[Depends(require_permission("work:agent"))])
|
||
def list_agents(user: CurrentUser = Depends(current_user), db: Session = Depends(get_db)) -> dict:
|
||
stmt = select(models.Agent)
|
||
if not user.is_admin:
|
||
stmt = stmt.where(models.Agent.person_id == user.person_id)
|
||
rows = db.execute(stmt.order_by(models.Agent.create_time.desc())).scalars().all()
|
||
return ok([serializers.agent(r) for r in rows])
|
||
|
||
|
||
@router.post("/agents")
|
||
def create_agent(
|
||
body: schemas.AgentBody,
|
||
user: CurrentUser = Depends(require_permission("work:agent")),
|
||
db: Session = Depends(get_db),
|
||
) -> dict:
|
||
if not body.identity:
|
||
raise bad_request("请选择代理身份")
|
||
row = models.Agent(
|
||
person_id=user.person_id,
|
||
person_name=user.display_name,
|
||
identity=body.identity,
|
||
from_identity=user.identity,
|
||
from_person=user.display_name,
|
||
process=body.process,
|
||
process_name=body.process_name,
|
||
enable_time=_parse_dt(body.enable_time),
|
||
expire_time=_parse_dt(body.expire_time),
|
||
enabled=body.enabled,
|
||
comment=body.comment,
|
||
)
|
||
db.add(row)
|
||
db.commit()
|
||
return ok(serializers.agent(row))
|
||
|
||
|
||
@router.delete("/agents/{agent_id}")
|
||
def delete_agent(
|
||
agent_id: str,
|
||
user: CurrentUser = Depends(require_permission("work:agent")),
|
||
db: Session = Depends(get_db),
|
||
) -> dict:
|
||
row = db.get(models.Agent, agent_id)
|
||
if row is None:
|
||
raise not_found("代理设置不存在")
|
||
if row.person_id != user.person_id and not user.is_admin:
|
||
raise bad_request("无权删除该代理设置")
|
||
db.delete(row)
|
||
db.commit()
|
||
return ok({"success": True})
|
||
|
||
|
||
def _parse_dt(value: str) -> datetime | None:
|
||
value = (value or "").strip()
|
||
if not value:
|
||
return None
|
||
for fmt in ("%Y-%m-%dT%H:%M:%S", "%Y-%m-%d %H:%M:%S", "%Y-%m-%d"):
|
||
try:
|
||
return datetime.strptime(value[: len(datetime.now().strftime(fmt))], fmt)
|
||
except ValueError:
|
||
continue
|
||
try:
|
||
return datetime.fromisoformat(value)
|
||
except ValueError:
|
||
return None
|
||
|
||
|
||
# -------------------------------- handover --------------------------------
|
||
|
||
|
||
@router.get("/handovers", dependencies=[Depends(require_permission("work:handover"))])
|
||
def list_handovers(user: CurrentUser = Depends(current_user), db: Session = Depends(get_db)) -> dict:
|
||
rows = db.execute(
|
||
select(models.Handover)
|
||
.where(or_(models.Handover.from_person == user.person_id, models.Handover.person == user.person_id))
|
||
.order_by(models.Handover.create_time.desc())
|
||
).scalars().all()
|
||
return ok([serializers.handover(r) for r in rows])
|
||
|
||
|
||
@router.post("/handovers")
|
||
def create_handover(
|
||
body: schemas.HandoverBody,
|
||
user: CurrentUser = Depends(require_permission("work:handover")),
|
||
db: Session = Depends(get_db),
|
||
) -> dict:
|
||
from ..engine import engine
|
||
|
||
ref = org.ref_for(db, body.to_identity)
|
||
if not ref.person and not user.is_admin:
|
||
raise bad_request("转交对象不存在")
|
||
tasks = db.execute(
|
||
select(models.Task).where(models.Task.identity == user.identity)
|
||
).scalars().all()
|
||
record = models.Handover(
|
||
title=body.title or f"{user.display_name} 的待办交接",
|
||
from_person=user.person_id,
|
||
from_person_name=user.display_name,
|
||
from_identity=user.identity,
|
||
to_person=ref.person or body.to_person,
|
||
to_person_name=ref.name,
|
||
to_identity=body.to_identity,
|
||
scheme=body.scheme,
|
||
status="executing",
|
||
person=user.person_id,
|
||
)
|
||
db.add(record)
|
||
for task in tasks:
|
||
task.identity = body.to_identity
|
||
task.identity_name = ref.name
|
||
task.person = ref.person or task.person
|
||
task.unit = ref.unit or task.unit
|
||
task.empower_from_identity = user.identity
|
||
engine.notify(
|
||
db,
|
||
[body.to_identity],
|
||
type_="task",
|
||
title=f"待办交接:{task.title}",
|
||
body=f"{user.display_name} 将《{task.title}》交接给你处理。",
|
||
job=task.job,
|
||
work=task.work,
|
||
task=task.id,
|
||
process=task.process,
|
||
sender=user.display_name,
|
||
)
|
||
record.task_count = len(tasks)
|
||
record.status = "completed"
|
||
record.execute_time = datetime.now()
|
||
db.commit()
|
||
return ok(serializers.handover(record))
|