feat(admin): 部门管理改造为组织树形结构
This commit is contained in:
1 parent
c5b7cc662b
commit
48fe19ed71
21 files changed
+1086
-234
No files matched your search
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
backend/app/api/admin/departments.py
|
||||
|
||||
用途:管理后台部门 CRUD API(薄路由层)。
|
||||
用途:管理后台部门 CRUD API(薄路由层,树形结构)。
|
||||
依赖:admin.blueprint、services/admin/department_service。
|
||||
逻辑:/departments* 路由。
|
||||
逻辑:/departments 平铺列表(兼容旧消费方)、/departments/tree 树、成员名单(支持含下级)。
|
||||
"""
|
||||
from flask import jsonify, request
|
||||
|
||||
@@ -15,10 +15,17 @@ from app.services.admin import department_service
|
||||
@admin_bp.route('/departments', methods=['GET'])
|
||||
@require_admin
|
||||
def list_departments():
|
||||
"""返回全部部门列表。"""
|
||||
"""返回全部部门平铺列表(旧消费方兼容:部门下拉等)。"""
|
||||
return jsonify(department_service.list_departments())
|
||||
|
||||
|
||||
@admin_bp.route('/departments/tree', methods=['GET'])
|
||||
@require_admin
|
||||
def department_tree():
|
||||
"""返回完整部门树(children 嵌套,成员数含下级递归汇总)。"""
|
||||
return jsonify(department_service.list_department_tree())
|
||||
|
||||
|
||||
@admin_bp.route('/departments', methods=['POST'])
|
||||
@require_admin
|
||||
def create_department():
|
||||
@@ -31,8 +38,9 @@ def create_department():
|
||||
@admin_bp.route('/departments/<int:id>/members', methods=['GET'])
|
||||
@require_admin
|
||||
def list_department_members(id: int):
|
||||
"""返回部门员工数量与名单。"""
|
||||
return jsonify(department_service.list_department_members(id))
|
||||
"""返回部门员工数量与名单;include_descendants=1 时含全部下级部门成员。"""
|
||||
include_descendants = request.args.get('include_descendants', '') in ('1', 'true')
|
||||
return jsonify(department_service.list_department_members(id, include_descendants))
|
||||
|
||||
|
||||
@admin_bp.route('/departments/<int:id>', methods=['PUT'])
|
||||
|
||||
@@ -1,27 +1,40 @@
|
||||
"""
|
||||
backend/app/models/department.py
|
||||
|
||||
用途:部门组织模型。
|
||||
用途:部门组织模型(parent_id 邻接表树形结构,对应 OA 组织架构)。
|
||||
依赖:models.base.Base。
|
||||
逻辑:parent_id 自关联构成部门树;sort_order 为同级排序(对应 ERP HRAO hrao09 阶层序号),
|
||||
is_hidden 对应 hrao08「在组织框架图中显示否」。树的组装与校验在 services/admin/department_service。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import String, Text
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
from sqlalchemy import Boolean, ForeignKey, String, Text
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class Department(Base):
|
||||
"""部门表:存储公司部门列表。"""
|
||||
"""部门表:存储公司部门树(parent_id 邻接表)。"""
|
||||
|
||||
__tablename__ = 'departments'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
name: Mapped[str] = mapped_column(String(100), unique=True)
|
||||
# 树形结构下 name 仅要求「同一上级下不重名」(由 department_service 校验),不再全局唯一,
|
||||
# 以支持多公司存在同名部门(如各公司均有「管理部」)。
|
||||
name: Mapped[str] = mapped_column(String(100))
|
||||
code: Mapped[Optional[str]] = mapped_column(String(50), unique=True)
|
||||
company: Mapped[Optional[str]] = mapped_column(String(100))
|
||||
description: Mapped[Optional[str]] = mapped_column(Text)
|
||||
# 上级部门主键;None 表示顶级部门(树顶公司层由前端按 company 字段虚拟分组,不入库)
|
||||
parent_id: Mapped[Optional[int]] = mapped_column(ForeignKey('departments.id'), nullable=True)
|
||||
# 同级排序号(升序),对应 ERP hrao09 部门阶层序号
|
||||
sort_order: Mapped[int] = mapped_column(default=0, server_default='0', nullable=False)
|
||||
# 是否在组织树中隐藏(对应 ERP hrao08「在组织框架图中显示否」;管理端仍可见并打标)
|
||||
is_hidden: Mapped[bool] = mapped_column(Boolean, default=False, server_default='false', nullable=False)
|
||||
|
||||
# 上级部门;children 由 backref 提供,供 service 组装树
|
||||
parent: Mapped[Optional['Department']] = relationship(remote_side=[id], backref='children')
|
||||
@@ -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()
|
||||
@@ -0,0 +1,100 @@
|
||||
"""Add department tree columns
|
||||
|
||||
Revision ID: dp1a2b3c4d5e6
|
||||
Revises: 9e5045511198
|
||||
Create Date: 2026-10-08 10:00:00.000000
|
||||
|
||||
用途:departments 表升级为树形结构(parent_id 邻接表 + 同级排序 + 隐藏标记),
|
||||
并放开 name 全局唯一约束(多公司允许同名部门,改由 service 层做同级查重)。
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'dp1a2b3c4d5e6'
|
||||
down_revision = '9e5045511198'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
conn = op.get_bind()
|
||||
insp = sa.inspect(conn)
|
||||
tables = set(insp.get_table_names())
|
||||
|
||||
if 'departments' not in tables:
|
||||
# 防御:空库直接按新结构建表
|
||||
op.create_table(
|
||||
'departments',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('name', sa.String(length=100), nullable=False),
|
||||
sa.Column('code', sa.String(length=50), nullable=True),
|
||||
sa.Column('company', sa.String(length=100), nullable=True),
|
||||
sa.Column('description', sa.Text(), nullable=True),
|
||||
sa.Column('parent_id', sa.Integer(), nullable=True),
|
||||
sa.Column('sort_order', sa.Integer(), nullable=False, server_default='0'),
|
||||
sa.Column('is_hidden', sa.Boolean(), nullable=False, server_default=sa.false()),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
sa.UniqueConstraint('code'),
|
||||
sa.ForeignKeyConstraint(
|
||||
['parent_id'], ['departments.id'], name='fk_departments_parent_id_departments'
|
||||
),
|
||||
)
|
||||
return
|
||||
|
||||
cols = {c['name'] for c in insp.get_columns('departments')}
|
||||
with op.batch_alter_table('departments', schema=None) as batch_op:
|
||||
if 'parent_id' not in cols:
|
||||
batch_op.add_column(sa.Column('parent_id', sa.Integer(), nullable=True))
|
||||
if 'sort_order' not in cols:
|
||||
batch_op.add_column(sa.Column('sort_order', sa.Integer(), nullable=False, server_default='0'))
|
||||
if 'is_hidden' not in cols:
|
||||
batch_op.add_column(sa.Column('is_hidden', sa.Boolean(), nullable=False, server_default=sa.false()))
|
||||
|
||||
# 重新内省后再补自关联外键(列可能由上一步刚添加)
|
||||
insp2 = sa.inspect(conn)
|
||||
fks = insp2.get_foreign_keys('departments')
|
||||
has_parent_fk = any(
|
||||
'parent_id' in (fk.get('constrained_columns') or []) for fk in fks
|
||||
)
|
||||
if not has_parent_fk:
|
||||
op.create_foreign_key(
|
||||
'fk_departments_parent_id_departments', 'departments', 'departments',
|
||||
['parent_id'], ['id'],
|
||||
)
|
||||
|
||||
# 放开 name 全局唯一:删除覆盖 name 列的 unique 约束(同名约束名在不同库不一致,按列名探测)
|
||||
name_uq_names = [
|
||||
uq['name'] for uq in insp2.get_unique_constraints('departments')
|
||||
if set(uq.get('column_names') or []) == {'name'} and uq.get('name')
|
||||
]
|
||||
if name_uq_names:
|
||||
with op.batch_alter_table('departments', schema=None) as batch_op:
|
||||
for uq_name in name_uq_names:
|
||||
batch_op.drop_constraint(uq_name, type_='unique')
|
||||
|
||||
|
||||
def downgrade():
|
||||
conn = op.get_bind()
|
||||
insp = sa.inspect(conn)
|
||||
if 'departments' not in set(insp.get_table_names()):
|
||||
return
|
||||
|
||||
cols = {c['name'] for c in insp.get_columns('departments')}
|
||||
with op.batch_alter_table('departments', schema=None) as batch_op:
|
||||
if 'is_hidden' in cols:
|
||||
batch_op.drop_column('is_hidden')
|
||||
if 'sort_order' in cols:
|
||||
batch_op.drop_column('sort_order')
|
||||
if 'parent_id' in cols:
|
||||
try:
|
||||
batch_op.drop_constraint('fk_departments_parent_id_departments', type_='foreignkey')
|
||||
except Exception:
|
||||
pass
|
||||
batch_op.drop_column('parent_id')
|
||||
# 恢复 name 全局唯一;若历史数据存在重名会失败,需先清洗数据
|
||||
try:
|
||||
batch_op.create_unique_constraint('uq_departments_name', ['name'])
|
||||
except Exception:
|
||||
pass
|
||||
@@ -1,45 +1,138 @@
|
||||
"""
|
||||
tests/services/admin/test_department_service.py
|
||||
|
||||
用途:department_service CRUD 单元测试。
|
||||
用途:department_service 部门树 CRUD、树组装、成员口径单元测试。
|
||||
覆盖:父子挂接 / 同级查重 / 编码唯一 / 防成环 / 删除保护(有下级、有员工)/ 成员数含下级汇总。
|
||||
"""
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.models import Department
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.models import Department, User
|
||||
from app.services.admin.department_service import (
|
||||
create_department,
|
||||
delete_department,
|
||||
list_department_members,
|
||||
list_department_tree,
|
||||
list_departments,
|
||||
update_department,
|
||||
)
|
||||
|
||||
|
||||
def test_department_crud(app):
|
||||
def test_department_crud_with_parent(app):
|
||||
"""断言:父子挂接进树、字段可更新、有下级禁删、无下级可删。"""
|
||||
with app.app_context():
|
||||
created = create_department({'name': 'R&D', 'code': 'RD', 'company': 'HX'})
|
||||
assert created['name'] == 'R&D'
|
||||
parent = create_department({'name': '品保部', 'code': 'QA', 'company': 'HX'})
|
||||
child = create_department({'name': '品保课', 'code': 'QA1', 'parent_id': parent['id'], 'sort_order': 2})
|
||||
assert child['name'] == '品保课'
|
||||
|
||||
items = list_departments()
|
||||
assert any(item['code'] == 'RD' for item in items)
|
||||
assert any(item['code'] == 'QA1' and item['parent_id'] == parent['id'] for item in items)
|
||||
|
||||
update_department(created['id'], {'description': 'Research'})
|
||||
dept = db.session.get(Department, created['id'])
|
||||
assert dept.description == 'Research'
|
||||
update_department(child['id'], {'sort_order': 9, 'is_hidden': True})
|
||||
dept = db.session.get(Department, child['id'])
|
||||
assert dept.sort_order == 9
|
||||
assert dept.is_hidden is True
|
||||
|
||||
delete_department(created['id'])
|
||||
assert db.session.get(Department, created['id']) is None
|
||||
# 分支测试意图:存在下级部门时删除必须被 HAS_CHILDREN 拦截
|
||||
with pytest.raises(ConflictError, match='child'):
|
||||
delete_department(parent['id'])
|
||||
delete_department(child['id'])
|
||||
delete_department(parent['id'])
|
||||
assert db.session.get(Department, parent['id']) is None
|
||||
|
||||
|
||||
def test_create_department_rejects_duplicate_name(app):
|
||||
def test_create_department_rejects_same_parent_duplicate_name(app):
|
||||
"""断言:同一上级下同名部门被拒(同级查重)。"""
|
||||
with app.app_context():
|
||||
create_department({'name': 'Sales'})
|
||||
with pytest.raises(ValidationError, match='Name exists'):
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
create_department({'name': 'Sales'})
|
||||
# 断言业务错误码而非消息文本(str(exc) 仅含 message,不含 code)
|
||||
assert exc_info.value.code == 'DEPT.NAME_EXISTS'
|
||||
|
||||
|
||||
def test_create_department_allows_same_name_under_different_parents(app):
|
||||
"""断言:不同分支(多公司)允许同名部门——name 全局唯一已放开。"""
|
||||
with app.app_context():
|
||||
root_a = create_department({'name': '和信', 'company': '和信'})
|
||||
root_b = create_department({'name': '泰国合欣', 'company': '泰国合欣'})
|
||||
create_department({'name': '管理部', 'parent_id': root_a['id']})
|
||||
create_department({'name': '管理部', 'parent_id': root_b['id']})
|
||||
tree = list_department_tree()
|
||||
assert len(tree) == 2
|
||||
assert all(len([c for c in root['children'] if c['name'] == '管理部']) == 1 for root in tree)
|
||||
|
||||
|
||||
def test_create_department_inherits_company_from_parent(app):
|
||||
"""断言:未填公司时继承上级部门 company(公司虚拟分组依赖)。"""
|
||||
with app.app_context():
|
||||
root = create_department({'name': '和信', 'company': '苏州和信'})
|
||||
child = create_department({'name': '财务部', 'parent_id': root['id']})
|
||||
dept = db.session.get(Department, child['id'])
|
||||
assert dept.company == '苏州和信'
|
||||
|
||||
|
||||
def test_create_department_rejects_duplicate_code(app):
|
||||
"""断言:部门编码全局唯一。"""
|
||||
with app.app_context():
|
||||
create_department({'name': 'A', 'code': 'C1'})
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
create_department({'name': 'B', 'code': 'C1'})
|
||||
assert exc_info.value.code == 'DEPT.CODE_EXISTS'
|
||||
|
||||
|
||||
def test_update_parent_cycle_rejected(app):
|
||||
"""分支测试意图:把部门挂到自己或自己的子孙下必须被 CYCLE_FORBIDDEN 拦截。"""
|
||||
with app.app_context():
|
||||
root = create_department({'name': 'Root'})
|
||||
child = create_department({'name': 'Child', 'parent_id': root['id']})
|
||||
grand = create_department({'name': 'Grand', 'parent_id': child['id']})
|
||||
assert grand['name'] == 'Grand'
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
update_department(root['id'], {'parent_id': grand['id']})
|
||||
assert exc_info.value.code == 'DEPT.CYCLE_FORBIDDEN'
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
update_department(root['id'], {'parent_id': root['id']})
|
||||
assert exc_info.value.code == 'DEPT.CYCLE_FORBIDDEN'
|
||||
|
||||
|
||||
def test_update_department_not_found(app):
|
||||
with app.app_context():
|
||||
with pytest.raises(NotFoundError):
|
||||
update_department(99999, {'name': 'X'})
|
||||
|
||||
|
||||
def test_delete_department_with_members_rejected(app):
|
||||
"""断言:名下仍有员工(users.department 文本命中)时删除被 HAS_MEMBERS 拦截。"""
|
||||
with app.app_context():
|
||||
dept = create_department({'name': '品保部'})
|
||||
db.session.add(User(username='u1', email='u1@example.com', department='品保部', role='user', status='active'))
|
||||
db.session.commit()
|
||||
with pytest.raises(ConflictError, match='members'):
|
||||
delete_department(dept['id'])
|
||||
|
||||
|
||||
def test_member_count_tree_rollup_and_members_scope(app):
|
||||
"""断言:树节点 member_count 为直属人数、total_member_count 递归含下级;成员接口按口径过滤。"""
|
||||
with app.app_context():
|
||||
root = create_department({'name': '物料部'})
|
||||
child = create_department({'name': '仓储课', 'parent_id': root['id']})
|
||||
db.session.add_all([
|
||||
User(username='r1', email='r1@example.com', department='物料部', role='user', status='active'),
|
||||
User(username='c1', email='c1@example.com', department='仓储课', role='user', status='active'),
|
||||
User(username='c2', email='c2@example.com', department='仓储课', role='user', status='active'),
|
||||
])
|
||||
db.session.commit()
|
||||
|
||||
tree = list_department_tree()
|
||||
node = tree[0]
|
||||
assert node['member_count'] == 1
|
||||
assert node['total_member_count'] == 3
|
||||
assert node['children'][0]['total_member_count'] == 2
|
||||
|
||||
direct = list_department_members(child['id'])
|
||||
assert direct['count'] == 2
|
||||
subtree = list_department_members(root['id'], include_descendants=True)
|
||||
assert subtree['count'] == 3
|
||||
assert all(member.get('department') in ('物料部', '仓储课') for member in subtree['members'])
|
||||
@@ -656,6 +656,7 @@
|
||||
| 管理端运营总览 | 「数据报表」新增「运营总览」入口:展示对话量/活跃用户/活跃应用/好评率、对话趋势与环比、Top 应用与低使用应用、低评分回答与未处理反馈,复用 chat_logs/feedbacks/general_feedbacks/agents/应用授权数据 | 已实现(数据处理) | P1 |
|
||||
| 管理端问题分析 | 「数据报表」新增「问题分析」入口,第一版为页面骨架与空状态,不伪造数据 | 已实现(骨架) | P2 |
|
||||
| 管理端时间范围统一 | 「数据报表」各数据页时间范围筛选器统一为「近 7 天 / 30 天 / 90 天」,并同步四语言文案 | 已实现 | P1 |
|
||||
| 管理端部门管理(组织树) | 部门管理改为树形组织结构(对应 OA 组织架构,层级来源对齐 ERP HRAO:hrao01 编码 / hrao02 名称 / hrao06 上级 / hrao09 同级排序 / hrao08 隐藏标记):`departments` 表增加 `parent_id`(邻接表)/ `sort_order` / `is_hidden`(迁移 `dp1a2b3c4d5e6`),`name` 全局唯一放开为「同一上级下唯一」;页面为树形表格,树顶公司层为前端按 `company` 字段虚拟分组不入库;节点支持添加子部门/编辑/删除(有下级或有员工禁删)、搜索命中自动展开、全部展开/收起;员工数与成员名单支持「含下级部门」递归口径;新增错误码 `DEPT.*` 四语言。ERP 数据一次性导入脚本与持续同步本期未做,部门数据继续管理端手工维护 | 已实现 | P1 |
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -576,10 +576,11 @@ export const updateAdminUserPermissions = (userId: number, agentIds: number[]) =
|
||||
body: JSON.stringify({ agent_ids: agentIds }),
|
||||
});
|
||||
|
||||
// Departments
|
||||
// Departments(树形结构:/tree 返回 children 嵌套,成员支持含下级)
|
||||
export const listAdminDepartments = () => requestJson<any[]>('/api/admin/departments', auth());
|
||||
export const listAdminDepartmentMembers = (id: number) =>
|
||||
requestJson(`/api/admin/departments/${id}/members`, auth());
|
||||
export const listAdminDepartmentTree = () => requestJson<any[]>('/api/admin/departments/tree', auth());
|
||||
export const listAdminDepartmentMembers = (id: number, includeDescendants = false) =>
|
||||
requestJson(`/api/admin/departments/${id}/members${includeDescendants ? '?include_descendants=1' : ''}`, auth());
|
||||
export const createAdminDepartment = (payload: Record<string, unknown>) =>
|
||||
requestJson('/api/admin/departments', { method: 'POST', ...jsonAuth(), body: JSON.stringify(payload) });
|
||||
export const updateAdminDepartment = (id: number, payload: Record<string, unknown>) =>
|
||||
|
||||
@@ -1,40 +1,56 @@
|
||||
/**
|
||||
* features/admin/modules/departments/DepartmentsPage.vue
|
||||
* 用途:部门管理独立页面——全宽表格列表 + 列排序 + 创建/编辑居中弹窗。
|
||||
* 依赖:useDepartmentsAdmin、SortableTableHeader、DepartmentFormModal、DeleteConfirmDialog。
|
||||
* 逻辑:路由 /admin/departments;表头排序复用 shared SortableTableHeader + useTableSort。
|
||||
* 用途:部门管理独立页面——树形表格(公司虚拟分组 + 部门层级缩进展开)+ 搜索 + 创建/编辑弹窗。
|
||||
* 依赖:useDepartmentsAdmin、DepartmentFormModal、DepartmentMembersModal、DeleteConfirmDialog。
|
||||
* 逻辑:路由 /admin/departments;数据来自 /admin/departments/tree;公司层为前端按 company 字段虚拟分组。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { Edit, Plus, Search, Trash2, Users } from 'lucide-vue-next';
|
||||
import {
|
||||
Building2,
|
||||
ChevronDown,
|
||||
ChevronRight,
|
||||
Edit,
|
||||
EyeOff,
|
||||
FolderPlus,
|
||||
ListTree,
|
||||
Plus,
|
||||
Search,
|
||||
Trash2,
|
||||
Users,
|
||||
} from 'lucide-vue-next';
|
||||
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
|
||||
import SortableTableHeader from '@/shared/components/SortableTableHeader.vue';
|
||||
import DepartmentFormModal from './components/DepartmentFormModal.vue';
|
||||
import DepartmentMembersModal from './components/DepartmentMembersModal.vue';
|
||||
import { useDepartmentsAdmin } from './composables/useDepartmentsAdmin';
|
||||
import { listAdminDepartmentMembers } from '@/features/admin/api/admin.api';
|
||||
import type { AdminDepartmentMembersResponse } from '@/features/admin/types/admin.types';
|
||||
import type { AdminDepartmentMembersResponse, AdminDepartmentTreeNode } from '@/features/admin/types/admin.types';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
|
||||
const { t } = useI18n();
|
||||
const msg = useMessage();
|
||||
const showMembersModal = ref(false);
|
||||
const departmentMembers = ref<AdminDepartmentMembersResponse | null>(null);
|
||||
/** 成员弹窗当前部门 id 与「含下级」开关 */
|
||||
const membersDeptId = ref<number | null>(null);
|
||||
const includeDescendants = ref(false);
|
||||
|
||||
const {
|
||||
filteredDepartments,
|
||||
displayRows,
|
||||
parentOptions,
|
||||
form,
|
||||
searchQuery,
|
||||
sortKey,
|
||||
sortDir,
|
||||
isLoading,
|
||||
isSaving,
|
||||
showFormModal,
|
||||
showDeleteConfirmDialog,
|
||||
deleteConfirmMessage,
|
||||
loadAll,
|
||||
toggleSort,
|
||||
toggleNode,
|
||||
toggleCompany,
|
||||
expandAll,
|
||||
collapseAll,
|
||||
openCreateModal,
|
||||
openEditModal,
|
||||
closeFormModal,
|
||||
@@ -48,15 +64,29 @@ onMounted(() => {
|
||||
void loadAll();
|
||||
});
|
||||
|
||||
/** 加载并展示指定部门的员工名单。 */
|
||||
const openDepartmentMembers = async (departmentId: number): Promise<void> => {
|
||||
/** 加载并展示指定部门的员工名单(includeDescendants 控制是否含下级)。 */
|
||||
const openDepartmentMembers = async (departmentId: number, include = false): Promise<void> => {
|
||||
try {
|
||||
departmentMembers.value = await listAdminDepartmentMembers(departmentId) as AdminDepartmentMembersResponse;
|
||||
membersDeptId.value = departmentId;
|
||||
includeDescendants.value = include;
|
||||
departmentMembers.value = await listAdminDepartmentMembers(
|
||||
departmentId,
|
||||
include,
|
||||
) as AdminDepartmentMembersResponse;
|
||||
showMembersModal.value = true;
|
||||
} catch (error) {
|
||||
msg.error((error as Error).message || t('admin.msg.requestFailed'));
|
||||
}
|
||||
};
|
||||
|
||||
/** 切换成员弹窗「含下级部门」口径并重新拉取名单。 */
|
||||
const toggleIncludeDescendants = (value: boolean): void => {
|
||||
if (membersDeptId.value == null) return;
|
||||
void openDepartmentMembers(membersDeptId.value, value);
|
||||
};
|
||||
|
||||
/** 公司虚拟分组行 key 去前缀,得到分组 key(用于展开状态)。 */
|
||||
const companyGroupKey = (rowKey: string): string => rowKey.slice('company:'.length);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -74,7 +104,7 @@ const openDepartmentMembers = async (departmentId: number): Promise<void> => {
|
||||
<button
|
||||
type="button"
|
||||
class="flex items-center gap-2 px-4 py-2 bg-brand-600 text-white rounded-xl hover:bg-brand-700 transition-all shadow-lg shadow-brand-200 active:scale-95 text-sm font-medium"
|
||||
@click="openCreateModal"
|
||||
@click="openCreateModal()"
|
||||
>
|
||||
<Plus class="w-4 h-4" />
|
||||
<span>{{ t('admin.dept.add') }}</span>
|
||||
@@ -91,103 +121,159 @@ const openDepartmentMembers = async (departmentId: number): Promise<void> => {
|
||||
:placeholder="t('admin.dept.searchPlaceholder')"
|
||||
/>
|
||||
</div>
|
||||
<div class="flex items-center gap-1">
|
||||
<button
|
||||
type="button"
|
||||
class="p-2 text-muted hover:text-primary hover:bg-subtle rounded-lg transition-colors"
|
||||
:title="t('admin.dept.expandAll')"
|
||||
@click="expandAll"
|
||||
><ListTree class="w-4 h-4" /></button>
|
||||
<button
|
||||
type="button"
|
||||
class="p-2 text-muted hover:text-primary hover:bg-subtle rounded-lg transition-colors"
|
||||
:title="t('admin.dept.collapseAll')"
|
||||
@click="collapseAll"
|
||||
><ChevronDown class="w-4 h-4" /></button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="admin-table-wrap">
|
||||
<!-- 列宽:名称 / 编码 / 公司 / 员工 / 操作 -->
|
||||
<!-- 列宽:名称(树)/ 编码 / 公司 / 员工 / 操作 -->
|
||||
<table class="admin-table table-fixed">
|
||||
<colgroup>
|
||||
<col class="w-[25%]" />
|
||||
<col class="w-[20%]" />
|
||||
<col class="w-[30%]" />
|
||||
<col class="w-[40%]" />
|
||||
<col class="w-[14%]" />
|
||||
<col class="w-[19%]" />
|
||||
<col class="w-[12%]" />
|
||||
<col class="w-[13%]" />
|
||||
<col class="w-[15%]" />
|
||||
</colgroup>
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="px-6 py-4 text-left text-xs">
|
||||
<SortableTableHeader
|
||||
column-key="name"
|
||||
:label="t('admin.dept.headers.name')"
|
||||
:active-key="sortKey"
|
||||
:direction="sortDir"
|
||||
@sort="toggleSort"
|
||||
/>
|
||||
</th>
|
||||
<th class="px-6 py-4 text-left text-xs">
|
||||
<SortableTableHeader
|
||||
column-key="code"
|
||||
:label="t('admin.dept.headers.code')"
|
||||
:active-key="sortKey"
|
||||
:direction="sortDir"
|
||||
@sort="toggleSort"
|
||||
/>
|
||||
</th>
|
||||
<th class="px-6 py-4 text-left text-xs">
|
||||
<SortableTableHeader
|
||||
column-key="company"
|
||||
:label="t('admin.dept.headers.company')"
|
||||
:active-key="sortKey"
|
||||
:direction="sortDir"
|
||||
@sort="toggleSort"
|
||||
/>
|
||||
</th>
|
||||
<th class="px-6 py-4 text-left text-xs">{{ t('admin.dept.headers.name') }}</th>
|
||||
<th class="px-6 py-4 text-left text-xs">{{ t('admin.dept.headers.code') }}</th>
|
||||
<th class="px-6 py-4 text-left text-xs">{{ t('admin.dept.headers.company') }}</th>
|
||||
<th class="px-6 py-4 text-center text-xs">{{ t('admin.dept.headers.members') }}</th>
|
||||
<th class="px-6 py-4 text-right text-xs">{{ t('admin.dept.headers.actions') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-if="filteredDepartments.length === 0">
|
||||
<tr v-if="displayRows.length === 0">
|
||||
<td colspan="5" class="px-6 admin-table-empty">
|
||||
{{ searchQuery.trim() ? t('admin.dept.noSearchResults') : t('admin.dept.noDepts') }}
|
||||
</td>
|
||||
</tr>
|
||||
<tr v-for="d in filteredDepartments" :key="d.id" class="group">
|
||||
<td class="px-6 py-4">
|
||||
<div class="font-medium text-primary text-sm truncate" :title="d.name">{{ d.name }}</div>
|
||||
<div
|
||||
v-if="d.description"
|
||||
class="text-xs text-muted truncate mt-0.5"
|
||||
:title="d.description"
|
||||
>
|
||||
{{ d.description }}
|
||||
</div>
|
||||
</td>
|
||||
<td class="px-6 py-4 text-sm text-muted font-mono whitespace-nowrap truncate" :title="d.code || '-'">
|
||||
{{ d.code || '-' }}
|
||||
</td>
|
||||
<td class="px-6 py-4 text-sm text-muted truncate" :title="d.company || '-'">
|
||||
{{ d.company || '-' }}
|
||||
</td>
|
||||
<td class="px-6 py-4 text-center">
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex items-center justify-center rounded-lg bg-blue-50 p-2 text-blue-600 hover:bg-blue-100"
|
||||
:title="t('admin.dept.actions.viewMembers')"
|
||||
@click="openDepartmentMembers(d.id)"
|
||||
><Users class="w-5 h-5" /><span class="ml-1 text-xs">{{ d.member_count || 0 }}</span></button>
|
||||
</td>
|
||||
<td class="px-6 py-4">
|
||||
<div class="flex justify-end gap-1">
|
||||
<template v-for="row in displayRows" :key="row.key">
|
||||
<!-- 公司虚拟分组行(不入库,前端按 company 字段归堆) -->
|
||||
<tr v-if="row.kind === 'company'" class="bg-subtle/40 cursor-pointer select-none" @click="toggleCompany(companyGroupKey(row.key))">
|
||||
<td class="px-6 py-3">
|
||||
<div class="flex items-center gap-2">
|
||||
<component
|
||||
:is="row.expanded ? ChevronDown : ChevronRight"
|
||||
class="w-4 h-4 text-muted shrink-0"
|
||||
/>
|
||||
<Building2 class="w-4 h-4 text-brand-600 shrink-0" />
|
||||
<span class="font-semibold text-primary text-sm truncate" :title="row.company">{{ row.company }}</span>
|
||||
</div>
|
||||
</td>
|
||||
<td class="px-6 py-3 text-xs text-muted">—</td>
|
||||
<td class="px-6 py-3 text-xs text-muted">
|
||||
<span class="inline-flex items-center px-2 py-0.5 rounded-full bg-brand-50 text-brand-700">{{ t('admin.dept.headers.company') }}</span>
|
||||
</td>
|
||||
<td class="px-6 py-3 text-center">
|
||||
<span class="inline-flex items-center text-sm text-muted" :title="t('admin.dept.members.countTitle', { count: row.totalMembers })">
|
||||
<Users class="w-4 h-4 mr-1" />{{ row.totalMembers }}
|
||||
</span>
|
||||
</td>
|
||||
<td class="px-6 py-3">
|
||||
<div class="flex justify-end">
|
||||
<button
|
||||
type="button"
|
||||
class="p-1.5 text-indigo-600 hover:bg-indigo-50 rounded-lg transition-colors"
|
||||
:title="t('admin.dept.addChild')"
|
||||
@click.stop="openCreateModal(null, row.company)"
|
||||
>
|
||||
<FolderPlus class="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
<!-- 部门行(层级缩进) -->
|
||||
<tr v-else class="group">
|
||||
<td class="px-6 py-4">
|
||||
<div
|
||||
class="flex items-center gap-2 min-w-0"
|
||||
:style="{ paddingLeft: `${(row.depth - 1) * 20}px` }"
|
||||
>
|
||||
<button
|
||||
v-if="row.hasChildren"
|
||||
type="button"
|
||||
class="p-0.5 text-muted hover:text-primary rounded transition-colors shrink-0"
|
||||
:title="row.expanded ? t('admin.dept.collapse') : t('admin.dept.expand')"
|
||||
@click="toggleNode(row.node!.id)"
|
||||
>
|
||||
<component :is="row.expanded ? ChevronDown : ChevronRight" class="w-4 h-4" />
|
||||
</button>
|
||||
<span v-else class="w-5 h-5 shrink-0 inline-block rounded-full border border-dashed border-subtle" />
|
||||
<span class="font-medium text-primary text-sm truncate" :title="row.node!.name">{{ row.node!.name }}</span>
|
||||
<span
|
||||
v-if="row.node!.is_hidden"
|
||||
class="inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] bg-amber-50 text-amber-700 shrink-0"
|
||||
:title="t('admin.dept.fields.hiddenHint')"
|
||||
><EyeOff class="w-3 h-3" />{{ t('admin.dept.tags.hidden') }}</span>
|
||||
</div>
|
||||
<div
|
||||
v-if="row.node!.description"
|
||||
class="text-xs text-muted truncate mt-0.5"
|
||||
:style="{ paddingLeft: `${(row.depth - 1) * 20 + 28}px` }"
|
||||
:title="row.node!.description"
|
||||
>
|
||||
{{ row.node!.description }}
|
||||
</div>
|
||||
</td>
|
||||
<td class="px-6 py-4 text-sm text-muted font-mono whitespace-nowrap truncate" :title="row.node!.code || '-'">
|
||||
{{ row.node!.code || '-' }}
|
||||
</td>
|
||||
<td class="px-6 py-4 text-sm text-muted truncate" :title="row.node!.company || '-'">
|
||||
{{ row.node!.company || '-' }}
|
||||
</td>
|
||||
<td class="px-6 py-4 text-center">
|
||||
<button
|
||||
type="button"
|
||||
class="p-1.5 text-indigo-600 hover:bg-indigo-50 rounded-lg transition-colors"
|
||||
:title="t('admin.dept.actions.edit')"
|
||||
@click="openEditModal(d)"
|
||||
>
|
||||
<Edit class="w-4 h-4" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="p-1.5 text-red-600 hover:bg-red-50 rounded-lg transition-colors"
|
||||
:title="t('admin.dept.actions.delete')"
|
||||
@click="deleteDepartment(d.id)"
|
||||
>
|
||||
<Trash2 class="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
class="inline-flex items-center justify-center rounded-lg bg-blue-50 p-2 text-blue-600 hover:bg-blue-100"
|
||||
:title="t('admin.dept.actions.viewMembers')"
|
||||
@click="openDepartmentMembers(row.node!.id, false)"
|
||||
><Users class="w-5 h-5" /><span class="ml-1 text-xs">{{ row.totalMembers }}</span></button>
|
||||
</td>
|
||||
<td class="px-6 py-4">
|
||||
<div class="flex justify-end gap-1">
|
||||
<button
|
||||
type="button"
|
||||
class="p-1.5 text-emerald-600 hover:bg-emerald-50 rounded-lg transition-colors"
|
||||
:title="t('admin.dept.addChild')"
|
||||
@click="openCreateModal(row.node as AdminDepartmentTreeNode)"
|
||||
>
|
||||
<FolderPlus class="w-4 h-4" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="p-1.5 text-indigo-600 hover:bg-indigo-50 rounded-lg transition-colors"
|
||||
:title="t('admin.dept.actions.edit')"
|
||||
@click="openEditModal(row.node!)"
|
||||
>
|
||||
<Edit class="w-4 h-4" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="p-1.5 text-red-600 hover:bg-red-50 rounded-lg transition-colors"
|
||||
:title="t('admin.dept.actions.delete')"
|
||||
@click="deleteDepartment(row.node!.id)"
|
||||
>
|
||||
<Trash2 class="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</template>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
@@ -196,6 +282,7 @@ const openDepartmentMembers = async (departmentId: number): Promise<void> => {
|
||||
<DepartmentFormModal
|
||||
:visible="showFormModal"
|
||||
:form="form"
|
||||
:parent-options="parentOptions"
|
||||
:is-saving="isSaving"
|
||||
@close="closeFormModal"
|
||||
@save="saveDepartment"
|
||||
@@ -203,7 +290,9 @@ const openDepartmentMembers = async (departmentId: number): Promise<void> => {
|
||||
<DepartmentMembersModal
|
||||
:visible="showMembersModal"
|
||||
:data="departmentMembers"
|
||||
:include-descendants="includeDescendants"
|
||||
@close="showMembersModal = false"
|
||||
@set-include="toggleIncludeDescendants"
|
||||
/>
|
||||
|
||||
<DeleteConfirmDialog
|
||||
|
||||
@@ -1,16 +1,18 @@
|
||||
/**
|
||||
/**
|
||||
* features/admin/modules/departments/components/DepartmentFormModal.vue
|
||||
* 用途:部门创建/编辑居中弹窗。
|
||||
* 依赖:DepartmentFormState、admin 通用 modal 样式。
|
||||
* 逻辑:DepartmentsPage 打开本组件;提交时 emit save,由 useDepartmentsAdmin 调 API。
|
||||
* 用途:部门创建/编辑居中弹窗(含上级部门选择、同级排序、隐藏标记)。
|
||||
* 依赖:DepartmentFormState、DeptParentOption、admin 通用 modal 样式。
|
||||
* 逻辑:DepartmentsPage 打开本组件;上级选项由父级传入(编辑时已排除自身及子孙);提交时 emit save。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { DepartmentFormState } from '@/features/admin/types/department.types';
|
||||
import type { DeptParentOption } from '../composables/useDepartmentsAdmin';
|
||||
|
||||
defineProps<{
|
||||
visible: boolean;
|
||||
form: DepartmentFormState;
|
||||
parentOptions: DeptParentOption[];
|
||||
isSaving: boolean;
|
||||
}>();
|
||||
|
||||
@@ -31,6 +33,19 @@ const { t } = useI18n();
|
||||
</h3>
|
||||
</div>
|
||||
<div class="px-5 sm:px-8 py-5 space-y-4 overflow-y-auto">
|
||||
<div class="space-y-1.5">
|
||||
<label class="label-field">{{ t('admin.dept.fields.parent') }}</label>
|
||||
<select v-model="form.parentId" class="input-field text-sm">
|
||||
<option
|
||||
v-for="option in parentOptions"
|
||||
:key="String(option.id)"
|
||||
:value="option.id"
|
||||
:disabled="option.disabled"
|
||||
>
|
||||
{{ option.label }}
|
||||
</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<label class="label-field">{{ t('admin.dept.fields.name') }}</label>
|
||||
<input
|
||||
@@ -60,6 +75,25 @@ const { t } = useI18n();
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div class="grid grid-cols-1 sm:grid-cols-2 gap-4 items-start">
|
||||
<div class="space-y-1.5">
|
||||
<label class="label-field">{{ t('admin.dept.fields.sort') }}</label>
|
||||
<input
|
||||
v-model.number="form.sortOrder"
|
||||
type="number"
|
||||
class="input-field text-sm"
|
||||
:placeholder="'0'"
|
||||
/>
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<label class="label-field">{{ t('admin.dept.fields.visibility') }}</label>
|
||||
<label class="flex items-center gap-2 text-sm text-muted cursor-pointer select-none py-2">
|
||||
<input v-model="form.isHidden" type="checkbox" class="accent-brand-600 w-4 h-4" />
|
||||
{{ t('admin.dept.fields.hidden') }}
|
||||
</label>
|
||||
<p class="text-xs text-muted">{{ t('admin.dept.fields.hiddenHint') }}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<label class="label-field">{{ t('admin.dept.fields.description') }}</label>
|
||||
<textarea
|
||||
|
||||
+28
-9
@@ -1,26 +1,40 @@
|
||||
/**
|
||||
/**
|
||||
* features/admin/modules/departments/components/DepartmentMembersModal.vue
|
||||
* 用途:展示部门对应的员工数量和名单。
|
||||
* 用途:展示部门对应的员工数量和名单(支持「含下级部门」口径切换)。
|
||||
* 依赖:部门成员只读 API 响应与 Vue 事件。
|
||||
* 逻辑:DepartmentsPage 点击员工图标后传入数据,本组件只负责呈现与关闭。
|
||||
* 逻辑:DepartmentsPage 点击员工图标后传入数据;切换含下级开关时 emit set-include 由父级重新拉取。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { Users, X } from 'lucide-vue-next';
|
||||
import type { AdminDepartmentMembersResponse } from '@/features/admin/types/admin.types';
|
||||
|
||||
defineProps<{ visible: boolean; data: AdminDepartmentMembersResponse | null }>();
|
||||
const emit = defineEmits<{ close: [] }>();
|
||||
defineProps<{
|
||||
visible: boolean;
|
||||
data: AdminDepartmentMembersResponse | null;
|
||||
/** 当前是否为「含下级部门」口径 */
|
||||
includeDescendants: boolean;
|
||||
}>();
|
||||
const emit = defineEmits<{ close: []; setInclude: [value: boolean] }>();
|
||||
const { t } = useI18n();
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="visible && data" class="admin-modal-overlay items-center" @click.self="emit('close')">
|
||||
<section class="admin-modal-panel max-w-2xl max-h-[90vh] animate-fade-in-up">
|
||||
<header class="px-8 py-6 border-b border-subtle flex items-center justify-between">
|
||||
<div>
|
||||
<h3 class="text-lg font-bold text-primary">{{ t('admin.dept.members.title', { name: data.department.name }) }}</h3>
|
||||
<header class="px-8 py-6 border-b border-subtle flex items-start justify-between gap-4">
|
||||
<div class="min-w-0">
|
||||
<h3 class="text-lg font-bold text-primary truncate">{{ t('admin.dept.members.title', { name: data.department.name }) }}</h3>
|
||||
<p class="text-sm text-muted mt-1">{{ t('admin.dept.members.count', { count: data.count }) }}</p>
|
||||
<label class="flex items-center gap-2 text-sm text-muted cursor-pointer select-none mt-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
class="accent-brand-600 w-4 h-4"
|
||||
:checked="includeDescendants"
|
||||
@change="emit('setInclude', ($event.target as HTMLInputElement).checked)"
|
||||
/>
|
||||
{{ t('admin.dept.members.includeDescendants') }}
|
||||
</label>
|
||||
</div>
|
||||
<button type="button" class="btn-icon-ds rounded-full" :title="t('admin.close')" @click="emit('close')"><X class="w-5 h-5" /></button>
|
||||
</header>
|
||||
@@ -33,7 +47,12 @@ const { t } = useI18n();
|
||||
<li v-for="member in data.members" :key="member.id" class="py-3 flex items-center justify-between gap-4">
|
||||
<div class="min-w-0">
|
||||
<p class="font-medium text-primary">{{ member.real_name || member.username }}</p>
|
||||
<p class="text-xs text-muted truncate">{{ member.employee_id || member.username }} · {{ member.email || '-' }}</p>
|
||||
<p class="text-xs text-muted truncate">
|
||||
{{ member.employee_id || member.username }} · {{ member.email || '-' }}
|
||||
<template v-if="includeDescendants && member.department && member.department !== data.department.name">
|
||||
· {{ t('admin.dept.members.fromDepartment', { department: member.department }) }}
|
||||
</template>
|
||||
</p>
|
||||
</div>
|
||||
<span class="text-xs text-muted whitespace-nowrap">{{ member.status }}</span>
|
||||
</li>
|
||||
|
||||
+210
-51
@@ -1,40 +1,55 @@
|
||||
/**
|
||||
/**
|
||||
* features/admin/modules/departments/composables/useDepartmentsAdmin.ts
|
||||
* 用途:部门管理列表、搜索过滤、列排序、创建/编辑弹窗、删除。
|
||||
* 依赖:admin.api、department.types、useMessage、useTableSort。
|
||||
* 逻辑:DepartmentsPage 调用本 composable;排序状态委托 shared useTableSort。
|
||||
* 用途:部门树加载、公司虚拟分组、展开/收起、搜索过滤、创建/编辑/删除。
|
||||
* 依赖:admin.api、department.types、useMessage。
|
||||
* 逻辑:DepartmentsPage 调用本 composable;数据来自 /admin/departments/tree(children 已按同级排序号排好);
|
||||
* 公司层不入库,按顶级部门的 company 字段在前端虚拟分组。
|
||||
*/
|
||||
import { computed, ref } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import {
|
||||
createAdminDepartment,
|
||||
deleteAdminDepartment,
|
||||
listAdminDepartments,
|
||||
listAdminDepartmentTree,
|
||||
updateAdminDepartment,
|
||||
} from '@/features/admin/api/admin.api';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import { useTableSort } from '@/shared/composables/useTableSort';
|
||||
import type { AdminDepartmentRow } from '@/features/admin/types/admin.types';
|
||||
import type { AdminDepartmentTreeNode } from '@/features/admin/types/admin.types';
|
||||
import {
|
||||
createEmptyDepartmentForm,
|
||||
departmentRowToForm,
|
||||
type DepartmentFormState,
|
||||
} from '@/features/admin/types/department.types';
|
||||
|
||||
/** 部门表可排序列 */
|
||||
export type DeptSortKey = 'name' | 'code' | 'company';
|
||||
/** 表单弹窗「上级部门」下拉选项(编辑时排除自身及子孙,防成环) */
|
||||
export interface DeptParentOption {
|
||||
id: number | null;
|
||||
label: string;
|
||||
disabled: boolean;
|
||||
}
|
||||
|
||||
/** 树表展开后的一行:company 为公司虚拟分组行,dept 为部门行 */
|
||||
export interface DeptTreeDisplayRow {
|
||||
kind: 'company' | 'dept';
|
||||
key: string;
|
||||
/** 缩进层级:公司组为 0,顶级部门为 1,逐层 +1 */
|
||||
depth: number;
|
||||
company?: string;
|
||||
/** dept 行对应的部门节点 */
|
||||
node?: AdminDepartmentTreeNode;
|
||||
expanded: boolean;
|
||||
hasChildren: boolean;
|
||||
/** 含下级递归汇总的成员数 */
|
||||
totalMembers: number;
|
||||
}
|
||||
|
||||
export function useDepartmentsAdmin() {
|
||||
const { t } = useI18n();
|
||||
const msg = useMessage();
|
||||
|
||||
const departments = ref<AdminDepartmentRow[]>([]);
|
||||
const tree = ref<AdminDepartmentTreeNode[]>([]);
|
||||
const form = ref<DepartmentFormState>(createEmptyDepartmentForm());
|
||||
const searchQuery = ref('');
|
||||
const { sortKey, sortDir, toggleSort, sortItems } = useTableSort<DeptSortKey>({
|
||||
initialKey: 'name',
|
||||
initialDir: 'asc',
|
||||
});
|
||||
const isLoading = ref(true);
|
||||
const isSaving = ref(false);
|
||||
const showFormModal = ref(false);
|
||||
@@ -43,44 +58,139 @@ export function useDepartmentsAdmin() {
|
||||
const deleteConfirmMessage = ref('');
|
||||
let deleteConfirmAction: (() => Promise<void> | void) | null = null;
|
||||
|
||||
/**
|
||||
* 先按关键词过滤,再按当前排序列排序。
|
||||
* 核心逻辑:模糊匹配四字段 → useTableSort.sortItems。
|
||||
*/
|
||||
const filteredDepartments = computed(() => {
|
||||
const q = searchQuery.value.trim().toLowerCase();
|
||||
const filtered = q
|
||||
? departments.value.filter((d) => {
|
||||
const haystack = [d.name, d.code, d.company, d.description]
|
||||
.filter(Boolean)
|
||||
.join(' ')
|
||||
.toLowerCase();
|
||||
return haystack.includes(q);
|
||||
})
|
||||
: departments.value;
|
||||
|
||||
return sortItems(
|
||||
filtered,
|
||||
(row, key) => row[key],
|
||||
(a, b) => a.id - b.id,
|
||||
);
|
||||
});
|
||||
/** 展开状态:部门节点 id 集合 / 公司分组 key 集合 */
|
||||
const expandedIds = ref<Set<number>>(new Set());
|
||||
const expandedCompanies = ref<Set<string>>(new Set());
|
||||
|
||||
/**
|
||||
* 拉取部门列表并写入 departments。
|
||||
* 拉取部门树并写入 tree。
|
||||
* @returns Promise<void>
|
||||
*/
|
||||
const loadDepartments = async (): Promise<void> => {
|
||||
try {
|
||||
departments.value = await listAdminDepartments();
|
||||
tree.value = (await listAdminDepartmentTree()) as AdminDepartmentTreeNode[];
|
||||
} catch (e) {
|
||||
console.error('Failed to load departments', e);
|
||||
departments.value = [];
|
||||
console.error('Failed to load department tree', e);
|
||||
tree.value = [];
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 页面初始化:加载部门列表并结束 loading。
|
||||
* 按关键词过滤树:命中节点及其祖先保留;搜索态下全部自动展开。
|
||||
* 核心逻辑:递归 filterTree → 命中自身或子孙的节点保留。
|
||||
*/
|
||||
const displayRows = computed<DeptTreeDisplayRow[]>(() => {
|
||||
const q = searchQuery.value.trim().toLowerCase();
|
||||
|
||||
const filterTree = (nodes: AdminDepartmentTreeNode[]): AdminDepartmentTreeNode[] => {
|
||||
const out: AdminDepartmentTreeNode[] = [];
|
||||
for (const n of nodes) {
|
||||
const children = filterTree(n.children || []);
|
||||
const haystack = [n.name, n.code, n.company, n.description]
|
||||
.filter(Boolean)
|
||||
.join(' ')
|
||||
.toLowerCase();
|
||||
if (!q || haystack.includes(q) || children.length) {
|
||||
out.push({ ...n, children });
|
||||
}
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
const activeTree = q ? filterTree(tree.value) : tree.value;
|
||||
const rows: DeptTreeDisplayRow[] = [];
|
||||
|
||||
/** 递归铺开部门行;搜索态全展开,常态按 expandedIds */
|
||||
const appendDeptRows = (nodes: AdminDepartmentTreeNode[], depth: number): void => {
|
||||
for (const n of nodes) {
|
||||
const children = n.children || [];
|
||||
const expanded = q ? true : expandedIds.value.has(n.id);
|
||||
rows.push({
|
||||
kind: 'dept',
|
||||
key: `dept:${n.id}`,
|
||||
depth,
|
||||
node: n,
|
||||
expanded,
|
||||
hasChildren: children.length > 0,
|
||||
totalMembers: n.total_member_count || 0,
|
||||
company: n.company,
|
||||
});
|
||||
if (expanded && children.length) appendDeptRows(children, depth + 1);
|
||||
}
|
||||
};
|
||||
|
||||
// 树顶公司虚拟分组:顶级部门按 company 文本归堆(未填公司归入「未分配公司」)
|
||||
const groups = new Map<string, AdminDepartmentTreeNode[]>();
|
||||
for (const root of activeTree) {
|
||||
const key = root.company?.trim() || '';
|
||||
if (!groups.has(key)) groups.set(key, []);
|
||||
groups.get(key)!.push(root);
|
||||
}
|
||||
const groupKeys = [...groups.keys()].sort((a, b) => a.localeCompare(b, 'zh-Hans-CN'));
|
||||
for (const key of groupKeys) {
|
||||
const roots = groups.get(key)!;
|
||||
const companyOpen = q ? true : expandedCompanies.value.has(key);
|
||||
rows.push({
|
||||
kind: 'company',
|
||||
key: `company:${key}`,
|
||||
depth: 0,
|
||||
company: key || t('admin.dept.noCompany'),
|
||||
expanded: companyOpen,
|
||||
hasChildren: true,
|
||||
totalMembers: roots.reduce((sum, r) => sum + (r.total_member_count || 0), 0),
|
||||
});
|
||||
if (companyOpen) appendDeptRows(roots, 1);
|
||||
}
|
||||
return rows;
|
||||
});
|
||||
|
||||
/** 在树中按 id 查找节点。 */
|
||||
const findNode = (
|
||||
nodes: AdminDepartmentTreeNode[],
|
||||
id: number,
|
||||
): AdminDepartmentTreeNode | null => {
|
||||
for (const n of nodes) {
|
||||
if (n.id === id) return n;
|
||||
const hit = findNode(n.children || [], id);
|
||||
if (hit) return hit;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
/** 表单弹窗「上级部门」选项:编辑时排除自身及子孙,避免把子树挂到自己下面 */
|
||||
const parentOptions = computed<DeptParentOption[]>(() => {
|
||||
const options: DeptParentOption[] = [
|
||||
{ id: null, label: t('admin.dept.fields.parentRoot'), disabled: false },
|
||||
];
|
||||
const exclude = new Set<number>();
|
||||
if (form.value.id) {
|
||||
const stack: number[] = [form.value.id];
|
||||
const target = findNode(tree.value, form.value.id);
|
||||
const collect = (nodes: AdminDepartmentTreeNode[]): void => {
|
||||
for (const n of nodes) {
|
||||
stack.push(n.id);
|
||||
collect(n.children || []);
|
||||
}
|
||||
};
|
||||
if (target) collect(target.children || []);
|
||||
while (stack.length) exclude.add(stack.pop()!);
|
||||
}
|
||||
const walk = (nodes: AdminDepartmentTreeNode[], depth: number): void => {
|
||||
for (const n of nodes) {
|
||||
options.push({
|
||||
id: n.id,
|
||||
label: `${' '.repeat(depth)}${n.name}`,
|
||||
disabled: exclude.has(n.id),
|
||||
});
|
||||
walk(n.children || [], depth + 1);
|
||||
}
|
||||
};
|
||||
walk(tree.value, 0);
|
||||
return options;
|
||||
});
|
||||
|
||||
/**
|
||||
* 页面初始化:加载部门树并结束 loading。
|
||||
* @returns Promise<void>
|
||||
*/
|
||||
const loadAll = async (): Promise<void> => {
|
||||
@@ -89,6 +199,42 @@ export function useDepartmentsAdmin() {
|
||||
isLoading.value = false;
|
||||
};
|
||||
|
||||
/** 切换部门节点展开/收起。 */
|
||||
const toggleNode = (id: number): void => {
|
||||
const next = new Set(expandedIds.value);
|
||||
if (next.has(id)) next.delete(id);
|
||||
else next.add(id);
|
||||
expandedIds.value = next;
|
||||
};
|
||||
|
||||
/** 切换公司虚拟分组展开/收起。 */
|
||||
const toggleCompany = (key: string): void => {
|
||||
const next = new Set(expandedCompanies.value);
|
||||
if (next.has(key)) next.delete(key);
|
||||
else next.add(key);
|
||||
expandedCompanies.value = next;
|
||||
};
|
||||
|
||||
/** 全部展开(含所有公司组与部门节点)。 */
|
||||
const expandAll = (): void => {
|
||||
const ids = new Set<number>();
|
||||
const walk = (nodes: AdminDepartmentTreeNode[]): void => {
|
||||
for (const n of nodes) {
|
||||
ids.add(n.id);
|
||||
walk(n.children || []);
|
||||
}
|
||||
};
|
||||
walk(tree.value);
|
||||
expandedIds.value = ids;
|
||||
expandedCompanies.value = new Set(tree.value.map((r) => r.company?.trim() || ''));
|
||||
};
|
||||
|
||||
/** 全部收起(仅保留公司组层)。 */
|
||||
const collapseAll = (): void => {
|
||||
expandedIds.value = new Set();
|
||||
expandedCompanies.value = new Set();
|
||||
};
|
||||
|
||||
/**
|
||||
* 打开删除确认对话框并绑定确认后的删除动作。
|
||||
* @param message - 确认文案
|
||||
@@ -119,17 +265,23 @@ export function useDepartmentsAdmin() {
|
||||
}
|
||||
};
|
||||
|
||||
/** 打开「添加部门」弹窗并重置表单。 */
|
||||
const openCreateModal = (): void => {
|
||||
/**
|
||||
* 打开「添加部门」弹窗。
|
||||
* @param parent - 上级部门节点(添加子部门时传入);空 = 顶级
|
||||
* @param company - 预填公司(公司虚拟分组行的「添加子部门」传入)
|
||||
*/
|
||||
const openCreateModal = (parent?: AdminDepartmentTreeNode | null, company?: string): void => {
|
||||
form.value = createEmptyDepartmentForm();
|
||||
form.value.parentId = parent ? parent.id : null;
|
||||
form.value.company = company ?? parent?.company ?? '';
|
||||
showFormModal.value = true;
|
||||
};
|
||||
|
||||
/**
|
||||
* 打开「编辑部门」弹窗并回填选中行数据。
|
||||
* @param dept - 待编辑的部门行
|
||||
* @param dept - 待编辑的部门树节点
|
||||
*/
|
||||
const openEditModal = (dept: AdminDepartmentRow): void => {
|
||||
const openEditModal = (dept: AdminDepartmentTreeNode): void => {
|
||||
form.value = departmentRowToForm(dept);
|
||||
showFormModal.value = true;
|
||||
};
|
||||
@@ -142,7 +294,8 @@ export function useDepartmentsAdmin() {
|
||||
|
||||
/**
|
||||
* 保存部门:有 id 则更新,否则新建。
|
||||
* 核心逻辑:校验名称 → 调 create/update API → 刷新列表并关闭弹窗。
|
||||
* 核心逻辑:校验名称 → 组装含 parent_id/sort_order/is_hidden 的载荷 → 调 API → 刷新树并关闭弹窗。
|
||||
* 后端负责同级查重、防成环等校验,失败抛 BusinessError(errors.json 四语言文案)。
|
||||
* @returns Promise<void>
|
||||
*/
|
||||
const saveDepartment = async (): Promise<void> => {
|
||||
@@ -157,6 +310,9 @@ export function useDepartmentsAdmin() {
|
||||
code: form.value.code?.trim() || '',
|
||||
company: form.value.company?.trim() || '',
|
||||
description: form.value.description?.trim() || '',
|
||||
parent_id: form.value.parentId ?? null,
|
||||
sort_order: form.value.sortOrder ?? 0,
|
||||
is_hidden: !!form.value.isHidden,
|
||||
};
|
||||
if (form.value.id) {
|
||||
await updateAdminDepartment(form.value.id, payload);
|
||||
@@ -174,6 +330,7 @@ export function useDepartmentsAdmin() {
|
||||
|
||||
/**
|
||||
* 删除指定部门,删除前弹出确认框。
|
||||
* 有下级部门或名下仍有员工时后端返回 409(HAS_CHILDREN / HAS_MEMBERS),此处展示其文案。
|
||||
* @param id - 部门主键
|
||||
*/
|
||||
const deleteDepartment = (id: number): void => {
|
||||
@@ -189,19 +346,21 @@ export function useDepartmentsAdmin() {
|
||||
};
|
||||
|
||||
return {
|
||||
departments,
|
||||
filteredDepartments,
|
||||
tree,
|
||||
displayRows,
|
||||
parentOptions,
|
||||
form,
|
||||
searchQuery,
|
||||
sortKey,
|
||||
sortDir,
|
||||
isLoading,
|
||||
isSaving,
|
||||
showFormModal,
|
||||
showDeleteConfirmDialog,
|
||||
deleteConfirmMessage,
|
||||
loadAll,
|
||||
toggleSort,
|
||||
toggleNode,
|
||||
toggleCompany,
|
||||
expandAll,
|
||||
collapseAll,
|
||||
openCreateModal,
|
||||
openEditModal,
|
||||
closeFormModal,
|
||||
|
||||
@@ -73,15 +73,30 @@ export interface AdminDepartmentRow {
|
||||
code?: string;
|
||||
company?: string;
|
||||
description?: string;
|
||||
/** 上级部门主键;null/缺省表示顶级部门 */
|
||||
parent_id?: number | null;
|
||||
/** 同级排序号(升序),对应 ERP hrao09 */
|
||||
sort_order?: number;
|
||||
/** 是否在组织树中隐藏(对应 ERP hrao08;管理端仍可见并打标) */
|
||||
is_hidden?: boolean;
|
||||
member_count?: number;
|
||||
}
|
||||
|
||||
/** 部门树节点:/admin/departments/tree 返回结构,children 已按同级排序号排好 */
|
||||
export interface AdminDepartmentTreeNode extends AdminDepartmentRow {
|
||||
/** 含全部下级部门的成员总数(递归汇总) */
|
||||
total_member_count?: number;
|
||||
children: AdminDepartmentTreeNode[];
|
||||
}
|
||||
|
||||
export interface AdminDepartmentMember {
|
||||
id: number;
|
||||
username: string;
|
||||
real_name?: string;
|
||||
employee_id?: string;
|
||||
email?: string;
|
||||
/** 成员所属部门名(含下级视图下用于区分来源部门) */
|
||||
department?: string;
|
||||
status?: string;
|
||||
}
|
||||
|
||||
|
||||
@@ -12,6 +12,12 @@ export interface DepartmentFormState {
|
||||
code?: string;
|
||||
company?: string;
|
||||
description?: string;
|
||||
/** 上级部门主键;null 表示顶级部门 */
|
||||
parentId?: number | null;
|
||||
/** 同级排序号(升序) */
|
||||
sortOrder?: number;
|
||||
/** 是否在组织树中隐藏 */
|
||||
isHidden?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -23,6 +29,9 @@ export const createEmptyDepartmentForm = (): DepartmentFormState => ({
|
||||
code: '',
|
||||
company: '',
|
||||
description: '',
|
||||
parentId: null,
|
||||
sortOrder: 0,
|
||||
isHidden: false,
|
||||
});
|
||||
|
||||
/**
|
||||
@@ -36,4 +45,7 @@ export const departmentRowToForm = (dept: AdminDepartmentRow): DepartmentFormSta
|
||||
code: dept.code || '',
|
||||
company: dept.company || '',
|
||||
description: dept.description || '',
|
||||
parentId: dept.parent_id ?? null,
|
||||
sortOrder: dept.sort_order ?? 0,
|
||||
isHidden: !!dept.is_hidden,
|
||||
});
|
||||
@@ -1244,6 +1244,12 @@
|
||||
"subtitle": "Manage organization structure",
|
||||
"edit": "Edit Department",
|
||||
"add": "Add New Department",
|
||||
"addChild": "Add sub-department",
|
||||
"expandAll": "Expand all",
|
||||
"collapseAll": "Collapse all",
|
||||
"expand": "Expand",
|
||||
"collapse": "Collapse",
|
||||
"noCompany": "Unassigned company",
|
||||
"noDepts": "No departments configured.",
|
||||
"noSearchResults": "No matching departments found",
|
||||
"searchPlaceholder": "Search by name, code, or company…",
|
||||
@@ -1262,8 +1268,12 @@
|
||||
"members": {
|
||||
"title": "{name} Members",
|
||||
"count": "{count} members",
|
||||
"includeDescendants": "Include sub-departments",
|
||||
"fromDepartment": "From: {department}",
|
||||
"countTitle": "{count} people in total (incl. sub-departments)",
|
||||
"empty": "No members"
|
||||
},
|
||||
"tags": { "hidden": "Hidden" },
|
||||
"fields": {
|
||||
"name": "Name",
|
||||
"namePlaceholder": "e.g. IT Department",
|
||||
@@ -1272,6 +1282,12 @@
|
||||
"company": "Company",
|
||||
"companyPlaceholder": "e.g. HQ",
|
||||
"description": "Description",
|
||||
"parent": "Parent department",
|
||||
"parentRoot": "(As top-level department)",
|
||||
"sort": "Sibling order",
|
||||
"visibility": "Visibility",
|
||||
"hidden": "Hide in organization tree",
|
||||
"hiddenHint": "Hidden departments are excluded from the organization tree but remain visible here (maps to ERP \"show in org chart\")",
|
||||
"descriptionPlaceholder": "Department description..."
|
||||
},
|
||||
"confirmDelete": "Delete this department?",
|
||||
|
||||
@@ -598,6 +598,13 @@
|
||||
"TRANSFER.DOCUMENT_NOT_FOUND": "Transfer ticket not found.",
|
||||
"INTEGRATION.BINDING_LEGACY_PUT_REJECTED": "Legacy single-step fields would truncate this binding's multi-step recipe; submit ordered steps via steps_json instead.",
|
||||
"INTEGRATION.CALL_NOT_FOUND": "Integration call not found.",
|
||||
"INTEGRATION.BINDING_STEPS_INVALID": "Binding steps invalid: steps_json is required, must be a non-empty array of objects."
|
||||
"INTEGRATION.BINDING_STEPS_INVALID": "Binding steps invalid: steps_json is required, must be a non-empty array of objects.",
|
||||
"DEPT.NAME_REQUIRED": "Department name is required.",
|
||||
"DEPT.PARENT_INVALID": "Parent department does not exist or has been deleted.",
|
||||
"DEPT.NAME_EXISTS": "A sibling department with the same name already exists.",
|
||||
"DEPT.CODE_EXISTS": "Department code is already used by another department.",
|
||||
"DEPT.CYCLE_FORBIDDEN": "A department cannot be its own parent or descendant.",
|
||||
"DEPT.HAS_CHILDREN": "This department has child departments; move or delete them first.",
|
||||
"DEPT.HAS_MEMBERS": "This department still has members and cannot be deleted."
|
||||
}
|
||||
}
|
||||
@@ -1244,6 +1244,12 @@
|
||||
"subtitle": "จัดการโครงสร้างองค์กร",
|
||||
"edit": "แก้ไขแผนก",
|
||||
"add": "เพิ่มแผนกใหม่",
|
||||
"addChild": "เพิ่มแผนกย่อย",
|
||||
"expandAll": "ขยายทั้งหมด",
|
||||
"collapseAll": "ยุบทั้งหมด",
|
||||
"expand": "ขยาย",
|
||||
"collapse": "ยุบ",
|
||||
"noCompany": "ยังไม่ระบุบริษัท",
|
||||
"noDepts": "ยังไม่มีการกำหนดค่าแผนก",
|
||||
"noSearchResults": "ไม่พบแผนกที่ตรงกัน",
|
||||
"searchPlaceholder": "ค้นหาชื่อ รหัส หรือบริษัท…",
|
||||
@@ -1259,6 +1265,7 @@
|
||||
"delete": "ลบ",
|
||||
"viewMembers": "View department members"
|
||||
},
|
||||
"tags": { "hidden": "ซ่อนอยู่" },
|
||||
"fields": {
|
||||
"name": "ชื่อ",
|
||||
"namePlaceholder": "เช่น แผนกไอที",
|
||||
@@ -1267,6 +1274,12 @@
|
||||
"company": "บริษัท",
|
||||
"companyPlaceholder": "เช่น สำนักงานใหญ่",
|
||||
"description": "คำอธิบาย",
|
||||
"parent": "แผนกแม่",
|
||||
"parentRoot": "(เป็นแผนกระดับบนสุด)",
|
||||
"sort": "ลำดับภายในระดับเดียวกัน",
|
||||
"visibility": "การแสดงผล",
|
||||
"hidden": "ซ่อนในผังองค์กร",
|
||||
"hiddenHint": "ซ่อนจากผังองค์กรแต่ผู้ดูแลระบบยังมองเห็น (ตรงกับ ERP \"แสดงในผังองค์กรหรือไม่\")",
|
||||
"descriptionPlaceholder": "กรอกรายละเอียดแผนก..."
|
||||
},
|
||||
"confirmDelete": "ลบแผนกนี้หรือไม่?",
|
||||
@@ -1276,6 +1289,9 @@
|
||||
"members": {
|
||||
"title": "{name} Members",
|
||||
"count": "{count} members",
|
||||
"includeDescendants": "รวมแผนกย่อย",
|
||||
"fromDepartment": "จาก: {department}",
|
||||
"countTitle": "รวมทั้งหมด {count} คน (รวมแผนกย่อย)",
|
||||
"empty": "No members"
|
||||
}
|
||||
},
|
||||
|
||||
@@ -598,6 +598,13 @@
|
||||
"TRANSFER.DOCUMENT_NOT_FOUND": "ไม่พบตั๋วโอนย้าย",
|
||||
"INTEGRATION.BINDING_LEGACY_PUT_REJECTED": "ฟิลด์ขั้นตอนเดียวแบบเดิมจะตัดทอนสูตรหลายขั้นตอนของการผูกนี้ โปรดส่งขั้นตอนตามลำดับด้วย steps_json แทน",
|
||||
"INTEGRATION.CALL_NOT_FOUND": "ไม่พบระเบียนการเรียกใช้งานการผสานรวม",
|
||||
"INTEGRATION.BINDING_STEPS_INVALID": "การกำหนดค่าขั้นตอนการเชื่อมโยงไม่ถูกต้อง: steps_json จำเป็นต้องมีและเป็นอาร์เรย์ที่ไม่ว่าง โดยแต่ละรายการต้องเป็นออบเจกต์"
|
||||
"INTEGRATION.BINDING_STEPS_INVALID": "การกำหนดค่าขั้นตอนการเชื่อมโยงไม่ถูกต้อง: steps_json จำเป็นต้องมีและเป็นอาร์เรย์ที่ไม่ว่าง โดยแต่ละรายการต้องเป็นออบเจกต์",
|
||||
"DEPT.NAME_REQUIRED": "กรุณากรอกชื่อแผนก",
|
||||
"DEPT.PARENT_INVALID": "ไม่พบแผนกแม่หรือแผนกแม่ถูกลบแล้ว",
|
||||
"DEPT.NAME_EXISTS": "มีแผนกชื่อเดียวกันอยู่ภายใต้แผนกแม่เดียวกันแล้ว",
|
||||
"DEPT.CODE_EXISTS": "รหัสแผนกนี้ถูกใช้โดยแผนกอื่นแล้ว",
|
||||
"DEPT.CYCLE_FORBIDDEN": "แผนกไม่สามารถเป็นแผนกแม่ของตัวเองหรือแผนกย่อยของตัวเองได้",
|
||||
"DEPT.HAS_CHILDREN": "แผนกนี้มีแผนกย่อย กรุณาจัดการแผนกย่อยก่อนจึงจะลบได้",
|
||||
"DEPT.HAS_MEMBERS": "แผนกนี้ยังมีพนักงานอยู่ จึงไม่สามารถลบได้"
|
||||
}
|
||||
}
|
||||
@@ -1372,6 +1372,12 @@
|
||||
"subtitle": "管理组织架构",
|
||||
"edit": "编辑部门",
|
||||
"add": "添加部门",
|
||||
"addChild": "添加子部门",
|
||||
"expandAll": "全部展开",
|
||||
"collapseAll": "全部收起",
|
||||
"expand": "展开",
|
||||
"collapse": "收起",
|
||||
"noCompany": "未分配公司",
|
||||
"noDepts": "暂无部门配置",
|
||||
"noSearchResults": "未找到匹配的部门",
|
||||
"searchPlaceholder": "搜索名称、编码或公司…",
|
||||
@@ -1390,8 +1396,12 @@
|
||||
"members": {
|
||||
"title": "{name}员工",
|
||||
"count": "共 {count} 人",
|
||||
"includeDescendants": "含下级部门",
|
||||
"fromDepartment": "来自:{department}",
|
||||
"countTitle": "含下级共 {count} 人",
|
||||
"empty": "暂无员工"
|
||||
},
|
||||
"tags": { "hidden": "已隐藏" },
|
||||
"fields": {
|
||||
"name": "名称",
|
||||
"namePlaceholder": "例如:信息技术部",
|
||||
@@ -1400,6 +1410,12 @@
|
||||
"company": "公司",
|
||||
"companyPlaceholder": "例如:总部",
|
||||
"description": "描述",
|
||||
"parent": "上级部门",
|
||||
"parentRoot": "(作为顶级部门)",
|
||||
"sort": "同级排序",
|
||||
"visibility": "显示设置",
|
||||
"hidden": "在组织树中隐藏",
|
||||
"hiddenHint": "隐藏后不在组织树中展示,管理端仍可见(对应 ERP「在组织框架图中显示否」)",
|
||||
"descriptionPlaceholder": "请输入部门描述..."
|
||||
},
|
||||
"confirmDelete": "确定删除该部门吗?",
|
||||
|
||||
@@ -598,6 +598,13 @@
|
||||
"TRANSFER.DOCUMENT_NOT_FOUND": "调拨票不存在。",
|
||||
"INTEGRATION.BINDING_LEGACY_PUT_REJECTED": "旧单步字段会截断该绑定的多步配方,请改用 steps_json 提交有序步骤。",
|
||||
"INTEGRATION.CALL_NOT_FOUND": "集成调用记录不存在。",
|
||||
"INTEGRATION.BINDING_STEPS_INVALID": "绑定步骤配置不合法:steps_json 必填且为非空数组,每项须为对象。"
|
||||
"INTEGRATION.BINDING_STEPS_INVALID": "绑定步骤配置不合法:steps_json 必填且为非空数组,每项须为对象。",
|
||||
"DEPT.NAME_REQUIRED": "部门名称必填。",
|
||||
"DEPT.PARENT_INVALID": "上级部门不存在或已被删除。",
|
||||
"DEPT.NAME_EXISTS": "同一上级部门下已存在同名部门。",
|
||||
"DEPT.CODE_EXISTS": "部门编码已被其他部门使用。",
|
||||
"DEPT.CYCLE_FORBIDDEN": "上级部门不能选择自己或自己的下级部门。",
|
||||
"DEPT.HAS_CHILDREN": "该部门存在下级部门,请先处理下级部门后再删除。",
|
||||
"DEPT.HAS_MEMBERS": "该部门名下仍有员工,无法删除。"
|
||||
}
|
||||
}
|
||||
@@ -1244,6 +1244,12 @@
|
||||
"subtitle": "管理組織架構",
|
||||
"edit": "編輯部門",
|
||||
"add": "添加部門",
|
||||
"addChild": "添加子部門",
|
||||
"expandAll": "全部展開",
|
||||
"collapseAll": "全部收起",
|
||||
"expand": "展開",
|
||||
"collapse": "收起",
|
||||
"noCompany": "未分配公司",
|
||||
"noDepts": "暫無部門配置",
|
||||
"noSearchResults": "未找到匹配的部門",
|
||||
"searchPlaceholder": "搜尋名稱、編碼或公司…",
|
||||
@@ -1259,6 +1265,7 @@
|
||||
"delete": "刪除",
|
||||
"viewMembers": "View department members"
|
||||
},
|
||||
"tags": { "hidden": "已隱藏" },
|
||||
"fields": {
|
||||
"name": "名稱",
|
||||
"namePlaceholder": "例如:資訊技術部",
|
||||
@@ -1267,6 +1274,12 @@
|
||||
"company": "公司",
|
||||
"companyPlaceholder": "例如:總部",
|
||||
"description": "描述",
|
||||
"parent": "上級部門",
|
||||
"parentRoot": "(作為頂級部門)",
|
||||
"sort": "同級排序",
|
||||
"visibility": "顯示設定",
|
||||
"hidden": "在組織樹中隱藏",
|
||||
"hiddenHint": "隱藏後不在組織樹中展示,管理端仍可見(對應 ERP「在組織框架圖中顯示否」)",
|
||||
"descriptionPlaceholder": "請輸入部門描述..."
|
||||
},
|
||||
"confirmDelete": "確定刪除該部門嗎?",
|
||||
@@ -1276,6 +1289,9 @@
|
||||
"members": {
|
||||
"title": "{name} Members",
|
||||
"count": "{count} members",
|
||||
"includeDescendants": "含下級部門",
|
||||
"fromDepartment": "來自:{department}",
|
||||
"countTitle": "含下級共 {count} 人",
|
||||
"empty": "No members"
|
||||
}
|
||||
},
|
||||
|
||||
@@ -598,6 +598,13 @@
|
||||
"TRANSFER.DOCUMENT_NOT_FOUND": "調撥票不存在。",
|
||||
"INTEGRATION.BINDING_LEGACY_PUT_REJECTED": "舊單步欄位會截斷該繫結的多步配方,請改用 steps_json 提交有序步驟。",
|
||||
"INTEGRATION.CALL_NOT_FOUND": "整合調用記錄不存在。",
|
||||
"INTEGRATION.BINDING_STEPS_INVALID": "綁定步驟配置不合法:steps_json 必填且為非空陣列,每項須為物件。"
|
||||
"INTEGRATION.BINDING_STEPS_INVALID": "綁定步驟配置不合法:steps_json 必填且為非空陣列,每項須為物件。",
|
||||
"DEPT.NAME_REQUIRED": "部門名稱必填。",
|
||||
"DEPT.PARENT_INVALID": "上級部門不存在或已被刪除。",
|
||||
"DEPT.NAME_EXISTS": "同一上級部門下已存在同名部門。",
|
||||
"DEPT.CODE_EXISTS": "部門編碼已被其他部門使用。",
|
||||
"DEPT.CYCLE_FORBIDDEN": "上級部門不能選擇自己或自己的下級部門。",
|
||||
"DEPT.HAS_CHILDREN": "該部門存在下級部門,請先處理下級部門後再刪除。",
|
||||
"DEPT.HAS_MEMBERS": "該部門名下仍有員工,無法刪除。"
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user