387 lines
14 KiB
Python
387 lines
14 KiB
Python
"""
|
|
backend/app/services/admin/department_service.py
|
|
|
|
用途:管理端部门树 CRUD 业务编排(parent_id 邻接表)。
|
|
依赖:models.Department、models.User、app.core.errors。
|
|
逻辑:api/admin/departments.py 调用;成员归属沿用 users.department 文本按部门名关联;
|
|
树顶公司层不入库,由前端按 company 字段虚拟分组。
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
from collections import defaultdict
|
|
from typing import Any, Optional
|
|
|
|
from sqlalchemy import func
|
|
|
|
from app import db
|
|
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(平铺行,供部门下拉等旧消费方兼容)。"""
|
|
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]:
|
|
"""平铺部门列表(保持旧接口兼容),按公司 → 同级排序号 → 名称排序。"""
|
|
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_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,
|
|
keyword: str = '',
|
|
page: int = 1,
|
|
page_size: int = 20,
|
|
) -> dict:
|
|
"""
|
|
分页查询部门员工名单(OA 组织结构右侧面板口径)。
|
|
|
|
[STEP 1] 读取部门;include_descendants=True 时递归收集子树内全部部门名。
|
|
[STEP 2] 按 users.department 文本 in 部门名集合过滤,keyword 模糊匹配
|
|
姓名/用户名/工号/邮箱/手机号。
|
|
[STEP 3] 返回 total 与当前页成员资料(含成员所属部门名,供含下级视图区分)。
|
|
|
|
Args:
|
|
dept_id: 部门主键。
|
|
include_descendants: 是否包含全部下级部门的成员(默认 False)。
|
|
keyword: 搜索关键词(姓名/工号/邮箱/手机号/用户名 模糊匹配)。
|
|
page: 页码,从 1 起;非正数按 1 处理。
|
|
page_size: 每页条数,钳制在 1..100。
|
|
Returns:
|
|
{ department, total, page, page_size, members }。
|
|
Raises:
|
|
NotFoundError: 部门不存在。
|
|
"""
|
|
dept = db.session.get(Department, dept_id)
|
|
if not dept:
|
|
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]
|
|
|
|
query = db.session.query(User).filter(User.department.in_(dept_names))
|
|
kw = (keyword or '').strip()
|
|
if kw:
|
|
like = f"%{kw}%"
|
|
query = query.filter(
|
|
db.or_(
|
|
User.real_name.ilike(like),
|
|
User.username.ilike(like),
|
|
User.employee_id.ilike(like),
|
|
User.email.ilike(like),
|
|
User.phone_number.ilike(like),
|
|
)
|
|
)
|
|
total = query.count()
|
|
page = max(int(page or 1), 1)
|
|
page_size = min(max(int(page_size or 20), 1), 100)
|
|
users = (
|
|
query.order_by(User.real_name.asc(), User.username.asc())
|
|
.offset((page - 1) * page_size)
|
|
.limit(page_size)
|
|
.all()
|
|
)
|
|
return {
|
|
'department': serialize_department(dept),
|
|
'total': total,
|
|
'page': page,
|
|
'page_size': page_size,
|
|
'members': [
|
|
{
|
|
'id': user.id,
|
|
'username': user.username,
|
|
'real_name': user.real_name,
|
|
'employee_id': user.employee_id,
|
|
'email': user.email,
|
|
'phone_number': user.phone_number,
|
|
'department': user.department,
|
|
'status': user.status,
|
|
}
|
|
for user in users
|
|
],
|
|
}
|
|
|
|
|
|
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],
|
|
company: Optional[str] = None,
|
|
exclude_id: Optional[int] = None,
|
|
) -> None:
|
|
"""
|
|
同级查重:同一上级下 name 唯一(树形下允许不同分支同名)。
|
|
顶级部门(parent_id 为空)按 company 分桶查重——树顶公司层为虚拟分组,
|
|
两家公司的顶级部门允许同名(如各公司均有「管理部」)。
|
|
"""
|
|
query = db.session.query(Department).filter(Department.name == name)
|
|
if parent_id:
|
|
query = query.filter(Department.parent_id == parent_id)
|
|
else:
|
|
query = query.filter(Department.parent_id.is_(None))
|
|
query = query.filter(Department.company == company) if company else query.filter(Department.company.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_REQUIRED / PARENT_INVALID / NAME_EXISTS / 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)
|
|
company = _clean_str(data.get('company')) or (parent.company if parent else None)
|
|
_validate_sibling_name(name, parent.id if parent else None, company=company)
|
|
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)
|
|
dept = Department(
|
|
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()
|
|
return {'id': dept.id, 'name': dept.name}
|
|
|
|
|
|
def update_department(dept_id: int, data: dict[str, Any]) -> None:
|
|
"""
|
|
更新部门字段(含上级转移、同级排序、隐藏标记)。
|
|
|
|
[STEP 1] 名称变更时按「变更后的上级」做同级查重。
|
|
[STEP 2] 上级变更时校验存在性并防成环。
|
|
[STEP 3] 编码变更时全局唯一校验。
|
|
|
|
Raises:
|
|
NotFoundError: 部门不存在。
|
|
ValidationError: NAME_EXISTS / PARENT_INVALID / CYCLE_FORBIDDEN / CODE_EXISTS。
|
|
"""
|
|
dept = db.session.get(Department, dept_id)
|
|
if not dept:
|
|
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 'company' in data:
|
|
dept.company = _clean_str(data.get('company')) or None
|
|
|
|
if 'name' in data:
|
|
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, company=dept.company, exclude_id=dept_id)
|
|
dept.name = name
|
|
|
|
if 'code' in data:
|
|
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('Department code exists', code=ERR_CODE_EXISTS)
|
|
dept.code = code
|
|
|
|
if 'description' in data:
|
|
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 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()
|