!29 fix(admin): 部门树首屏默认展开第一层,成员表居中消除集中空白

Merge pull request !29 from 王瑞雪/departmental-structure
This commit is contained in:
sophie authored and Gitee committed 2026-10-30 03:29:32 +00:00
commit b2fe9b78e2
28 files changed
+2101 -412

No files matched your search

+19 -5
View File
@@ -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,15 @@ 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))
"""部门员工分页名单(OA 组织面板口径):include_descendants=1 含下级,keyword 搜姓名/工号/邮箱/手机。"""
include_descendants = request.args.get('include_descendants', '') in ('1', 'true')
return jsonify(department_service.list_department_members(
id,
include_descendants,
keyword=request.args.get('keyword', ''),
page=request.args.get('page', 1, type=int),
page_size=request.args.get('page_size', 20, type=int),
))
@admin_bp.route('/departments/<int:id>', methods=['PUT'])
+18 -5
View File
@@ -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')
+314 -56
View File
@@ -1,59 +1,206 @@
"""
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 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]
def list_department_members(dept_id: int) -> dict:
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}
[STEP 1] 通过部门主键读取部门名称。
[STEP 2] 复用现有 users.department 文本关联查询成员。
[STEP 3] 返回人数与脱敏后的管理端成员资料。
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('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]
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),
'count': len(users),
'total': total,
'page': page,
'page_size': page_size,
'members': [
{
'id': user.id,
@@ -61,6 +208,8 @@ def list_department_members(dept_id: int) -> dict:
'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
@@ -68,25 +217,104 @@ 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],
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 缺失或 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)
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=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 +323,64 @@ 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')
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']
if 'code' in data:
if data['code'] and db.session.query(Department).filter(
Department.code == data['code'], Department.id != dept_id
).first():
raise ValidationError('Code exists')
dept.code = data['code']
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 = data['company']
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 = 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
@@ -0,0 +1,24 @@
"""merge department tree and latest dev migration heads
Revision ID: eff84b4f6171
Revises: fa1d22f99de9, pr0a1b2c3d4e5
Create Date: 2026-10-29 17:06:07.732022
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'eff84b4f6171'
down_revision = ('fa1d22f99de9', 'pr0a1b2c3d4e5')
branch_labels = None
depends_on = None
def upgrade():
pass
def downgrade():
pass
@@ -0,0 +1,24 @@
"""merge department tree and dev migration heads
Revision ID: fa1d22f99de9
Revises: dp1a2b3c4d5e6, eah8c9d0e1f2
Create Date: 2026-10-22 13:19:23.491330
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'fa1d22f99de9'
down_revision = ('dp1a2b3c4d5e6', 'eah8c9d0e1f2')
branch_labels = None
depends_on = None
def upgrade():
pass
def downgrade():
pass
@@ -0,0 +1,11 @@
{
"_comment": "hrao00 -> 公司中文名。来源 ERP dc.HRAA_FILE(hraa01=公司编号,hraa02=公司名称)。0000 集团公司无部门,保留映射以备后续。",
"0000": "集团公司",
"0001": "电子",
"0002": "科技",
"0003": "和信",
"0004": "泰国合欣",
"0005": "台湾尊场",
"0006": "无锡和宏智",
"0007": "上海数智"
}
@@ -0,0 +1,358 @@
"""Import ERP HRAO_FILE departments into the local department tree.
Purpose: one-shot import of the Tiptop department master (ERP `dc.HRAO_FILE`) exported as
CSV from DBeaver into the local `departments` tree, upserting by department code (hrao01).
Dependencies: Flask app context, SQLAlchemy models, csv/json stdlib (no Oracle driver).
Flow: dry-run is the default and only prints a validation report; pass `--apply` to write.
hrao06 parent codes resolve to hrao01 after all rows are upserted; dangling parents and
cycles fall back to top-level with a report. Local rows whose code is absent from the ERP
file are kept untouched (per the agreed merge policy). `users.department` links by name
text, so renames are reported for manual re-linking instead of being rewritten here.
Usage (from backend/):
python scripts/import_departments_from_hrao.py --file scripts/data/hrao_departments.csv
python scripts/import_departments_from_hrao.py --file ... --apply
"""
from __future__ import annotations
import argparse
import json
import sys
from collections import Counter
from pathlib import Path
from typing import Any, Optional
BACKEND_ROOT = Path(__file__).resolve().parents[1]
if str(BACKEND_ROOT) not in sys.path:
sys.path.insert(0, str(BACKEND_ROOT))
from app import create_app
from app.extensions import db
from app.models import Department, User
DEFAULT_CSV = Path("scripts/data/hrao_departments.csv")
DEFAULT_COMPANY_MAP = Path("scripts/data/hrao_company_map.json")
HIDDEN_MODES = ("ignore", "n_is_hidden", "not_y_is_hidden")
def _clean(value: Any) -> str:
"""Trim a CSV cell to a normalized string ('' for None)."""
return str(value or "").strip()
def _read_csv(path: Path) -> list[dict[str, str]]:
"""Read the DBeaver CSV export; headers are normalized to lowercase (utf-8 with BOM tolerated).
Args:
path: CSV file exported from `SELECT hrao00, hrao01, hrao02, hrao03, hrao06, hrao09, ... FROM dc.HRAO_FILE`.
Returns:
List of row dicts keyed by lowercase column names (hrao00 ...).
Raises:
SystemExit: file missing or no recognizable hrao01 header.
"""
if not path.exists():
raise SystemExit(f"CSV not found: {path}\n先在 DBeaver 导出 HRAO 查询结果为 CSV(UTF-8),再放到该路径。")
import csv
with path.open(encoding="utf-8-sig", newline="") as fh:
reader = csv.DictReader(fh)
rows = [
{(k or "").strip().lower(): (v or "") for k, v in raw.items()}
for raw in reader
]
if rows and not any("hrao01" in row for row in rows[:1]):
raise SystemExit(f"CSV 首行未找到 hrao01 列头,请确认导出来自 HRAO_FILE 查询:{path}")
return rows
def _load_company_map(path: Path) -> dict[str, str]:
"""Load hrao00 -> company display name mapping from a JSON file.
Raises:
SystemExit: mapping file missing (with a template hint).
"""
if not path.exists():
raise SystemExit(
f"公司映射文件不存在:{path}\n"
'请创建 JSON:{"0002": "苏州和信精密科技有限公司", ...}(hrao00 -> 公司中文名)。'
)
data = json.loads(path.read_text(encoding="utf-8"))
return {_clean(k): _clean(v) for k, v in data.items() if _clean(k)}
def _parse_hidden(hrao08: str, mode: str) -> bool:
"""Map hrao08 (在组织框架图中显示否) to is_hidden per the chosen mode.
Args:
mode: ignore(默认,全部不隐藏)| n_is_hidden(N=不显示→隐藏)| not_y_is_hidden(非 Y 即隐藏)。
"""
flag = _clean(hrao08).upper()
if mode == "n_is_hidden":
return flag == "N"
if mode == "not_y_is_hidden":
return flag != "Y"
return False
def _normalize_rows(
raw_rows: list[dict[str, str]], hidden_mode: str
) -> tuple[list[dict[str, Any]], list[str]]:
"""Normalize CSV rows into import payloads; duplicate hrao01 keeps the first occurrence.
Returns:
(rows, problems) — rows keyed by code with name/company_code/parent_code/sort_order/is_hidden.
"""
rows: dict[str, dict[str, Any]] = {}
problems: list[str] = []
for raw in raw_rows:
code = _clean(raw.get("hrao01"))
name = _clean(raw.get("hrao02")) or _clean(raw.get("hrao03"))
if not code:
problems.append(f"跳过:hrao01 为空(hrao02={_clean(raw.get('hrao02'))!r})")
continue
if not name:
problems.append(f"跳过:{code} 部门名称为空(hrao02/hrao03 均空)")
continue
if code in rows:
problems.append(f"跳过重复编码:{code} 第二次出现({name!r}),保留首行")
continue
sort_raw = _clean(raw.get("hrao09"))
parent = _clean(raw.get("hrao06"))
rows[code] = {
"code": code,
"name": name,
"company_code": _clean(raw.get("hrao00")),
"parent_code": parent if parent and parent != "0" else None,
"sort_order": int(sort_raw) if sort_raw.isdigit() else 0,
"is_hidden": _parse_hidden(raw.get("hrao08"), hidden_mode),
}
return list(rows.values()), problems
def _resolve_parents(rows: list[dict[str, Any]]) -> tuple[dict[str, Optional[str]], list[str]]:
"""Resolve each row's parent code; dangling/self references fall back to top-level.
Returns:
(parent_by_code, problems) — parent codes or None for top-level.
"""
codes = {r["code"] for r in rows}
parent_by_code: dict[str, Optional[str]] = {}
problems: list[str] = []
for row in rows:
parent = row["parent_code"]
if parent is not None and (parent not in codes or parent == row["code"]):
problems.append(f"悬空上级:{row['code']} {row['name']} 的 hrao06={parent!r} 匹配不到 hrao01,按顶级导入")
parent = None
parent_by_code[row["code"]] = parent
return parent_by_code, problems
def _break_cycles(
rows: list[dict[str, Any]], parent_by_code: dict[str, Optional[str]]
) -> tuple[dict[str, Optional[str]], list[str]]:
"""Rows caught in a parent cycle (e.g. A->B->A) are detached to top-level.
Returns:
(parent_by_code, problems)
"""
problems: list[str] = []
for row in rows:
seen: set[str] = set()
cursor: Optional[str] = row["code"]
cyclic = False
while cursor and parent_by_code.get(cursor):
if cursor in seen:
cyclic = True
break
seen.add(cursor)
cursor = parent_by_code[cursor]
if cyclic:
name = next(r["name"] for r in rows if r["code"] == row["code"])
problems.append(f"成环:{row['code']} {name} 的上级链形成环,整链按顶级导入")
parent_by_code[row["code"]] = None
return parent_by_code, problems
def _find_name_conflicts(
rows: list[dict[str, Any]], parent_by_code: dict[str, Optional[str]]
) -> list[str]:
"""Same-parent (or same-company top-level) duplicate names would fail sibling validation."""
buckets: Counter = Counter()
for row in rows:
parent = parent_by_code[row["code"]]
company = row["company_code"] if parent is None else parent
buckets[(company, parent, row["name"])] += 1
return [
f"同级重名:{name!r}(公司/父={key})出现 {count} 次,需人工改名后再导入"
for (key, _, name), count in buckets.items()
if count > 1
]
def plan_import(
rows: list[dict[str, Any]],
company_map: dict[str, str],
allow_unmapped: bool,
) -> tuple[dict[str, Any], list[str]]:
"""Diff ERP rows against local departments into an upsert plan.
Args:
rows: normalized ERP rows.
company_map: hrao00 -> company display name.
allow_unmapped: when False, unmapped hrao00 aborts the plan (apply refuses).
Returns:
(plan, problems) — plan holds inserts/updates/kept/dangling etc. for the reporter.
"""
problems: list[str] = []
unmapped = sorted({r["company_code"] for r in rows if r["company_code"] and r["company_code"] not in company_map})
if unmapped and not allow_unmapped:
problems.append(f"未映射的公司编码:{unmapped}(补 hrao_company_map.json 或加 --allow-unmapped)")
for row in rows:
row["company"] = company_map.get(row["company_code"])
local_by_code = {d.code: d for d in db.session.query(Department).all()}
inserts = [r for r in rows if r["code"] not in local_by_code]
updates = [
{"local": local_by_code[r["code"]], "row": r}
for r in rows
if r["code"] in local_by_code
]
kept = sorted(set(local_by_code) - {r["code"] for r in rows})
renames = []
for item in updates:
old_name = item["local"].name
if old_name != item["row"]["name"]:
linked = db.session.query(User).filter(User.department == old_name).count()
renames.append((old_name, item["row"]["name"], linked))
plan = {
"inserts": inserts,
"updates": updates,
"kept": kept,
"renames": renames,
"unmapped": unmapped,
}
return plan, problems
def apply_plan(plan: dict[str, Any], parent_by_code: dict[str, Optional[str]]) -> tuple[int, int]:
"""Execute the plan in one transaction; parents are linked after ids exist.
Returns:
(created, updated) row counts.
"""
code_to_id = {d.code: d.id for d in db.session.query(Department).all()}
created = updated = 0
# [STEP 1] 先落行(parent_id 暂空),拿到主键后再统一挂父,避免插入顺序依赖
for row in plan["inserts"]:
dept = Department(
name=row["name"],
code=row["code"],
company=row["company"],
parent_id=None,
sort_order=row["sort_order"],
is_hidden=row["is_hidden"],
)
db.session.add(dept)
db.session.flush()
code_to_id[row["code"]] = dept.id
created += 1
# [STEP 2] 更新已存在行(按编码 upsert,保留本地多余行)
for item in plan["updates"]:
local, row = item["local"], item["row"]
local.name = row["name"]
local.company = row["company"]
local.sort_order = row["sort_order"]
local.is_hidden = row["is_hidden"]
updated += 1
# [STEP 3] 挂上级:本地已有编码或本次新插入的编码都可作为父
for row in plan["inserts"] + [i["row"] for i in plan["updates"]]:
parent_code = parent_by_code[row["code"]]
if parent_code:
db.session.get(Department, code_to_id[row["code"]]).parent_id = code_to_id.get(parent_code)
db.session.commit()
return created, updated
def _print_report(
rows: list[dict[str, Any]],
plan: dict[str, Any],
problems: list[str],
company_map: dict[str, str],
raw_rows: list[dict[str, str]],
) -> None:
"""Print the dry-run/apply report; problem lines always warn before the summary."""
companies = Counter(r["company_code"] for r in rows)
print("== 公司分布(hrao00 -> 行数)==")
for code, count in sorted(companies.items()):
print(f" {code or '(空)'} x{count} -> {company_map.get(code, '(未映射)')}")
if plan["unmapped"]:
print(f" ⚠ 未映射编码:{plan['unmapped']}")
print(f"== 汇总 == ERP 行 {len(rows)};插入 {len(plan['inserts'])};更新 {len(plan['updates'])};本地保留 {len(plan['kept'])}")
if plan["renames"]:
print("== 更名(users.department 按名称关联,需人工重挂)==")
for old, new, linked in plan["renames"]:
print(f" {old!r} -> {new!r}(名下员工 {linked} 人)")
for line in problems:
print(f" ⚠ {line}")
if not any("⚠" in line for line in problems) and not plan["renames"]:
print(" (无告警)")
# hrao 标志位分布,帮助确认 is_hidden 映射是否正确
for col in ("hrao05", "hrao07", "hrao08"):
dist = Counter(_clean(r.get(col)).upper() for r in raw_rows)
print(f"== {col} 取值分布 == {dict(dist)}")
def main() -> None:
"""Parse args, build the plan, and write only with --apply (single transaction)."""
parser = argparse.ArgumentParser(description="Import ERP HRAO_FILE departments (CSV) into the local tree")
parser.add_argument("--file", type=Path, default=DEFAULT_CSV, help="DBeaver 导出的 HRAO CSV 路径")
parser.add_argument("--company-map", type=Path, default=DEFAULT_COMPANY_MAP, help="hrao00 -> 公司名 JSON")
parser.add_argument("--hidden-mode", choices=HIDDEN_MODES, default="ignore",
help="hrao08 -> is_hidden 映射;默认 ignore(不隐藏)")
parser.add_argument("--allow-unmapped", action="store_true", help="允许未映射公司编码(company 置空)")
parser.add_argument("--company", action="append", default=None,
help="只导入指定 hrao00 的公司(可多次传入,如 --company 0003);缺省导入全部")
parser.add_argument("--apply", action="store_true", help="真正写库;缺省仅 dry-run 预览")
args = parser.parse_args()
company_map = _load_company_map(args.company_map)
raw_rows = _read_csv(args.file)
rows, problems = _normalize_rows(raw_rows, args.hidden_mode)
if args.company:
wanted = {c.strip() for c in args.company}
missing = wanted - {r["company_code"] for r in rows}
if missing:
raise SystemExit(f"CSV 中不存在这些公司编码:{sorted(missing)}")
rows = [r for r in rows if r["company_code"] in wanted]
if args.company:
wanted = {c.strip() for c in args.company}
missing = wanted - {r["company_code"] for r in rows}
if missing:
raise SystemExit(f"CSV 中不存在这些公司编码:{sorted(missing)}")
rows = [r for r in rows if r["company_code"] in wanted]
parent_by_code, parent_problems = _resolve_parents(rows)
parent_by_code, cycle_problems = _break_cycles(rows, parent_by_code)
problems += parent_problems + cycle_problems
problems += _find_name_conflicts(rows, parent_by_code)
app = create_app()
with app.app_context():
plan, plan_problems = plan_import(rows, company_map, args.allow_unmapped)
problems += plan_problems
_print_report(rows, plan, problems, company_map, raw_rows)
fatal = [p for p in problems if "需人工" in p or "未映射的公司编码" in p]
if args.apply and not fatal:
created, updated = apply_plan(plan, parent_by_code)
print(f"✅ 已写入:插入 {created},更新 {updated}(事务已提交)")
elif args.apply:
raise SystemExit("存在需人工处理的告警,已阻止写库;处理后重试或加对应参数。")
else:
print("(dry-run 未写库;确认无误后加 --apply 执行)")
if __name__ == "__main__":
main()
@@ -1,45 +1,180 @@
"""
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_allows_same_name_root_across_companies(app):
"""分支测试意图:两家公司的顶级部门允许同名(按 company 分桶查重),同公司顶级同名仍拒绝。"""
with app.app_context():
create_department({'name': '管理部', 'company': '苏州和信'})
create_department({'name': '管理部', 'company': '泰国合欣'})
with pytest.raises(ValidationError) as exc_info:
create_department({'name': '管理部', 'company': '苏州和信'})
assert exc_info.value.code == 'DEPT.NAME_EXISTS'
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['total'] == 2
subtree = list_department_members(root['id'], include_descendants=True)
assert subtree['total'] == 3
assert all(member.get('department') in ('物料部', '仓储课') for member in subtree['members'])
def test_members_keyword_search_and_pagination(app):
"""分支测试意图:成员接口按 姓名/工号/手机 模糊搜索,并按 page/page_size 分页。"""
with app.app_context():
dept = create_department({'name': '品保部'})
db.session.add_all([
User(username='u1', real_name='张一', employee_id='E001', phone_number='13800000001',
email='u1@example.com', department='品保部', role='user', status='active'),
User(username='u2', real_name='张二', employee_id='E002', phone_number='13800000002',
email='u2@example.com', department='品保部', role='user', status='active'),
User(username='u3', real_name='李三', employee_id='E003', phone_number='13800000003',
email='u3@example.com', department='品保部', role='user', status='active'),
])
db.session.commit()
# 关键词命中工号
by_emp = list_department_members(dept['id'], keyword='E003')
assert by_emp['total'] == 1
assert by_emp['members'][0]['real_name'] == '李三'
# 关键词命中手机号
by_phone = list_department_members(dept['id'], keyword='13800000002')
assert by_phone['total'] == 1
assert by_phone['members'][0]['username'] == 'u2'
# 关键词命中姓名(同姓两人)
by_name = list_department_members(dept['id'], keyword='张')
assert by_name['total'] == 2
# 分页:page_size=2 时第 2 页只剩 1 条
paged = list_department_members(dept['id'], page=2, page_size=2)
assert paged['total'] == 3
assert paged['page'] == 2
assert len(paged['members']) == 1