feat(admin): 部门管理改造为组织树形结构
This commit is contained in:
1 parent
c5b7cc662b
commit
48fe19ed71
21 files changed
+1086
-234
No files matched your search
@@ -1,56 +1,172 @@
|
||||
"""
|
||||
backend/app/services/admin/department_service.py
|
||||
|
||||
用途:管理端部门 CRUD 业务编排。
|
||||
依赖:models.Department、app.core.errors。
|
||||
逻辑:由 api/admin/departments.py 调用。
|
||||
用途:管理端部门树 CRUD 业务编排(parent_id 邻接表)。
|
||||
依赖:models.Department、models.User、app.core.errors。
|
||||
逻辑:api/admin/departments.py 调用;成员归属沿用 users.department 文本按部门名关联;
|
||||
树顶公司层不入库,由前端按 company 字段虚拟分组。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
from collections import defaultdict
|
||||
from typing import Any, Optional
|
||||
|
||||
from sqlalchemy import func
|
||||
|
||||
from app import db
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.models import Department, User
|
||||
|
||||
# 业务错误码:与前端 locales/*/errors.json 的 codes 段一一对应
|
||||
ERR_NAME_REQUIRED = 'DEPT.NAME_REQUIRED'
|
||||
ERR_PARENT_INVALID = 'DEPT.PARENT_INVALID'
|
||||
ERR_NAME_EXISTS = 'DEPT.NAME_EXISTS'
|
||||
ERR_CODE_EXISTS = 'DEPT.CODE_EXISTS'
|
||||
ERR_CYCLE_FORBIDDEN = 'DEPT.CYCLE_FORBIDDEN'
|
||||
ERR_HAS_CHILDREN = 'DEPT.HAS_CHILDREN'
|
||||
ERR_HAS_MEMBERS = 'DEPT.HAS_MEMBERS'
|
||||
|
||||
|
||||
def serialize_department(dept: Department) -> dict:
|
||||
"""部门 ORM → API dict。"""
|
||||
"""部门 ORM → API dict(平铺行,供部门下拉等旧消费方兼容)。"""
|
||||
return {
|
||||
'id': dept.id,
|
||||
'name': dept.name,
|
||||
'code': dept.code,
|
||||
'company': dept.company,
|
||||
'description': dept.description,
|
||||
'parent_id': dept.parent_id,
|
||||
'sort_order': int(dept.sort_order or 0),
|
||||
'is_hidden': bool(dept.is_hidden),
|
||||
}
|
||||
|
||||
|
||||
def _member_count_by_name() -> dict[str, int]:
|
||||
"""
|
||||
全员按部门名聚合计数。
|
||||
核心逻辑:users.department 为文本字段,一次 GROUP BY 供整棵树复用,避免逐节点查库。
|
||||
"""
|
||||
rows = db.session.query(User.department, func.count(User.id)).group_by(User.department).all()
|
||||
return {name: int(cnt) for name, cnt in rows if name}
|
||||
|
||||
|
||||
def _sibling_sort_key(node: dict) -> tuple:
|
||||
"""同级排序:sort_order 升序 → 编码 → 名称(编码可能为空,排最后)。"""
|
||||
return (node['sort_order'], node['code'] or '', node['name'])
|
||||
|
||||
|
||||
def list_departments() -> list[dict]:
|
||||
"""返回全部部门(按 name 升序)。"""
|
||||
rows = (
|
||||
db.session.query(Department, func.count(User.id).label('member_count'))
|
||||
.outerjoin(User, User.department == Department.name)
|
||||
.group_by(Department.id)
|
||||
.order_by(Department.name.asc())
|
||||
.all()
|
||||
)
|
||||
return [{**serialize_department(dept), 'member_count': int(member_count or 0)} for dept, member_count in rows]
|
||||
"""平铺部门列表(保持旧接口兼容),按公司 → 同级排序号 → 名称排序。"""
|
||||
depts = db.session.query(Department).all()
|
||||
counts = _member_count_by_name()
|
||||
depts.sort(key=lambda d: (d.company or '', d.sort_order or 0, d.code or '', d.name))
|
||||
return [{**serialize_department(d), 'member_count': counts.get(d.name, 0)} for d in depts]
|
||||
|
||||
|
||||
def list_department_members(dept_id: int) -> dict:
|
||||
def list_department_tree() -> list[dict]:
|
||||
"""
|
||||
返回完整部门树(children 嵌套,成员数含下级递归汇总)。
|
||||
|
||||
[STEP 1] 一次取全表部门 + 一次按部门名聚合人数。
|
||||
[STEP 2] 按 parent_id 挂 children;父缺失或成环的脏数据按顶级处理(防御)。
|
||||
[STEP 3] 后序遍历汇总 total_member_count(本部门 + 全部下级)。
|
||||
[STEP 4] 同级按 sort_order → 编码 → 名称排序后输出根节点数组。
|
||||
"""
|
||||
depts = db.session.query(Department).all()
|
||||
counts = _member_count_by_name()
|
||||
dept_by_id = {d.id: d for d in depts}
|
||||
nodes = {
|
||||
d.id: {
|
||||
**serialize_department(d),
|
||||
'member_count': counts.get(d.name, 0),
|
||||
'total_member_count': counts.get(d.name, 0),
|
||||
'children': [],
|
||||
}
|
||||
for d in depts
|
||||
}
|
||||
|
||||
def _is_orphan(d: Department) -> bool:
|
||||
"""父链断裂或成环时按顶级处理,避免历史脏数据导致死循环。"""
|
||||
seen: set[int] = set()
|
||||
cur = d
|
||||
while cur.parent_id:
|
||||
if cur.parent_id not in dept_by_id or cur.parent_id in seen:
|
||||
return True
|
||||
seen.add(cur.parent_id)
|
||||
cur = dept_by_id[cur.parent_id]
|
||||
return False
|
||||
|
||||
roots: list[dict] = []
|
||||
for d in depts:
|
||||
node = nodes[d.id]
|
||||
parent_node = nodes.get(d.parent_id) if d.parent_id else None
|
||||
if parent_node is not None and not _is_orphan(d):
|
||||
parent_node['children'].append(node)
|
||||
else:
|
||||
roots.append(node)
|
||||
|
||||
def _summarize(node: dict) -> int:
|
||||
"""后序汇总:total_member_count = 本部门 + 直接成员数之和(树已去环,可安全递归)。"""
|
||||
total = node['member_count']
|
||||
for child in node['children']:
|
||||
total += _summarize(child)
|
||||
node['total_member_count'] = total
|
||||
return total
|
||||
|
||||
def _sort_level(level: list[dict]) -> None:
|
||||
level.sort(key=_sibling_sort_key)
|
||||
for n in level:
|
||||
_sort_level(n['children'])
|
||||
|
||||
_sort_level(roots)
|
||||
for r in roots:
|
||||
_summarize(r)
|
||||
return roots
|
||||
|
||||
|
||||
def _subtree_departments(root: Department) -> list[Department]:
|
||||
"""收集 root 的全部下级部门(不含 root 自身;BFS,脏数据由 parent_id 存在性保证收敛)。"""
|
||||
depts = db.session.query(Department).all()
|
||||
by_parent: dict[Optional[int], list[Department]] = defaultdict(list)
|
||||
for d in depts:
|
||||
by_parent[d.parent_id].append(d)
|
||||
out: list[Department] = []
|
||||
stack = [root.id]
|
||||
while stack:
|
||||
current = stack.pop()
|
||||
for child in by_parent.get(current, []):
|
||||
out.append(child)
|
||||
stack.append(child.id)
|
||||
return out
|
||||
|
||||
|
||||
def list_department_members(dept_id: int, include_descendants: bool = False) -> dict:
|
||||
"""
|
||||
查询指定部门的员工名单。
|
||||
|
||||
[STEP 1] 通过部门主键读取部门名称。
|
||||
[STEP 2] 复用现有 users.department 文本关联查询成员。
|
||||
[STEP 3] 返回人数与脱敏后的管理端成员资料。
|
||||
[STEP 1] 读取部门;include_descendants=True 时递归收集子树内全部部门名。
|
||||
[STEP 2] 按 users.department 文本 in 部门名集合查询成员。
|
||||
[STEP 3] 返回人数与脱敏后的管理端成员资料(含成员所属部门名,供含下级视图区分)。
|
||||
|
||||
Args:
|
||||
dept_id: 部门主键。
|
||||
include_descendants: 是否包含全部下级部门的成员。
|
||||
Raises:
|
||||
NotFoundError: 部门不存在。
|
||||
"""
|
||||
dept = db.session.get(Department, dept_id)
|
||||
if not dept:
|
||||
raise NotFoundError('Not found')
|
||||
users = db.session.query(User).filter(User.department == dept.name).order_by(User.real_name.asc(), User.username.asc()).all()
|
||||
raise NotFoundError('Department not found')
|
||||
if include_descendants:
|
||||
dept_names = [dept.name] + [d.name for d in _subtree_departments(dept)]
|
||||
else:
|
||||
dept_names = [dept.name]
|
||||
users = (
|
||||
db.session.query(User)
|
||||
.filter(User.department.in_(dept_names))
|
||||
.order_by(User.real_name.asc(), User.username.asc())
|
||||
.all()
|
||||
)
|
||||
return {
|
||||
'department': serialize_department(dept),
|
||||
'count': len(users),
|
||||
@@ -61,6 +177,7 @@ def list_department_members(dept_id: int) -> dict:
|
||||
'real_name': user.real_name,
|
||||
'employee_id': user.employee_id,
|
||||
'email': user.email,
|
||||
'department': user.department,
|
||||
'status': user.status,
|
||||
}
|
||||
for user in users
|
||||
@@ -68,25 +185,95 @@ def list_department_members(dept_id: int) -> dict:
|
||||
}
|
||||
|
||||
|
||||
def _validate_parent(parent_id: Any) -> Optional[Department]:
|
||||
"""校验上级部门存在性;None/空表示顶级。返回上级 ORM 或 None。"""
|
||||
if parent_id in (None, ''):
|
||||
return None
|
||||
parent = db.session.get(Department, int(parent_id))
|
||||
if not parent:
|
||||
raise ValidationError('Parent department not found', code=ERR_PARENT_INVALID)
|
||||
return parent
|
||||
|
||||
|
||||
def _validate_parent_change(dept: Department, new_parent_id: Any) -> Optional[Department]:
|
||||
"""
|
||||
校验修改上级的合法性:上级必须存在,且不能是自己或自己的子孙(防成环)。
|
||||
[STEP 1] 沿新上级逐层向上走。
|
||||
[STEP 2] 途中遇到本部门 id 即说明会把子树挂到自己下面,抛 CYCLE_FORBIDDEN。
|
||||
"""
|
||||
parent = _validate_parent(new_parent_id)
|
||||
if parent is None:
|
||||
return None
|
||||
if parent.id == dept.id:
|
||||
raise ValidationError('Parent cannot be itself or its descendant', code=ERR_CYCLE_FORBIDDEN)
|
||||
seen = {dept.id}
|
||||
cur_id: Optional[int] = parent.parent_id
|
||||
while cur_id:
|
||||
if cur_id in seen:
|
||||
raise ValidationError('Parent cannot be itself or its descendant', code=ERR_CYCLE_FORBIDDEN)
|
||||
seen.add(cur_id)
|
||||
cursor = db.session.get(Department, cur_id)
|
||||
if not cursor:
|
||||
break
|
||||
cur_id = cursor.parent_id
|
||||
return parent
|
||||
|
||||
|
||||
def _validate_sibling_name(name: str, parent_id: Optional[int], exclude_id: Optional[int] = None) -> None:
|
||||
"""同级查重:同一上级下 name 唯一(树形下允许不同分支/公司同名)。"""
|
||||
query = db.session.query(Department).filter(Department.name == name)
|
||||
query = (
|
||||
query.filter(Department.parent_id == parent_id)
|
||||
if parent_id
|
||||
else query.filter(Department.parent_id.is_(None))
|
||||
)
|
||||
if exclude_id:
|
||||
query = query.filter(Department.id != exclude_id)
|
||||
if query.first():
|
||||
raise ValidationError('Sibling department name exists', code=ERR_NAME_EXISTS)
|
||||
|
||||
|
||||
def _clean_str(value: Any) -> str:
|
||||
return (value or '').strip() if isinstance(value, str) else ''
|
||||
|
||||
|
||||
def _clean_int(value: Any) -> int:
|
||||
try:
|
||||
return int(value)
|
||||
except (TypeError, ValueError):
|
||||
return 0
|
||||
|
||||
|
||||
def create_department(data: dict[str, Any]) -> dict:
|
||||
"""
|
||||
创建部门。
|
||||
|
||||
[STEP 1] 校验名称必填、上级存在、同级不重名、编码全局唯一。
|
||||
[STEP 2] 公司未填时继承上级部门 company(树顶公司分组依赖该字段)。
|
||||
|
||||
Returns:
|
||||
{ id, name }。
|
||||
Raises:
|
||||
ValidationError: name 缺失或 name/code 重复。
|
||||
ValidationError: NAME_REQUIRED / PARENT_INVALID / NAME_EXISTS / CODE_EXISTS。
|
||||
"""
|
||||
if not data.get('name'):
|
||||
raise ValidationError('Name is required')
|
||||
if db.session.query(Department).filter_by(name=data['name']).first():
|
||||
raise ValidationError('Name exists')
|
||||
if data.get('code') and db.session.query(Department).filter_by(code=data['code']).first():
|
||||
raise ValidationError('Code exists')
|
||||
name = _clean_str(data.get('name'))
|
||||
if not name:
|
||||
raise ValidationError('Department name is required', code=ERR_NAME_REQUIRED)
|
||||
parent_id = data.get('parent_id')
|
||||
parent = _validate_parent(parent_id)
|
||||
_validate_sibling_name(name, parent.id if parent else None)
|
||||
code = _clean_str(data.get('code')) or None
|
||||
if code and db.session.query(Department).filter_by(code=code).first():
|
||||
raise ValidationError('Department code exists', code=ERR_CODE_EXISTS)
|
||||
company = _clean_str(data.get('company')) or (parent.company if parent else None)
|
||||
dept = Department(
|
||||
name=data['name'],
|
||||
code=data.get('code'),
|
||||
company=data.get('company'),
|
||||
description=data.get('description'),
|
||||
name=name,
|
||||
code=code,
|
||||
company=company,
|
||||
description=_clean_str(data.get('description')) or None,
|
||||
parent_id=parent.id if parent else None,
|
||||
sort_order=_clean_int(data.get('sort_order')),
|
||||
is_hidden=bool(data.get('is_hidden')),
|
||||
)
|
||||
db.session.add(dept)
|
||||
db.session.commit()
|
||||
@@ -95,34 +282,63 @@ def create_department(data: dict[str, Any]) -> dict:
|
||||
|
||||
def update_department(dept_id: int, data: dict[str, Any]) -> None:
|
||||
"""
|
||||
更新部门字段。
|
||||
更新部门字段(含上级转移、同级排序、隐藏标记)。
|
||||
|
||||
[STEP 1] 名称变更时按「变更后的上级」做同级查重。
|
||||
[STEP 2] 上级变更时校验存在性并防成环。
|
||||
[STEP 3] 编码变更时全局唯一校验。
|
||||
|
||||
Raises:
|
||||
NotFoundError: 部门不存在。
|
||||
ValidationError: name/code 与其它记录冲突。
|
||||
ValidationError: NAME_EXISTS / PARENT_INVALID / CYCLE_FORBIDDEN / CODE_EXISTS。
|
||||
"""
|
||||
dept = db.session.get(Department, dept_id)
|
||||
if not dept:
|
||||
raise NotFoundError('Not found')
|
||||
raise NotFoundError('Department not found')
|
||||
|
||||
if 'parent_id' in data:
|
||||
parent = _validate_parent_change(dept, data['parent_id'])
|
||||
dept.parent_id = parent.id if parent else None
|
||||
|
||||
if 'name' in data:
|
||||
if db.session.query(Department).filter(Department.name == data['name'], Department.id != dept_id).first():
|
||||
raise ValidationError('Name exists')
|
||||
dept.name = data['name']
|
||||
name = _clean_str(data.get('name'))
|
||||
if not name:
|
||||
raise ValidationError('Department name is required', code=ERR_NAME_REQUIRED)
|
||||
_validate_sibling_name(name, dept.parent_id, exclude_id=dept_id)
|
||||
dept.name = name
|
||||
|
||||
if 'code' in data:
|
||||
if data['code'] and db.session.query(Department).filter(
|
||||
Department.code == data['code'], Department.id != dept_id
|
||||
code = _clean_str(data.get('code')) or None
|
||||
if code and db.session.query(Department).filter(
|
||||
Department.code == code, Department.id != dept_id
|
||||
).first():
|
||||
raise ValidationError('Code exists')
|
||||
dept.code = data['code']
|
||||
raise ValidationError('Department code exists', code=ERR_CODE_EXISTS)
|
||||
dept.code = code
|
||||
|
||||
if 'company' in data:
|
||||
dept.company = data['company']
|
||||
dept.company = _clean_str(data.get('company')) or None
|
||||
if 'description' in data:
|
||||
dept.description = data['description']
|
||||
dept.description = _clean_str(data.get('description')) or None
|
||||
if 'sort_order' in data:
|
||||
dept.sort_order = _clean_int(data.get('sort_order'))
|
||||
if 'is_hidden' in data:
|
||||
dept.is_hidden = bool(data.get('is_hidden'))
|
||||
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def delete_department(dept_id: int) -> None:
|
||||
"""删除部门(不存在时静默成功)。"""
|
||||
"""
|
||||
删除部门。
|
||||
Raises:
|
||||
ConflictError: 存在下级部门(HAS_CHILDREN)或名下仍有员工(HAS_MEMBERS)时禁止删除。
|
||||
"""
|
||||
dept = db.session.get(Department, dept_id)
|
||||
if dept:
|
||||
db.session.delete(dept)
|
||||
db.session.commit()
|
||||
if not dept:
|
||||
return
|
||||
if db.session.query(Department).filter(Department.parent_id == dept_id).first():
|
||||
raise ConflictError('Department has child departments', code=ERR_HAS_CHILDREN)
|
||||
if db.session.query(User).filter(User.department == dept.name).first():
|
||||
raise ConflictError('Department still has members', code=ERR_HAS_MEMBERS)
|
||||
db.session.delete(dept)
|
||||
db.session.commit()
|
||||
Reference in new issue
Block a user