965 lines
41 KiB
Python
965 lines
41 KiB
Python
"""Organization management: units, persons, roles, groups, agents, handover."""
|
||
|
||
from __future__ import annotations
|
||
|
||
from datetime import datetime
|
||
from typing import Iterable
|
||
|
||
from fastapi import APIRouter, Depends, Query, Request
|
||
from sqlalchemy import delete, func, or_, select
|
||
from sqlalchemy.orm import Session, selectinload
|
||
|
||
from .. import models, permissions, schemas, serializers
|
||
from ..db import get_db
|
||
from ..deps import CurrentUser, client_ip, current_user, require_permission
|
||
from ..envelope import bad_request, not_found, ok
|
||
from ..query import count_of
|
||
from ..security import hash_password
|
||
from ..service import hub, hub_refs, hub_sync, org, personref
|
||
|
||
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)
|
||
_repropagate(db, child.id)
|
||
|
||
|
||
def _managers_by_id(
|
||
db: Session, units: Iterable[models.Unit], known: Iterable[models.User] = ()
|
||
) -> dict[int, models.User]:
|
||
"""``users.id -> 人员``,给部门列表补负责人姓名用(一次取齐,不在循环里查库)。
|
||
|
||
只捞这批部门真挂到的那几个人。以前是把 ``users`` 整张表读进内存再挑负责人:
|
||
部门页每开一次就把全员连 ``password_hash`` 一起搬过一遍网络,库在另一台机器上时
|
||
这一趟比部门树本身还贵,而且人数一涨就一起涨。
|
||
|
||
``known`` 给本次请求**已经 load 进来的人员行**(``GET /org/tree`` 拼人员节点时
|
||
刚整张读过一次 ``users``):负责人基本都是这批在职人里的一个,先在这份内存里找,
|
||
只对找不到的那几个发一次 ``IN``。找不到的三种情况都得照样问一遍,口径不能省:
|
||
负责人已停用(树上不显示他,但部门节点要写他的名字)、负责人是内置系统账号(同理)、
|
||
负责人在本次数据范围之外(部门负责人只看自己那一支时撞上别的支的负责人)。
|
||
远端库上一趟十几毫秒,这一条在树上通常是白跑的一趟。
|
||
"""
|
||
rows = {row.id: row for row in known}
|
||
ids = sorted(
|
||
{int(row.manager_person_id) for row in units if row.manager_person_id} - set(rows)
|
||
)
|
||
if ids:
|
||
rows.update(
|
||
{
|
||
row.id: row
|
||
for row in db.execute(
|
||
select(models.User).where(models.User.id.in_(ids))
|
||
).scalars().all()
|
||
}
|
||
)
|
||
return rows
|
||
|
||
|
||
def _account_or_fail(db: Session, value: str, *, field: str) -> str:
|
||
"""把界面交上来的人员引用换成登录账号,认不出就当场报错。
|
||
|
||
选人控件交出来的本来就是账号,这一层挡的是别的入口(开放接口、找人脚本、被改过的
|
||
前端):库里"是谁"那一列只认账号,放一串对不上人的字符串进去,待办就会挂在一个不
|
||
存在的人身上——本人的待办、对方的待办、交接记录里都看不见它,界面上一个错误都不报
|
||
(口径见 :mod:`app.service.personref`)。
|
||
"""
|
||
account = personref.account_of(db, value)
|
||
if not account:
|
||
raise bad_request(f"{field}认不出是谁,请重新选择")
|
||
return account
|
||
|
||
|
||
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)
|
||
)
|
||
# 不预加载 ``User.unit``:这一页只要"每个人挂在哪个部门",而部门上面那条查询
|
||
# 已经整张取过一次了,人员节点要的那行 DN 从 ``units`` 里现算就够(见 ``path_by_unit``)。
|
||
person_stmt = permissions.scoped(
|
||
select(models.User).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()
|
||
# 部门 id -> 展示用路径,口径与 ``User.organization_path`` 一致(库里 path 结尾带一个
|
||
# 分隔符,这里去掉)。树上已经加载的部门够用;只有"这个人所在的部门不在本次可见
|
||
# 范围里"那种少见组合才会缺一条,缺几个 id 就按 id 补查一次。
|
||
path_by_unit = {u.id: (u.path or u.name or "").rstrip(chr(92)) for u in units}
|
||
persons = db.execute(
|
||
person_stmt.order_by(models.User.display_name, models.User.id)
|
||
).scalars().all()
|
||
# 人所在部门不在本次可见范围时(部门负责人只看自己那一支时会碰到),
|
||
# 补一次按 id 的部门路径查询;缺几个补几个,不整表搬。
|
||
missing_units = sorted(
|
||
{
|
||
person.organization_id
|
||
for person in persons
|
||
if person.organization_id and person.organization_id not in path_by_unit
|
||
}
|
||
)
|
||
if missing_units:
|
||
for unit_id, unit_name, unit_path in db.execute(
|
||
select(models.Unit.id, models.Unit.name, models.Unit.path).where(
|
||
models.Unit.id.in_(missing_units)
|
||
)
|
||
).all():
|
||
path_by_unit[unit_id] = (unit_path or unit_name or "").rstrip(chr(92))
|
||
|
||
managers = _managers_by_id(db, units, known=persons)
|
||
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 "",
|
||
# 这一行只用于展示与搜索,认人用的是节点上另给的 ``account``
|
||
"distinguished_name": org.dn_for(
|
||
path_by_unit.get(person.organization_id, ""), person.display_name, person.account
|
||
),
|
||
"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, rows)
|
||
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 _carry_unit_renames(db: Session, before_units: dict[int, str]) -> None:
|
||
"""部门改了名或挪了层级,把审批岗位、共享名单里那些按部门路径存的引用搬走。
|
||
|
||
跟统一身份同步用的是同一套搬运逻辑(见 ``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
|
||
maps = hub_refs.build_maps(path_map=path_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
|
||
# 改名/挪层级会连带改掉整棵子树的路径,先记下现值,
|
||
# 收尾时好把按路径存的审批岗位与共享名单一起搬走。
|
||
before_units = _subtree_units(db, unit_id) if (moved or name_changed) 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)
|
||
_repropagate(db, unit.id)
|
||
elif name_changed:
|
||
_unit_paths(db, unit, db.get(models.Unit, unit.parent_id) if unit.parent_id else None)
|
||
_repropagate(db, unit.id)
|
||
if before_units:
|
||
_carry_unit_renames(db, before_units)
|
||
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})
|
||
|
||
|
||
def _hub_units(db: Session) -> list[models.Unit]:
|
||
"""所有绑过统一身份的部门。空壳检查只看这批:本地自建部门轮不到同步去处置。"""
|
||
return list(db.execute(select(models.Unit).where(models.Unit.hub_org_id.is_not(None))).scalars().all())
|
||
|
||
|
||
def _shell_rows(db: Session) -> list[dict]:
|
||
"""当前库里的空壳部门 + 每一具"删不掉的原因"。
|
||
|
||
壳子通常只有个位数(Hub 每挪一次主键留一具),所以这里逐条查人数、下级和角色引用,
|
||
不为了省几次查询把判据拆成三份互相抄不准的 SQL。
|
||
"""
|
||
rows: list[dict] = []
|
||
for unit in hub_sync.find_shell_units(_hub_units(db)):
|
||
rows.append(
|
||
{
|
||
"id": str(unit.id),
|
||
"name": unit.name,
|
||
"code": unit.code,
|
||
"hub_org_id": str(unit.hub_org_id),
|
||
"status": int(unit.status),
|
||
"blockers": hub_sync.shell_unit_blockers(db, unit),
|
||
}
|
||
)
|
||
return rows
|
||
|
||
|
||
@router.get("/units/shells", dependencies=[Depends(require_permission("org:unit"))])
|
||
def list_shell_units(db: Session = Depends(get_db)) -> dict:
|
||
"""列出 Hub 换主键之后留下的空壳部门(停用的旧身子,身份已被同名同码的在职部门接走)。
|
||
|
||
判据与「同步前体检」共用 :func:`hub_sync.find_shell_units`,界面上报几具就是几具;
|
||
``blockers`` 非空的那几具删不掉,得先把人挪走、下级删掉或改角色的数据范围。
|
||
"""
|
||
rows = _shell_rows(db)
|
||
return ok(
|
||
{
|
||
"total": len(rows),
|
||
"deletable": len([row for row in rows if not row["blockers"]]),
|
||
"items": rows,
|
||
}
|
||
)
|
||
|
||
|
||
@router.post("/units/shells/cleanup", dependencies=[Depends(require_permission("org:unit"))])
|
||
def cleanup_shell_units(
|
||
body: schemas.UnitShellCleanupBody,
|
||
request: Request,
|
||
db: Session = Depends(get_db),
|
||
user: CurrentUser = Depends(current_user),
|
||
) -> dict:
|
||
"""一键清理空壳部门:把 Hub 换主键留下的死壳子删掉。
|
||
|
||
为什么这些能删、别的不行:本地对同步部门只停用不删除,是因为 ``hub_org_id`` 一丢就
|
||
再也对不回 Hub 那个组织。壳子不一样——它的编码与名称已经被一个在职部门顶着,同步
|
||
认回的是那个在职部门,这一具永远不会再接上任何组织,留在树上只是重名干扰。
|
||
|
||
删之前逐条重算判据(不认前端传来的旧名单):已经不再是壳子的跳过,还有人、有下级、
|
||
被权限角色当数据范围的也跳过并把原因报回去。``dry_run`` 一行都不动。
|
||
"""
|
||
candidates = {str(unit.id): unit for unit in hub_sync.find_shell_units(_hub_units(db))}
|
||
wanted = [str(models.as_id(value) or "") for value in body.ids] if body.ids else list(candidates)
|
||
deleted: list[dict] = []
|
||
skipped: list[dict] = []
|
||
for unit_id in wanted:
|
||
unit = candidates.get(unit_id)
|
||
if unit is None:
|
||
skipped.append({"id": unit_id, "name": "", "blockers": ["已经不是空壳部门(已被删除或 Hub 重新认回了)"]})
|
||
continue
|
||
blockers = hub_sync.shell_unit_blockers(db, unit)
|
||
if blockers:
|
||
skipped.append({"id": unit_id, "name": unit.name, "blockers": blockers})
|
||
continue
|
||
snapshot = {
|
||
"id": unit_id,
|
||
"name": unit.name,
|
||
"code": unit.code,
|
||
"hub_org_id": str(unit.hub_org_id),
|
||
}
|
||
if not body.dry_run:
|
||
db.delete(unit)
|
||
db.flush()
|
||
deleted.append(snapshot)
|
||
if deleted and not body.dry_run:
|
||
db.add(
|
||
models.OperationLog(
|
||
action="org_unit_shell_cleanup",
|
||
target=f"units:{len(deleted)}",
|
||
detail=";".join(
|
||
f"{row['name']}(编码 {row['code']},原 Hub 组织 {row['hub_org_id']})" for row in deleted
|
||
)[:2000],
|
||
person=str(user.person.id),
|
||
person_name=user.display_name,
|
||
identity=user.ref,
|
||
ip=client_ip(request),
|
||
)
|
||
)
|
||
db.commit()
|
||
return ok(
|
||
{"dry_run": bool(body.dry_run), "deleted": deleted, "skipped": skipped},
|
||
(
|
||
(f"预演:将删除 {len(deleted)} 个空壳部门" if body.dry_run else f"已删除 {len(deleted)} 个空壳部门")
|
||
+ (f",{len(skipped)} 个删不掉" if skipped else "")
|
||
),
|
||
)
|
||
|
||
|
||
@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),
|
||
# 拿手机号找人很常见(工单里只留了个号码、HR 拿花名册对号)
|
||
models.User.mobile.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 = count_of(db, stmt)
|
||
rows = db.execute(
|
||
stmt.order_by(models.User.display_name, models.User.id)
|
||
.offset((page - 1) * page_size)
|
||
.limit(page_size)
|
||
).scalars().all()
|
||
items = [serializers.person(row) for row in rows]
|
||
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()
|
||
# 不再随人发身份 DN 清单:选人控件存的就是账号,部门已经有 organization_name,
|
||
# 那一串 DN 拖过网络只换来一个没人再读的形状(多身份按本部署口径不再使用)
|
||
return ok(
|
||
[
|
||
{
|
||
"id": str(r.id),
|
||
"account": r.account,
|
||
"display_name": r.display_name,
|
||
"organization_name": r.organization_name,
|
||
}
|
||
for r in rows
|
||
]
|
||
)
|
||
|
||
|
||
@router.get("/persons/label")
|
||
def person_labels(
|
||
db: Session = Depends(get_db),
|
||
_: CurrentUser = Depends(current_user),
|
||
values: str = Query(""),
|
||
) -> dict:
|
||
"""一批人员引用 -> 姓名,给只读回显用(详情页、打印页、审批轨迹里那一格选人)。
|
||
|
||
那一格里存的是登录账号,浏览器手上没有人员档案,光拆字符串只能拆出账号本身——
|
||
给人看"DSH Hub Admin"是合格的,给人看"dsh_admin"不是。老单据上还可能存着历史
|
||
身份 DN,所以这里按 :mod:`app.service.personref` 的口径一并认,回包里 ``value``
|
||
原样带回调用方给的那个串,前端照着填缓存。
|
||
|
||
认不出人的(人删了、手写错了)不进结果:前端拿不到就原样显示,不编名字。
|
||
"""
|
||
wanted = [item.strip() for item in str(values or "").split(",") if item.strip()]
|
||
briefs = org.refs_for(db, wanted)
|
||
items = [
|
||
{
|
||
"value": value,
|
||
"account": ref.account,
|
||
"display_name": ref.name,
|
||
"person_name": ref.person_name,
|
||
"unit_name": ref.unit_name,
|
||
}
|
||
for value, ref in ((value, briefs.get(value)) for value in dict.fromkeys(wanted))
|
||
if ref is not None and (ref.account or ref.person_name)
|
||
]
|
||
return ok(items)
|
||
|
||
|
||
@router.get("/persons/roles")
|
||
def person_roles(
|
||
db: Session = Depends(get_db),
|
||
_: CurrentUser = Depends(current_user),
|
||
values: str = Query(""),
|
||
) -> dict:
|
||
"""一批登录账号 -> 各自挂在哪些岗位角色 / 分组下("一个人几个身份"那一问)。
|
||
|
||
人员管理页那一列要一次给一整页的人标出岗位,所以按账号批量问,前端跟姓名缓存
|
||
(``/persons/label``)一样攒一轮再发一次。口径与审批人解析同一套:成员值就是本人
|
||
账号的算直挂名,靠部门 / 别的角色 / 分组绕进来的算间接,认不出的字符串不算人。
|
||
"""
|
||
wanted = [item.strip() for item in str(values or "").split(",") if item.strip()]
|
||
mapping = org.memberships_for(db, wanted)
|
||
return ok(
|
||
[{"value": value, "memberships": mapping.get(value, [])} for value in dict.fromkeys(wanted)]
|
||
)
|
||
|
||
|
||
@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, rows)
|
||
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,
|
||
mobile=schemas.clean_mobile(body.mobile),
|
||
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()
|
||
db.commit()
|
||
return ok(serializers.person(person))
|
||
|
||
|
||
@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.mobile = schemas.clean_mobile(body.mobile)
|
||
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
|
||
db.commit()
|
||
return ok(serializers.person(person))
|
||
|
||
|
||
@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
|
||
# 个人资料里填的收款账户按登录账号挂、没有外键(见 models.BankAccount),删人时顺手清掉:
|
||
# 留着的话这个账号哪天被下一个人认领(或 Hub 拿同号重建),他会凭空继承上一个人的银行卡。
|
||
db.execute(delete(models.BankAccount).where(or_(
|
||
models.BankAccount.account == person.account,
|
||
models.BankAccount.person_id == person.id,
|
||
)))
|
||
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 == 办理人账号来命中,存进去的串对不上人就永远不命中
|
||
identity=_account_or_fail(db, body.identity, field="代理对象"),
|
||
from_identity=user.ref,
|
||
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
|
||
|
||
# 交接是把本人全部待办的归属列直接改写,写进去的串必须认得出是谁:
|
||
# 管理员原本可以填任意字符串,那样待办会从两边列表同时消失、只剩一条谁也接不了的单
|
||
to_account = _account_or_fail(db, body.to_identity, field="交接对象")
|
||
ref = org.ref_for(db, to_account)
|
||
tasks = db.execute(
|
||
select(models.Task).where(models.Task.identity == user.ref)
|
||
).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.ref,
|
||
to_person=ref.person or body.to_person,
|
||
to_person_name=ref.name,
|
||
to_identity=to_account,
|
||
scheme=body.scheme,
|
||
status="executing",
|
||
person=user.person_id,
|
||
)
|
||
db.add(record)
|
||
for task in tasks:
|
||
task.identity = to_account
|
||
task.identity_name = ref.name
|
||
task.person = ref.person or task.person
|
||
task.unit = ref.unit or task.unit
|
||
task.empower_from_identity = user.ref
|
||
engine.notify(
|
||
db,
|
||
[to_account],
|
||
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))
|