Compare commits

..
30 Commits
Author SHA1 Message Date
HTEWJ\26070045 2e8405e2f0 fix(migrations): 合并用户多角色与部门树两条迁移头恢复单链 2026-10-30 11:56:14 +08:00
sophie b2fe9b78e2 !29 fix(admin): 部门树首屏默认展开第一层,成员表居中消除集中空白
Merge pull request !29 from 王瑞雪/departmental-structure
2026-10-30 03:29:32 +00:00
sophie 8336ab6349 !28 Merge branch 'dev' into branch-statement-button
Merge pull request !28 from 王瑞雪/branch-statement-button
2026-10-30 02:45:23 +00:00
sophie d64a49548f !27 Merge branch 'dev' into picture-feedback
Merge pull request !27 from 王瑞雪/picture-feedback
2026-10-30 02:43:26 +00:00
HTEWJ\26070045 81eeef944f build(frontend): vite 支持 HXOPS_VITE_POLLING 轮询监听防改动丢失 2026-10-30 09:30:01 +08:00
HTEWJ\26070045 60a8b20bf9 fix(admin): 部门页布局关键样式全面内联化并修正列宽总和 580/600 失配 2026-10-30 09:16:47 +08:00
HTEWJ\26070045 638a46ad0d chore(admin): 部门页加控制台版本标记便于核对浏览器加载版本 2026-10-30 08:52:39 +08:00
HTEWJ\26070045 1b3b63df24 fix(admin): 部门页根高度内联化,外层滚动条消除、两栏各自独立滚动 2026-10-29 20:55:23 +08:00
HTEWJ\26070045 eb468d3c78 fix(admin): 部门树首屏默认展开第一层,成员表居中消除集中空白 2026-10-29 18:58:44 +08:00
HTEWJ\26070045 8e73031e42 fix(admin): 部门成员表列宽紧凑定宽,表格不再撑满面板 2026-10-29 18:49:43 +08:00
HTEWJ\26070045 4105fd92f2 fix(admin): 部门树列贴合内容宽度,剩余宽度全部让给成员面板 2026-10-29 18:38:28 +08:00
HTEWJ\26070045 dd3a671a3d fix(admin): 部门树列宽改为内联样式避免热更滞后 2026-10-29 18:22:25 +08:00
HTEWJ\26070045 ee2b7cdb7e fix(admin): 部门树列定宽消除空白条,右栏弹性铺满并防分页溢出 2026-10-29 18:12:45 +08:00
HTEWJ\26070045 26f25d88c0 fix(admin): 部门成员面板定宽收窄列宽,左树弹性占满剩余宽度 2026-10-29 17:58:35 +08:00
HTEWJ\26070045 90166068ee fix(admin): 部门树页左右两栏锁定视口高度并改用 ElTable 固定表头滚动 2026-10-29 17:48:38 +08:00
HTEWJ\26070045 bf44a5a70e feat(admin): 部门导入脚本支持按公司编码过滤 2026-10-29 17:12:21 +08:00
HTEWJ\26070045 be49b44004 Merge branch 'dev' into departmental-structure 2026-10-29 17:11:21 +08:00
HTEWJ\26070045 8c3df85b2e Merge branch 'dev' into branch-statement-button
# Conflicts:
#	docs/funclist.md
2026-10-29 16:19:40 +08:00
HTEWJ\26070045 97c46625e4 Merge branch 'dev' into branch-statement-button
# Conflicts:
#	docs/funclist.md
2026-10-29 13:47:00 +08:00
HTEWJ\26070045 9dd7184aa7 refactor(admin): 部门管理树形页控件换用 Element Plus 2026-10-22 13:45:11 +08:00
HTEWJ\26070045 ec47e012a7 Merge branch 'dev' into departmental-structure 2026-10-22 13:19:53 +08:00
HTEWJ\26070045 63a86f8944 fix(admin): 分页器补 pr-10 使文字避开全局 select 背景箭头 2026-10-22 10:26:16 +08:00
HTEWJ\26070045 0c27b81654 fix(admin): 分页器复用全局 select 背景箭头消除双箭头叠加 2026-10-22 10:09:21 +08:00
HTEWJ\26070045 ace836c1af fix(admin): 成员面板分页器去除原生箭头并将表头 sticky 下沉到 th 2026-10-22 09:44:31 +08:00
HTEWJ\26070045 2cee02bec1 fix(admin): 修复部门成员面板表头与分页器穿模并锁定列宽 2026-10-22 09:30:09 +08:00
HTEWJ\26070045 194a51bc2d feat(admin): 部门管理改为左树右成员面板的 OA 组织口径 2026-10-22 09:08:04 +08:00
HTEWJ\26070045 e421d2607d feat(branch-statement-button): 增加前端显示时在检索失败分支语句结尾处添加一个按钮。按钮名为【知识库内容清单】 2026-10-21 17:02:30 +08:00
HTEWJ\26070045 396f17a15a docs(funclist): 部门管理标注 HRAO 首次导入已完成 2026-10-08 11:29:43 +08:00
HTEWJ\26070045 f7361905b7 feat(admin): 部门管理新增 ERP HRAO 部门一次性导入脚本 2026-10-08 10:59:35 +08:00
HTEWJ\26070045 48fe19ed71 feat(admin): 部门管理改造为组织树形结构 2026-10-08 09:38:36 +08:00
43 changed files with 2484 additions and 416 deletions

No files matched your search

+4
View File
@@ -101,6 +101,10 @@ backend/data/freight_rpa/
backend/data/shipping_notice/ backend/data/shipping_notice/
backend/data/logs/ backend/data/logs/
backend/data/logs/*.log backend/data/logs/*.log
backend/data/logs/*.log
# ERP HRAO 部门导入的本地数据(CSV 导出与真实公司映射不入库,模板 *.example.json 保留)
backend/scripts/data/*.csv
backend/scripts/data/hrao_company_map.json
# Engramory live memory store (plain text, machine-local) # Engramory live memory store (plain text, machine-local)
/.engramory-memory/ /.engramory-memory/
+19 -5
View File
@@ -1,9 +1,9 @@
""" """
backend/app/api/admin/departments.py backend/app/api/admin/departments.py
用途:管理后台部门 CRUD API(薄路由层)。 用途:管理后台部门 CRUD API(薄路由层,树形结构)。
依赖:admin.blueprint、services/admin/department_service。 依赖:admin.blueprint、services/admin/department_service。
逻辑:/departments* 路由。 逻辑:/departments 平铺列表(兼容旧消费方)、/departments/tree 树、成员名单(支持含下级)。
""" """
from flask import jsonify, request from flask import jsonify, request
@@ -15,10 +15,17 @@ from app.services.admin import department_service
@admin_bp.route('/departments', methods=['GET']) @admin_bp.route('/departments', methods=['GET'])
@require_admin @require_admin
def list_departments(): def list_departments():
"""返回全部部门列表。""" """返回全部部门平铺列表(旧消费方兼容:部门下拉等)。"""
return jsonify(department_service.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']) @admin_bp.route('/departments', methods=['POST'])
@require_admin @require_admin
def create_department(): def create_department():
@@ -31,8 +38,15 @@ def create_department():
@admin_bp.route('/departments/<int:id>/members', methods=['GET']) @admin_bp.route('/departments/<int:id>/members', methods=['GET'])
@require_admin @require_admin
def list_department_members(id: int): def list_department_members(id: int):
"""返回部门员工数量与名单。""" """部门员工分页名单(OA 组织面板口径):include_descendants=1 含下级,keyword 搜姓名/工号/邮箱/手机。"""
return jsonify(department_service.list_department_members(id)) 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']) @admin_bp.route('/departments/<int:id>', methods=['PUT'])
+1 -1
View File
@@ -12,7 +12,7 @@ from flask import Blueprint
chat_bp = Blueprint('chat', __name__) chat_bp = Blueprint('chat', __name__)
# 子模块导入时在同一 Blueprint 上注册原有 URL。 # 子模块导入时在同一 Blueprint 上注册原有 URL。
from . import assets, completions, directory, feedback, previews, sessions, uploads # noqa: E402, F401 from . import assets, capability_list, completions, directory, feedback, previews, sessions, uploads # noqa: E402, F401
from .shared import ( # noqa: E402, F401 from .shared import ( # noqa: E402, F401
CHAT_USER_ATTACHMENT_LIMIT, CHAT_USER_ATTACHMENT_LIMIT,
CHAT_USER_ATTACHMENT_MAX_SIZE, CHAT_USER_ATTACHMENT_MAX_SIZE,
+31
View File
@@ -0,0 +1,31 @@
"""
api/chat/capability_list.py
用途:聊天端「知识库内容清单」查询接口,作为知识库未命中兜底回复按钮的数据源。
依赖:chat.shared(公共上下文与异常)、chat_bp、services.chat.capability_list。
逻辑:GET /api/chat/capability-list?agent_id=...,经 require_agent_permission 鉴权后
返回常用问题中该应用「能力清单条目」的标准答案;未配置时抛 404 业务错误。
"""
from __future__ import annotations
from .shared import * # noqa: F403
from . import chat_bp
from app.services.chat.capability_list import get_agent_capability_list
@chat_bp.route('/capability-list', methods=['GET'])
@require_agent_permission
def get_capability_list():
"""
获取当前应用的知识库内容清单。
用途:AI 回复命中知识库未命中兜底语句时,前端【知识库内容清单】按钮点击后调用。
核心逻辑:
1. require_agent_permission 从 query 读取 agent_id 并校验用户对该应用的访问权限;
2. 委托 services.chat.capability_list 返回「能力清单条目」标准答案;
3. 未配置时抛 code=CHAT.CAPABILITY_LIST_NOT_FOUND(404),前端按错误码本地化提示。
参数约束:agent_id 必须来自当前会话路由(当前聊天应用),禁止跨应用探测他人条目。
"""
agent = getattr(g, 'current_agent', None)
if agent is None:
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing agent context', http_status=500)
return jsonify(get_agent_capability_list(agent))
+18 -5
View File
@@ -1,27 +1,40 @@
""" """
backend/app/models/department.py backend/app/models/department.py
用途:部门组织模型。 用途:部门组织模型(parent_id 邻接表树形结构,对应 OA 组织架构)。
依赖:models.base.Base。 依赖:models.base.Base。
逻辑:parent_id 自关联构成部门树;sort_order 为同级排序(对应 ERP HRAO hrao09 阶层序号),
is_hidden 对应 hrao08「在组织框架图中显示否」。树的组装与校验在 services/admin/department_service。
""" """
from __future__ import annotations from __future__ import annotations
from typing import Optional from typing import Optional
from sqlalchemy import String, Text from sqlalchemy import Boolean, ForeignKey, String, Text
from sqlalchemy.orm import Mapped, mapped_column from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base from app.models.base import Base
class Department(Base): class Department(Base):
"""部门表:存储公司部门列表。""" """部门表:存储公司部门树(parent_id 邻接表)。"""
__tablename__ = 'departments' __tablename__ = 'departments'
id: Mapped[int] = mapped_column(primary_key=True) 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) code: Mapped[Optional[str]] = mapped_column(String(50), unique=True)
company: Mapped[Optional[str]] = mapped_column(String(100)) company: Mapped[Optional[str]] = mapped_column(String(100))
description: Mapped[Optional[str]] = mapped_column(Text) 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 backend/app/services/admin/department_service.py
用途:管理端部门 CRUD 业务编排。 用途:管理端部门树 CRUD 业务编排(parent_id 邻接表)。
依赖:models.Department、app.core.errors。 依赖:models.Department、models.User、app.core.errors。
逻辑:由 api/admin/departments.py 调用。 逻辑:api/admin/departments.py 调用;成员归属沿用 users.department 文本按部门名关联;
树顶公司层不入库,由前端按 company 字段虚拟分组。
""" """
from __future__ import annotations from __future__ import annotations
from typing import Any from collections import defaultdict
from typing import Any, Optional
from sqlalchemy import func from sqlalchemy import func
from app import db 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 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: def serialize_department(dept: Department) -> dict:
"""部门 ORM → API dict。""" """部门 ORM → API dict(平铺行,供部门下拉等旧消费方兼容)。"""
return { return {
'id': dept.id, 'id': dept.id,
'name': dept.name, 'name': dept.name,
'code': dept.code, 'code': dept.code,
'company': dept.company, 'company': dept.company,
'description': dept.description, '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]: def _member_count_by_name() -> dict[str, int]:
"""返回全部部门(按 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:
""" """
查询指定部门的员工名单。 全员按部门名聚合计数。
核心逻辑: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 文本关联查询成员。 def _sibling_sort_key(node: dict) -> tuple:
[STEP 3] 返回人数与脱敏后的管理端成员资料。 """同级排序: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) dept = db.session.get(Department, dept_id)
if not dept: if not dept:
raise NotFoundError('Not found') raise NotFoundError('Department not found')
users = db.session.query(User).filter(User.department == dept.name).order_by(User.real_name.asc(), User.username.asc()).all() 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 { return {
'department': serialize_department(dept), 'department': serialize_department(dept),
'count': len(users), 'total': total,
'page': page,
'page_size': page_size,
'members': [ 'members': [
{ {
'id': user.id, 'id': user.id,
@@ -61,6 +208,8 @@ def list_department_members(dept_id: int) -> dict:
'real_name': user.real_name, 'real_name': user.real_name,
'employee_id': user.employee_id, 'employee_id': user.employee_id,
'email': user.email, 'email': user.email,
'phone_number': user.phone_number,
'department': user.department,
'status': user.status, 'status': user.status,
} }
for user in users 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: def create_department(data: dict[str, Any]) -> dict:
""" """
创建部门。 创建部门。
[STEP 1] 校验名称必填、上级存在、同级不重名、编码全局唯一。
[STEP 2] 公司未填时继承上级部门 company(树顶公司分组依赖该字段)。
Returns: Returns:
{ id, name }。 { id, name }。
Raises: Raises:
ValidationError: name 缺失或 name/code 重复。 ValidationError: NAME_REQUIRED / PARENT_INVALID / NAME_EXISTS / CODE_EXISTS。
""" """
if not data.get('name'): name = _clean_str(data.get('name'))
raise ValidationError('Name is required') if not name:
if db.session.query(Department).filter_by(name=data['name']).first(): raise ValidationError('Department name is required', code=ERR_NAME_REQUIRED)
raise ValidationError('Name exists') parent_id = data.get('parent_id')
if data.get('code') and db.session.query(Department).filter_by(code=data['code']).first(): parent = _validate_parent(parent_id)
raise ValidationError('Code exists') 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( dept = Department(
name=data['name'], name=name,
code=data.get('code'), code=code,
company=data.get('company'), company=company,
description=data.get('description'), 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.add(dept)
db.session.commit() 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: def update_department(dept_id: int, data: dict[str, Any]) -> None:
""" """
更新部门字段。 更新部门字段(含上级转移、同级排序、隐藏标记)。
[STEP 1] 名称变更时按「变更后的上级」做同级查重。
[STEP 2] 上级变更时校验存在性并防成环。
[STEP 3] 编码变更时全局唯一校验。
Raises: Raises:
NotFoundError: 部门不存在。 NotFoundError: 部门不存在。
ValidationError: name/code 与其它记录冲突。 ValidationError: NAME_EXISTS / PARENT_INVALID / CYCLE_FORBIDDEN / CODE_EXISTS。
""" """
dept = db.session.get(Department, dept_id) dept = db.session.get(Department, dept_id)
if not dept: if not dept:
raise NotFoundError('Not found') raise NotFoundError('Department not found')
if 'name' in data:
if db.session.query(Department).filter(Department.name == data['name'], Department.id != dept_id).first(): if 'parent_id' in data:
raise ValidationError('Name exists') parent = _validate_parent_change(dept, data['parent_id'])
dept.name = data['name'] dept.parent_id = parent.id if parent else None
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']
if 'company' in data: 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: 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() db.session.commit()
def delete_department(dept_id: int) -> None: def delete_department(dept_id: int) -> None:
"""删除部门(不存在时静默成功)。""" """
删除部门。
Raises:
ConflictError: 存在下级部门(HAS_CHILDREN)或名下仍有员工(HAS_MEMBERS)时禁止删除。
"""
dept = db.session.get(Department, dept_id) dept = db.session.get(Department, dept_id)
if dept: if not dept:
db.session.delete(dept) return
db.session.commit() 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,68 @@
"""
services/chat/capability_list.py
用途:查询指定智能体在常用问题(QuickQuestion)中的「能力清单」条目标准答案。
依赖:models.QuickQuestion、core.errors.AppError、SQLAlchemy db。
逻辑:Dify 知识库未命中兜底回复会在前端展示【知识库内容清单】按钮;按钮点击后由
api/chat/capability_list.py 调用本模块,按 agent_id 过滤全局条目并返回标准答案。
管理端维护约定:条目标题形如「<应用名>·能力清单条目」,因此以标题含「能力清单」
作为识别关键字,应用归属仍以 agent_id 外键为准(禁止按标题前缀解析应用名)。
"""
from __future__ import annotations
from typing import Any
from app import db
from app.core.errors import AppError
from app.models import QuickQuestion
# 能力清单条目的标题识别关键字(管理端维护约定,见模块 docstring)。
CAPABILITY_LIST_TITLE_KEYWORD = '能力清单'
def get_agent_capability_list(agent: Any) -> dict[str, Any]:
"""
查询智能体的知识库内容清单条目。
用途:聊天端兜底回复【知识库内容清单】按钮的数据来源。
核心逻辑:
1. 仅匹配全局条目(user_id 为空)且归属当前 agent_id;
2. 标题须含「能力清单」关键字,且标准答案非空;
3. 多条命中时按 sort_order、id 取第一条,保证返回稳定。
Args:
agent: 已通过 require_agent_permission 鉴权的 Agent 模型实例,禁止传 None。
Returns:
含 id/agent_id/title/question/answer 的条目字典,answer 为标准答案原文。
Raises:
AppError: code=CHAT.CAPABILITY_LIST_NOT_FOUND,表示该应用尚未配置能力清单条目。
"""
agent_id = getattr(agent, 'id', None)
if not agent_id:
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing agent id', http_status=500)
entry = (
db.session.query(QuickQuestion)
.filter(
QuickQuestion.agent_id == agent_id,
QuickQuestion.user_id.is_(None),
QuickQuestion.title.contains(CAPABILITY_LIST_TITLE_KEYWORD),
QuickQuestion.answer.isnot(None),
QuickQuestion.answer != '',
)
.order_by(QuickQuestion.sort_order.asc(), QuickQuestion.id.asc())
.first()
)
if entry is None:
raise AppError(
code='CHAT.CAPABILITY_LIST_NOT_FOUND',
message='capability list entry is not configured for this agent',
http_status=404,
)
return {
'id': entry.id,
'agent_id': entry.agent_id,
'title': entry.title,
'question': entry.question,
'answer': entry.answer or '',
}
@@ -0,0 +1,37 @@
"""merge migration heads: 合并「用户多角色/意见反馈附图」与「部门树」两条迁移头
用途:c375467a21f9 与 eff84b4f6171 两条并行迁移链各自成头,导致
``flask db upgrade`` 报 Multiple head revisions(见 scripts/check_migration_heads.py)。
本迁移仅归并两条链,无任何表结构变更,upgrade/downgrade 均为空操作。
依赖关系:down_revision 同时挂载两条待归并的迁移头
- c375467a21f9(合并用户多角色与意见反馈附图两条 alembic 头)
- eff84b4f6171(合并部门树与最新 dev 迁移头)
逻辑关系:作为迁移图的新唯一 head,位于两条链收敛点之后,
后续新迁移应以本 revision 为 down_revision。
Revision ID: d143df04ab5a
Revises: c375467a21f9, eff84b4f6171
Create Date: 2026-10-30
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'd143df04ab5a'
down_revision = ('c375467a21f9', 'eff84b4f6171')
branch_labels = None
depends_on = None
def upgrade():
"""纯 merge 迁移:仅收敛迁移图,无结构变更。"""
pass
def downgrade():
"""拆开 merge 点即回到原两条并行头,无需回滚任何结构。"""
pass
@@ -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 tests/services/admin/test_department_service.py
用途:department_service CRUD 单元测试。 用途:department_service 部门树 CRUD、树组装、成员口径单元测试。
覆盖:父子挂接 / 同级查重 / 编码唯一 / 防成环 / 删除保护(有下级、有员工)/ 成员数含下级汇总。
""" """
import pytest import pytest
from app import db from app import db
from app.core.errors import NotFoundError, ValidationError from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.models import Department from app.models import Department, User
from app.services.admin.department_service import ( from app.services.admin.department_service import (
create_department, create_department,
delete_department, delete_department,
list_department_members,
list_department_tree,
list_departments, list_departments,
update_department, update_department,
) )
def test_department_crud(app): def test_department_crud_with_parent(app):
"""断言:父子挂接进树、字段可更新、有下级禁删、无下级可删。"""
with app.app_context(): with app.app_context():
created = create_department({'name': 'R&D', 'code': 'RD', 'company': 'HX'}) parent = create_department({'name': '品保部', 'code': 'QA', 'company': 'HX'})
assert created['name'] == 'R&D' child = create_department({'name': '品保课', 'code': 'QA1', 'parent_id': parent['id'], 'sort_order': 2})
assert child['name'] == '品保课'
items = list_departments() 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'}) update_department(child['id'], {'sort_order': 9, 'is_hidden': True})
dept = db.session.get(Department, created['id']) dept = db.session.get(Department, child['id'])
assert dept.description == 'Research' assert dept.sort_order == 9
assert dept.is_hidden is True
delete_department(created['id']) # 分支测试意图:存在下级部门时删除必须被 HAS_CHILDREN 拦截
assert db.session.get(Department, created['id']) is None 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(): with app.app_context():
create_department({'name': 'Sales'}) create_department({'name': 'Sales'})
with pytest.raises(ValidationError, match='Name exists'): with pytest.raises(ValidationError) as exc_info:
create_department({'name': 'Sales'}) 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): def test_update_department_not_found(app):
with app.app_context(): with app.app_context():
with pytest.raises(NotFoundError): with pytest.raises(NotFoundError):
update_department(99999, {'name': 'X'}) 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
+10
View File
@@ -105,6 +105,15 @@
| 反馈企业微信群通知 | 已实现 | 反馈入库后通过 `WECOM_FEEDBACK_BOT_WEBHOOK` 即时推送到企业微信群;未配置 webhook 时静默跳过,不影响用户提交 | | 反馈企业微信群通知 | 已实现 | 反馈入库后通过 `WECOM_FEEDBACK_BOT_WEBHOOK` 即时推送到企业微信群;未配置 webhook 时静默跳过,不影响用户提交 |
| 反馈截图附件 | 已实现 | 意见反馈支持粘贴/上传截图附件(每条最多 5 张),管理端报表可查看附图缩略图与大图预览 | | 反馈截图附件 | 已实现 | 意见反馈支持粘贴/上传截图附件(每条最多 5 张),管理端报表可查看附图缩略图与大图预览 |
## 知识库内容清单按钮(2026-10)
| 功能项 | 状态 | 说明 |
| ---------------------- | ------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 兜底回复触发识别 | 已实现 | Dify 知识库未命中兜底回复末尾追加 `[知识库能力清单]` 标记(兼容「内容清单」写法)时,前端识别并在语句结尾渲染【知识库内容清单】按钮;对无标记的已发布兜底原句按特征片段兜底识别,历史会话同样生效 |
| 标记展示剥离 | 已实现 | 渲染前从正文剥离标记及其前导标点(含流式半截标记裁剪),用户不会看到原始标记符号 |
| 能力清单标准答案查询 | 已实现 | `GET /api/chat/capability-list?agent_id=`(`require_agent_permission` 鉴权)返回常用问题中该应用「能力清单条目」(标题含「能力清单」的全局条目)的标准答案;未配置返回 `CHAT.CAPABILITY_LIST_NOT_FOUND` |
| 内容清单弹窗 | 已实现 | 点击按钮后按当前会话应用拉取标准答案并弹窗展示(Markdown 渲染);未配置时按错误码本地化提示,文案同步 zh-CN/zh-TW/en/th |
## 年度教育训练计划 ## 年度教育训练计划
独立于下方「新人培训 Agent」。需求已整理,尚未开发。 独立于下方「新人培训 Agent」。需求已整理,尚未开发。
@@ -683,6 +692,7 @@
| 管理端运营总览 | 「数据报表」新增「运营总览」入口:展示对话量/活跃用户/活跃应用/好评率、对话趋势与环比、Top 应用与低使用应用、低评分回答与未处理反馈,复用 chat_logs/feedbacks/general_feedbacks/agents/应用授权数据 | 已实现(数据处理) | P1 | | 管理端运营总览 | 「数据报表」新增「运营总览」入口:展示对话量/活跃用户/活跃应用/好评率、对话趋势与环比、Top 应用与低使用应用、低评分回答与未处理反馈,复用 chat_logs/feedbacks/general_feedbacks/agents/应用授权数据 | 已实现(数据处理) | P1 |
| 管理端问题分析 | 「数据报表」新增「问题分析」入口,第一版为页面骨架与空状态,不伪造数据 | 已实现(骨架) | P2 | | 管理端问题分析 | 「数据报表」新增「问题分析」入口,第一版为页面骨架与空状态,不伪造数据 | 已实现(骨架) | P2 |
| 管理端时间范围统一 | 「数据报表」各数据页时间范围筛选器统一为「近 7 天 / 30 天 / 90 天」,并同步四语言文案 | 已实现 | P1 | | 管理端时间范围统一 | 「数据报表」各数据页时间范围筛选器统一为「近 7 天 / 30 天 / 90 天」,并同步四语言文案 | 已实现 | P1 |
| 管理端部门管理(组织树) | 部门管理改为树形组织结构(对应 OA 组织架构,层级来源对齐 ERP HRAO:hrao01 编码 / hrao02 名称 / hrao06 上级 / hrao09 同级排序 / hrao08 隐藏标记):`departments` 表增加 `parent_id`(邻接表)/ `sort_order` / `is_hidden`(迁移 `dp1a2b3c4d5e6`),`name` 全局唯一放开为「同一上级下唯一」;页面为左树右成员面板(OA 组织结构口径,控件已按 Element Plus 迁移规范 Element 化:ElTable/ElPagination/ElTag/ElDialog/ElMessageBox,树行为自定义层级结构),树顶公司层为前端按 `company` 字段虚拟分组不入库;节点支持添加子部门/编辑/删除(有下级或有员工禁删)、搜索命中自动展开、全部展开/收起;员工展示改为 OA 组织结构口径(左树右成员面板):树表员工计数列剔除,点击部门节点右侧分页展示成员名单(关键词搜索姓名/工号/邮箱/手机、每页 20/50/100 可调,「含下级部门」口径可切换,成员接口 `members` 支持 keyword/page/page_size);新增错误码 `DEPT.*` 四语言。ERP 一次性导入脚本已提供(`backend/scripts/import_departments_from_hrao.py`:DBeaver 导出 HRAO_FILE CSV + 公司映射取自 HRAA_FILE,dry-run 默认、`--apply` 按编码 upsert 合并、悬空/成环/重名告警兜底),已于 2026-10-08 执行首次全量导入(366 部门 / 7 公司,本地 56 行全部按编码命中更新);持续同步仍未做 | 已实现 | P1 |
| 管理端常用问题模糊匹配 | 「常用问题」编辑弹窗新增「启用模糊匹配」开关与阈值(0.50–1.00,默认 0.80,逐条目独立、以启用 FAQ 缓存为前提):精确未命中时按相似度兜底直答,容忍加前后缀与近义词差异;得分取 max(编辑距离相似度, 包含覆盖率),命中方式与得分写入 ChatLog payload(match_type / match_score / matched_text) | 已实现 | P2 | | 管理端常用问题模糊匹配 | 「常用问题」编辑弹窗新增「启用模糊匹配」开关与阈值(0.50–1.00,默认 0.80,逐条目独立、以启用 FAQ 缓存为前提):精确未命中时按相似度兜底直答,容忍加前后缀与近义词差异;得分取 max(编辑距离相似度, 包含覆盖率),命中方式与得分写入 ChatLog payload(match_type / match_score / matched_text) | 已实现 | P2 |
--- ---
+1 -1
View File
@@ -200,7 +200,7 @@ section.admin-table-section 一张圆角卡片,页面上只此一层
| 用户管理 | 列表、筛选、三个业务弹窗、删除和改角色确认已按 §3、§4 对齐。筛选宽度和两列表单写在页面里。 | | 用户管理 | 列表、筛选、三个业务弹窗、删除和改角色确认已按 §3、§4 对齐。筛选宽度和两列表单写在页面里。 |
| 知识库分组 | 列表骨架、行内链接按钮、删除确认、创建分组、Dify 设置和健康检查已对齐。 | | 知识库分组 | 列表骨架、行内链接按钮、删除确认、创建分组、Dify 设置和健康检查已对齐。 |
| 应用配置 | 列表、状态标签、测试弹窗、授权弹窗、删除确认和 680px 创建/编辑表单内部已对齐。保存仍走原来的 `save` 事件。 | | 应用配置 | 列表、状态标签、测试弹窗、授权弹窗、删除确认和 680px 创建/编辑表单内部已对齐。保存仍走原来的 `save` 事件。 |
| 部门管理 | 列表已用 `AdminListPage`。搜索、表头排序、行内链接、480px 表单、员工名单和删除确认已按 §3、§4 对齐。列表仍是本地过滤和排序,没有分页。 | | 部门管理 | 已改为左树右成员面板的组织树页(非 AdminListPage 列表骨架,页面头注释有说明)。树行内链接按钮、成员 ElTable/ElPagination/ElTag、680px 表单(含上级部门/同级排序/隐藏标记)和 ElMessageBox 删除确认已按 §4 对齐;成员分页走服务端。 |
| 公告管理 | 列表已用 `AdminListPage`。发布/编辑是 680px 对话框,详情是描述列表,删除确认已对齐。 | | 公告管理 | 列表已用 `AdminListPage`。发布/编辑是 680px 对话框,详情是描述列表,删除确认已对齐。 |
| 关联服务 | 列表已用 `AdminListPage`。启用用 `ElSwitch`,表单 480px,删除确认已对齐。 | | 关联服务 | 列表已用 `AdminListPage`。启用用 `ElSwitch`,表单 480px,删除确认已对齐。 |
| 知识库分组 | 外层不再套第二张卡片,列表骨架改为 `AdminListPage`。 | | 知识库分组 | 外层不再套第二张卡片,列表骨架改为 `AdminListPage`。 |
+17 -3
View File
@@ -584,10 +584,24 @@ export const updateAdminUserPermissions = (userId: number, agentIds: number[]) =
body: JSON.stringify({ agent_ids: agentIds }), body: JSON.stringify({ agent_ids: agentIds }),
}); });
// Departments // Departments(树形结构:/tree 返回 children 嵌套,成员支持含下级)
export const listAdminDepartments = () => requestJson<any[]>('/api/admin/departments', auth()); export const listAdminDepartments = () => requestJson<any[]>('/api/admin/departments', auth());
export const listAdminDepartmentMembers = (id: number) => export const listAdminDepartmentTree = () => requestJson<any[]>('/api/admin/departments/tree', auth());
requestJson(`/api/admin/departments/${id}/members`, auth()); export interface AdminDepartmentMembersQuery {
includeDescendants?: boolean;
keyword?: string;
page?: number;
pageSize?: number;
}
export const listAdminDepartmentMembers = (id: number, query: AdminDepartmentMembersQuery = {}) => {
const params = new URLSearchParams();
if (query.includeDescendants) params.set('include_descendants', '1');
if (query.keyword?.trim()) params.set('keyword', query.keyword.trim());
if (query.page && query.page > 1) params.set('page', String(query.page));
if (query.pageSize && query.pageSize !== 20) params.set('page_size', String(query.pageSize));
const qs = params.toString();
return requestJson(`/api/admin/departments/${id}/members${qs ? `?${qs}` : ''}`, auth());
};
export const createAdminDepartment = (payload: Record<string, unknown>) => export const createAdminDepartment = (payload: Record<string, unknown>) =>
requestJson('/api/admin/departments', { method: 'POST', ...jsonAuth(), body: JSON.stringify(payload) }); requestJson('/api/admin/departments', { method: 'POST', ...jsonAuth(), body: JSON.stringify(payload) });
export const updateAdminDepartment = (id: number, payload: Record<string, unknown>) => export const updateAdminDepartment = (id: number, payload: Record<string, unknown>) =>
@@ -1,219 +1,492 @@
/** /**
* features/admin/modules/departments/DepartmentsPage.vue * features/admin/modules/departments/DepartmentsPage.vue
* 用途:部门管理列表。一张卡片里放标题、添加按钮、搜索、表格。 * 用途:部门管理独立页面——左树(公司虚拟分组 + 部门层级)右成员面板(OA 组织结构口径)。
* 依赖:AdminListPage、useDepartmentsAdmin、element-plus、部门表单和员工名单弹窗。 * 依赖:useDepartmentsAdmin、DepartmentFormModal、element-plus、@element-plus/icons-vue。
* 逻辑:路由 /admin/departments。骨架用 AdminListPage。筛选、列和两个弹窗留在本页。 * 逻辑:路由 /admin/departments。左侧点击部门节点后,右侧按分页 + 关键词展示该部门成员
* 名称、编码、公司用表头排序,排的是当前过滤结果。删除用 Element 确认框。 * (含下级口径可切换);删除确认走 ElMessageBox。控件按 ELEMENT_MIGRATION.md 全量 Element 化,
* 表格用 Element stripe 斑马纹。员工数、编辑、删除用 Element 链接按钮,悬停文案走 i18n title。 * 树本身是自定义层级结构,不是 ElTable/ElTree 列表页,故不走 AdminListPage 骨架。
*/ */
<script setup lang="ts"> <script setup lang="ts">
import { computed, onMounted, ref } from 'vue'; import { computed, onMounted } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { Delete, Edit, Plus, User } from '@element-plus/icons-vue'; import { ElButton, ElCheckbox, ElConfigProvider, ElEmpty, ElIcon, ElInput, ElLoading, ElPagination, ElTable, ElTableColumn, ElTag } from 'element-plus';
import { import {
ElButton, ArrowDown,
ElInput, ArrowRight,
ElLoading, Delete,
ElTable, Edit,
ElTableColumn, Expand,
} from 'element-plus'; Fold,
FolderAdd,
Hide,
OfficeBuilding,
Plus,
Search,
} from '@element-plus/icons-vue';
import DepartmentFormModal from './components/DepartmentFormModal.vue';
import { useDepartmentsAdmin } from './composables/useDepartmentsAdmin';
import { useElementProvider } from '@/features/admin/composables/useElementProvider';
import type { AdminDepartmentTreeNode } from '@/features/admin/types/admin.types';
import 'element-plus/dist/index.css'; import 'element-plus/dist/index.css';
import 'element-plus/theme-chalk/dark/css-vars.css'; import 'element-plus/theme-chalk/dark/css-vars.css';
import '@/features/admin/styles/element-trial.css'; import '@/features/admin/styles/element-trial.css';
import AdminListPage from '@/features/admin/components/AdminListPage.vue';
import type { AdminDepartmentMembersResponse, AdminDepartmentRow } from '@/features/admin/types/admin.types';
import DepartmentFormModal from './components/DepartmentFormModal.vue';
import DepartmentMembersModal from './components/DepartmentMembersModal.vue';
import { useDepartmentsAdmin, type DeptSortKey } from './composables/useDepartmentsAdmin';
import { listAdminDepartmentMembers } from '@/features/admin/api/admin.api';
import { useMessage } from '@/shared/composables/useMessage';
const vLoading = ElLoading.directive; const vLoading = ElLoading.directive;
const { t } = useI18n(); const { t, te } = useI18n();
const msg = useMessage(); const { elementLocale } = useElementProvider();
const showMembersModal = ref(false);
const departmentMembers = ref<AdminDepartmentMembersResponse | null>(null);
const { const {
filteredDepartments, displayRows,
parentOptions,
form, form,
searchQuery, searchQuery,
sortKey,
sortDir,
isLoading, isLoading,
isListLoading,
isSaving, isSaving,
showFormModal, showFormModal,
loadAll, loadAll,
applySort, toggleNode,
toggleCompany,
expandAll,
collapseAll,
openCreateModal, openCreateModal,
openEditModal, openEditModal,
closeFormModal, closeFormModal,
saveDepartment, saveDepartment,
deleteDepartment, deleteDepartment,
selectedDeptId,
selectedDept,
selectedDeptPath,
memberData,
memberLoading,
memberKeyword,
memberIncludeDescendants,
memberPage,
memberPageSize,
selectDept,
setMemberKeyword,
setMemberIncludeDescendants,
setMemberPage,
setMemberPageSize,
} = useDepartmentsAdmin(); } = useDepartmentsAdmin();
const defaultSort = computed(() => ({ /** 成员面板总页数(由 total / page_size 推导)。 */
prop: sortKey.value || 'name', const memberTotalPages = computed(() => {
order: sortDir.value === 'desc' ? 'descending' as const : 'ascending' as const, const data = memberData.value;
})); if (!data || data.page_size <= 0) return 1;
return Math.max(1, Math.ceil(data.total / data.page_size));
});
const emptyText = computed(() => ( /** 左树空状态文案:搜索无结果或尚无部门。 */
const treeEmptyText = computed(() => (
searchQuery.value.trim() ? t('admin.dept.noSearchResults') : t('admin.dept.noDepts') searchQuery.value.trim() ? t('admin.dept.noSearchResults') : t('admin.dept.noDepts')
)); ));
/** /** 成员状态 → 本地化标签;未知状态回退显示原值。 */
* 把 Element 表头排序交给本地列表。 const statusLabel = (status?: string): string => {
* 核心逻辑:只接受名称、编码、公司;第三次点击 order 为空时清空排序。 if (!status) return '-';
* @param payload.prop - 列字段 const key = `admin.dept.members.status.${status}`;
* @param payload.order - ascending、descending 或空 return te(key) ? t(key) : status;
*/ };
function onSortChange(payload: { prop: string | null; order: string | null }): void {
const field = payload.prop;
const sortable = field === 'name' || field === 'code' || field === 'company';
if (sortable && payload.order) {
applySort(field as DeptSortKey, payload.order === 'descending' ? 'desc' : 'asc');
return;
}
applySort('', '');
}
/** /** 成员状态 → ElTag 类型:启用 success,待审核 warning,其余 info。 */
* 打开编辑弹窗。表格插槽行类型较宽,这里收成部门行。 const statusTagType = (status?: string): 'success' | 'warning' | 'info' => {
* @param row - 当前表格行 if (status === 'active') return 'success';
*/ if (status === 'pending') return 'warning';
function editDepartment(row: AdminDepartmentRow): void { return 'info';
openEditModal(row); };
}
/** /** 公司虚拟分组行 key 去前缀,得到分组 key(用于展开状态)。 */
* 加载并展示指定部门的员工名单。 const companyGroupKey = (rowKey: string): string => rowKey.slice('company:'.length);
* 核心逻辑:请求成功才打开弹窗;失败只提示,不打开空名单。
* @param departmentId - 部门主键
*/
async function openDepartmentMembers(departmentId: number): Promise<void> {
try {
departmentMembers.value = await listAdminDepartmentMembers(departmentId) as AdminDepartmentMembersResponse;
showMembersModal.value = true;
} catch (error) {
msg.error((error as Error).message || t('admin.msg.requestFailed'));
}
}
onMounted(() => { onMounted(() => {
// 【版本标记】用于核对浏览器加载的是否为本版代码;确认后可移除
console.info('[departments] UI build v8 (2026-10-30): 树列贴合内容/成员表580定宽居中/默认展开第一层/两栏独立滚动');
void loadAll(); void loadAll();
}); });
</script> </script>
<template> <template>
<AdminListPage :loading="isLoading"> <ElConfigProvider :locale="elementLocale">
<template #title> <!-- 高度/布局写内联样式:外层内容列不再出现整页滚动条,滚动只发生在左右两栏各自内部 -->
<h2 class="section-title">{{ t('admin.dept.title') }}</h2> <section
<p class="section-desc mt-1">{{ t('admin.dept.subtitle') }}</p> class="admin-table-section admin-dept-page"
</template> style="height: 100%; min-height: 0; display: flex; flex-direction: column; overflow: hidden;"
<template #actions> >
<ElButton type="primary" :icon="Plus" @click="openCreateModal"> <header class="admin-table-header admin-table-header--stacked">
<div>
<h2 class="section-title">{{ t('admin.dept.title') }}</h2>
<p class="section-desc mt-1">{{ t('admin.dept.subtitle') }}</p>
</div>
<ElButton type="primary" :icon="Plus" @click="openCreateModal()">
{{ t('admin.dept.add') }} {{ t('admin.dept.add') }}
</ElButton> </ElButton>
</template> </header>
<template #filters>
<!-- 筛选条:左树搜索 + 展开/收起,一条分隔线与内容区分开 -->
<div class="admin-dept-filter">
<ElInput <ElInput
v-model="searchQuery" v-model="searchQuery"
class="admin-dept-filter__search"
:prefix-icon="Search"
clearable clearable
class="dept-filter-search"
:placeholder="t('admin.dept.searchPlaceholder')" :placeholder="t('admin.dept.searchPlaceholder')"
/> />
</template> <ElButton text :icon="Expand" :title="t('admin.dept.expandAll')" @click="expandAll" />
<ElButton text :icon="Fold" :title="t('admin.dept.collapseAll')" @click="collapseAll" />
</div>
<ElTable <div v-loading="isLoading" class="admin-dept-body" style="flex: 1; min-height: 0; display: flex; align-items: stretch; overflow-x: auto;">
v-loading="isListLoading" <!-- 左侧:组织树(公司虚拟分组 + 层级缩进);定宽写在 style 上,避免 HMR 样式层滞后导致宽度不生效 -->
class="hx-admin-table" <div class="admin-dept-tree" style="width: max-content; min-width: 260px; max-width: 45%; flex-shrink: 0;">
:data="filteredDepartments" <ElEmpty v-if="displayRows.length === 0" :description="treeEmptyText" :image-size="80" />
row-key="id" <template v-for="row in displayRows" :key="row.key">
stripe <!-- 公司虚拟分组行(不入库,前端按 company 字段归堆) -->
:default-sort="defaultSort" <div
:empty-text="emptyText" v-if="row.kind === 'company'"
@sort-change="onSortChange" class="admin-dept-tree__row admin-dept-tree__row--company"
> @click="toggleCompany(companyGroupKey(row.key))"
<ElTableColumn prop="name" :label="t('admin.dept.headers.name')" sortable="custom" min-width="200">
<template #default="{ row }">
<div :title="row.name">{{ row.name }}</div>
<p v-if="row.description" class="hx-element-hint dept-desc" :title="row.description">
{{ row.description }}
</p>
</template>
</ElTableColumn>
<ElTableColumn prop="code" :label="t('admin.dept.headers.code')" sortable="custom" min-width="140">
<template #default="{ row }">{{ row.code || '-' }}</template>
</ElTableColumn>
<ElTableColumn prop="company" :label="t('admin.dept.headers.company')" sortable="custom" min-width="180">
<template #default="{ row }">{{ row.company || '-' }}</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.dept.headers.members')" width="120" align="center">
<template #default="{ row }">
<ElButton
link
type="primary"
:icon="User"
:title="t('admin.dept.actions.viewMembers')"
@click="openDepartmentMembers((row as AdminDepartmentRow).id)"
> >
{{ row.member_count || 0 }} <ElIcon class="admin-dept-tree__chevron">
</ElButton> <component :is="row.expanded ? ArrowDown : ArrowRight" />
</template> </ElIcon>
</ElTableColumn> <ElIcon class="admin-dept-tree__company-icon"><OfficeBuilding /></ElIcon>
<ElTableColumn :label="t('admin.dept.headers.actions')" width="120" align="right"> <span class="admin-dept-tree__name" :title="row.company">{{ row.company }}</span>
<template #default="{ row }">
<div class="dept-row-actions">
<ElButton <ElButton
link link
type="primary" type="primary"
:icon="Edit" :icon="FolderAdd"
:title="t('admin.dept.actions.edit')" :title="t('admin.dept.addChild')"
@click="editDepartment(row as AdminDepartmentRow)" @click.stop="openCreateModal(null, row.company)"
/>
<ElButton
link
type="danger"
:icon="Delete"
:title="t('admin.dept.actions.delete')"
@click="deleteDepartment((row as AdminDepartmentRow).id)"
/> />
</div> </div>
<!-- 部门行(层级缩进;点击选中 → 右侧出成员面板) -->
<div
v-else
class="admin-dept-tree__row"
:class="{ 'is-selected': selectedDeptId === row.node!.id }"
:style="{ paddingLeft: `${(row.depth - 1) * 16 + 4}px` }"
@click="selectDept(row.node!)"
>
<button
v-if="row.hasChildren"
type="button"
class="admin-dept-tree__toggle"
:title="row.expanded ? t('admin.dept.collapse') : t('admin.dept.expand')"
@click.stop="toggleNode(row.node!.id)"
>
<ElIcon>
<component :is="row.expanded ? ArrowDown : ArrowRight" />
</ElIcon>
</button>
<span v-else class="admin-dept-tree__toggle" />
<span class="admin-dept-tree__name" :title="row.node!.name">{{ row.node!.name }}</span>
<ElTag
v-if="row.node!.is_hidden"
type="warning"
effect="light"
size="small"
:icon="Hide"
:title="t('admin.dept.fields.hiddenHint')"
>
{{ t('admin.dept.tags.hidden') }}
</ElTag>
<span class="admin-dept-tree__spacer" />
<span class="admin-dept-tree__actions" @click.stop>
<ElButton
link
type="primary"
:icon="FolderAdd"
:title="t('admin.dept.addChild')"
@click="openCreateModal(row.node as AdminDepartmentTreeNode)"
/>
<ElButton
link
type="primary"
:icon="Edit"
:title="t('admin.dept.actions.edit')"
@click="openEditModal(row.node!)"
/>
<ElButton
link
type="danger"
:icon="Delete"
:title="t('admin.dept.actions.delete')"
@click="deleteDepartment(row.node!.id)"
/>
</span>
</div>
</template> </template>
</ElTableColumn> </div>
</ElTable>
</AdminListPage> <!-- 右侧:选中部门的成员面板(OA 口径) -->
<div class="admin-dept-members" style="flex: 1; min-width: 280px; min-height: 0; display: flex; flex-direction: column;">
<template v-if="!selectedDept">
<ElEmpty class="admin-dept-members__empty" :description="t('admin.dept.members.hint')" :image-size="80" />
</template>
<template v-else>
<header class="admin-dept-members__header">
<div class="admin-dept-members__title">
<h3>{{ selectedDept.name }}</h3>
<p :title="selectedDeptPath.join(' / ')">{{ selectedDeptPath.join(' / ') }}</p>
</div>
<ElCheckbox
:model-value="memberIncludeDescendants"
@change="setMemberIncludeDescendants($event as boolean)"
>
{{ t('admin.dept.members.includeDescendants') }}
</ElCheckbox>
</header>
<div class="admin-dept-members__toolbar">
<ElInput
:model-value="memberKeyword"
class="admin-dept-members__search"
:prefix-icon="Search"
clearable
:placeholder="t('admin.dept.members.searchPlaceholder')"
@input="setMemberKeyword(String($event))"
/>
</div>
<div v-loading="memberLoading" class="admin-dept-members__tablewrap" style="flex: 1 1 0; min-height: 0; width: 600px; max-width: 100%; margin-inline: auto;">
<ElTable
:data="memberData?.members ?? []"
row-key="id"
stripe
height="100%"
:empty-text="t('admin.dept.members.empty')"
>
<ElTableColumn :label="t('admin.dept.members.columns.name')" width="170">
<template #default="{ row }">
<div class="admin-dept-member__name">{{ row.real_name || row.username }}</div>
<div class="admin-dept-member__sub">{{ row.username }}</div>
</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.dept.members.columns.contact')" width="150" show-overflow-tooltip>
<template #default="{ row }">{{ row.phone_number || row.email || '-' }}</template>
</ElTableColumn>
<ElTableColumn prop="employee_id" :label="t('admin.dept.members.columns.employeeId')" width="90" show-overflow-tooltip />
<ElTableColumn prop="department" :label="t('admin.dept.members.columns.department')" width="110" show-overflow-tooltip />
<ElTableColumn :label="t('admin.dept.members.columns.status')" width="80">
<template #default="{ row }">
<ElTag :type="statusTagType(row.status)" effect="light" size="small">
{{ statusLabel(row.status) }}
</ElTag>
</template>
</ElTableColumn>
</ElTable>
</div>
<footer v-if="memberData" class="admin-dept-members__footer" style="width: 600px; max-width: 100%; margin-inline: auto; display: flex; align-items: center; justify-content: flex-end; flex-wrap: wrap; row-gap: 8px; gap: 12px; padding: 12px 0; border-top: 1px solid var(--el-border-color-lighter);">
<ElPagination
background
layout="total, sizes, prev, pager, next"
:total="memberData.total"
:current-page="memberPage"
:page-size="memberPageSize"
:page-sizes="[20, 50, 100]"
@current-change="setMemberPage"
@size-change="setMemberPageSize"
/>
<span class="admin-dept-members__pages">{{ memberPage }} / {{ memberTotalPages }}</span>
</footer>
</template>
</div>
</div>
</section>
<DepartmentFormModal <DepartmentFormModal
:visible="showFormModal" :visible="showFormModal"
:form="form" :form="form"
:parent-options="parentOptions"
:is-saving="isSaving" :is-saving="isSaving"
@close="closeFormModal" @close="closeFormModal"
@save="saveDepartment" @save="saveDepartment"
/> />
<DepartmentMembersModal </ElConfigProvider>
:visible="showMembersModal"
:data="departmentMembers"
@close="showMembersModal = false"
/>
</template> </template>
<style scoped> <style scoped>
:deep(.dept-filter-search) { /* 页内布局(非 Element 控件内部),间距对齐迁移规范:筛选条、面板分隔、分页右侧 */
/* AdminLayout 内容列高度确定(h-dvh 壳内 flex-1 min-h-0),本页卡片填满后左右两栏各自滚动 */
.admin-dept-page {
height: 100%;
min-height: 24rem;
display: flex;
flex-direction: column;
}
.admin-dept-filter {
display: flex;
align-items: center;
gap: 8px;
padding: 12px 32px;
border-bottom: 1px solid var(--el-border-color-lighter);
}
.admin-dept-filter__search {
width: 16rem; width: 16rem;
} }
.admin-dept-body {
.dept-desc { flex: 1;
min-height: 0;
display: flex;
align-items: stretch;
overflow-x: auto;
}
.admin-dept-tree {
width: max-content;
min-width: 260px;
max-width: 45%;
flex-shrink: 0;
padding: 12px 8px 12px 24px;
border-right: 1px solid var(--el-border-color-lighter);
overflow-y: auto;
}
.admin-dept-tree__row {
display: flex;
align-items: center;
gap: 4px;
padding: 6px 4px;
border-radius: var(--el-border-radius-base);
cursor: pointer;
user-select: none;
min-width: 0;
}
.admin-dept-tree__row:hover {
background: var(--el-fill-color-light);
}
.admin-dept-tree__row--company {
font-weight: 600;
}
.admin-dept-tree__row.is-selected {
background: var(--el-color-primary-light-9);
}
.admin-dept-tree__row.is-selected .admin-dept-tree__name {
color: var(--el-color-primary);
}
.admin-dept-tree__chevron,
.admin-dept-tree__toggle {
flex-shrink: 0;
width: 20px;
display: inline-flex;
justify-content: center;
color: var(--el-text-color-secondary);
background: none;
border: none;
padding: 0;
cursor: pointer;
}
.admin-dept-tree__company-icon {
flex-shrink: 0;
color: var(--el-color-primary);
}
.admin-dept-tree__name {
font-size: var(--el-font-size-base);
color: var(--el-text-color-primary);
white-space: nowrap;
overflow: hidden; overflow: hidden;
text-overflow: ellipsis; text-overflow: ellipsis;
}
.admin-dept-tree__spacer {
flex: 1;
}
.admin-dept-tree__actions {
display: none;
align-items: center;
flex-shrink: 0;
}
.admin-dept-tree__row:hover .admin-dept-tree__actions {
display: inline-flex;
}
.admin-dept-members {
flex: 1;
min-width: 280px;
min-height: 0;
display: flex;
flex-direction: column;
}
.admin-dept-members__empty {
flex: 1;
margin: auto;
}
.admin-dept-members__header {
/* width 由 .admin-dept-members 统一定宽 */
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
flex-wrap: wrap;
padding: 16px 24px 8px;
}
.admin-dept-members__title {
min-width: 0;
}
.admin-dept-members__title h3 {
font-size: var(--el-font-size-large);
font-weight: 600;
color: var(--el-text-color-primary);
margin: 0;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.admin-dept-members__title p {
font-size: var(--el-font-size-small);
color: var(--el-text-color-secondary);
margin: 2px 0 0;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.admin-dept-members__toolbar {
padding: 8px 24px 12px;
border-bottom: 1px solid var(--el-border-color-lighter);
}
.admin-dept-members__search {
width: 16rem;
}
.admin-dept-members__tablewrap {
/* 宽度须与上方五列 width 之和(170+150+90+110+80=600)保持一致;居中使剩余空白均匀分两侧 */
width: 600px;
max-width: 100%;
margin-inline: auto;
}
.admin-dept-members__footer {
/* 与表格同宽并同样居中,分页对齐表格右缘 */
width: 600px;
max-width: 100%;
margin-inline: auto;
display: flex;
align-items: center;
justify-content: flex-end;
flex-wrap: wrap;
row-gap: 8px;
gap: 12px;
padding: 12px 0;
border-top: 1px solid var(--el-border-color-lighter);
}
.admin-dept-members__pages {
font-size: var(--el-font-size-small);
color: var(--el-text-color-secondary);
white-space: nowrap; white-space: nowrap;
} }
.admin-dept-member__name {
.dept-row-actions { color: var(--el-text-color-primary);
display: inline-flex; }
justify-content: flex-end; .admin-dept-member__sub {
gap: 4px; font-size: var(--el-font-size-extra-small);
color: var(--el-text-color-secondary);
margin-top: 2px;
}
@media (max-width: 1023px) {
.admin-dept-body {
flex-direction: column;
}
.admin-dept-tree {
max-height: 40vh;
}
.admin-dept-members {
width: 100%;
}
} }
</style> </style>
@@ -1,17 +1,20 @@
/** /**
* features/admin/modules/departments/components/DepartmentFormModal.vue * features/admin/modules/departments/components/DepartmentFormModal.vue
* 用途:部门创建和编辑对话框。四个字段,单列。 * 用途:部门创建/编辑对话框(上级部门选择、同级排序、隐藏标记)。
* 依赖:element-plus 对话框和表单、DepartmentFormState。 * 依赖:element-plus 对话框和表单、DepartmentFormState、DeptParentOption。
* 逻辑:DepartmentsPage 打开本组件。提交时 emit save,由 useDepartmentsAdmin 调接口。样式跟页面已引入的 Element 皮肤走。 * 逻辑:DepartmentsPage 打开本组件。上级选项由父级传入(编辑时已排除自身及子孙,防成环);
* 公司未填时由后端继承上级部门;提交时 emit save,由 useDepartmentsAdmin 调接口。
*/ */
<script setup lang="ts"> <script setup lang="ts">
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { ElButton, ElDialog, ElForm, ElFormItem, ElInput } from 'element-plus'; import { ElButton, ElCol, ElDialog, ElForm, ElFormItem, ElInput, ElInputNumber, ElOption, ElRow, ElSelect, ElSwitch } from 'element-plus';
import type { DepartmentFormState } from '@/features/admin/types/department.types'; import type { DepartmentFormState } from '@/features/admin/types/department.types';
import type { DeptParentOption } from '../composables/useDepartmentsAdmin';
defineProps<{ const props = defineProps<{
visible: boolean; visible: boolean;
form: DepartmentFormState; form: DepartmentFormState;
parentOptions: DeptParentOption[];
isSaving: boolean; isSaving: boolean;
}>(); }>();
@@ -22,6 +25,14 @@ const emit = defineEmits<{
const { t } = useI18n(); const { t } = useI18n();
/**
* 上级部门下拉回写:ElSelect 不接受 null 类型,空值在此统一为 null(顶级部门)。
* @param value - 下拉选中的值
*/
function onParentChange(value: unknown): void {
props.form.parentId = (value ?? null) as number | null;
}
/** /**
* 对话框关闭时通知页面收起并重置表单。 * 对话框关闭时通知页面收起并重置表单。
* @param open - Element 对话框的打开状态 * @param open - Element 对话框的打开状态
@@ -35,7 +46,7 @@ function onVisibleChange(open: boolean): void {
<ElDialog <ElDialog
:model-value="visible" :model-value="visible"
:title="form.id ? t('admin.dept.edit') : t('admin.dept.add')" :title="form.id ? t('admin.dept.edit') : t('admin.dept.add')"
width="480px" width="680px"
align-center align-center
append-to-body append-to-body
:close-on-click-modal="false" :close-on-click-modal="false"
@@ -44,15 +55,54 @@ function onVisibleChange(open: boolean): void {
@update:model-value="onVisibleChange" @update:model-value="onVisibleChange"
> >
<ElForm label-position="top" :model="form" @submit.prevent="emit('save')"> <ElForm label-position="top" :model="form" @submit.prevent="emit('save')">
<ElFormItem :label="t('admin.dept.fields.parent')">
<!-- 运行时以 null 表示顶级部门(有对应选项),modelValue 的类型限制此处用 as any 放行 -->
<ElSelect :model-value="(form.parentId ?? null) as any" filterable @update:model-value="onParentChange">
<ElOption
v-for="option in parentOptions"
:key="String(option.id)"
:label="option.label"
:value="option.id as number"
:disabled="option.disabled"
/>
</ElSelect>
</ElFormItem>
<ElFormItem :label="t('admin.dept.fields.name')" required> <ElFormItem :label="t('admin.dept.fields.name')" required>
<ElInput v-model="form.name" :placeholder="t('admin.dept.fields.namePlaceholder')" /> <ElInput v-model="form.name" :placeholder="t('admin.dept.fields.namePlaceholder')" />
</ElFormItem> </ElFormItem>
<ElFormItem :label="t('admin.dept.fields.code')"> <ElRow>
<ElInput v-model="form.code" :placeholder="t('admin.dept.fields.codePlaceholder')" /> <ElCol :span="12" class="admin-dept-form__col">
</ElFormItem> <ElFormItem :label="t('admin.dept.fields.code')">
<ElFormItem :label="t('admin.dept.fields.company')"> <ElInput v-model="form.code" :placeholder="t('admin.dept.fields.codePlaceholder')" />
<ElInput v-model="form.company" :placeholder="t('admin.dept.fields.companyPlaceholder')" /> </ElFormItem>
</ElFormItem> </ElCol>
<ElCol :span="12" class="admin-dept-form__col">
<ElFormItem :label="t('admin.dept.fields.company')">
<ElInput v-model="form.company" :placeholder="t('admin.dept.fields.companyPlaceholder')" />
</ElFormItem>
</ElCol>
</ElRow>
<ElRow>
<ElCol :span="12" class="admin-dept-form__col">
<ElFormItem :label="t('admin.dept.fields.sort')">
<ElInputNumber
:model-value="form.sortOrder ?? 0"
:min="0"
class="admin-dept-form__number"
@update:model-value="form.sortOrder = $event ?? 0"
/>
</ElFormItem>
</ElCol>
<ElCol :span="12" class="admin-dept-form__col">
<ElFormItem :label="t('admin.dept.fields.visibility')">
<div class="admin-dept-form__switch">
<ElSwitch v-model="form.isHidden" />
<span class="admin-dept-form__switch-label">{{ t('admin.dept.fields.hidden') }}</span>
</div>
<p class="admin-dept-form__hint">{{ t('admin.dept.fields.hiddenHint') }}</p>
</ElFormItem>
</ElCol>
</ElRow>
<ElFormItem :label="t('admin.dept.fields.description')"> <ElFormItem :label="t('admin.dept.fields.description')">
<ElInput <ElInput
v-model="form.description" v-model="form.description"
@@ -70,3 +120,31 @@ function onVisibleChange(open: boolean): void {
</template> </template>
</ElDialog> </ElDialog>
</template> </template>
<style scoped>
.admin-dept-form__col {
padding-right: 16px;
}
.admin-dept-form__col:last-child {
padding-right: 0;
}
.admin-dept-form__number {
width: 100%;
}
.admin-dept-form__switch {
display: flex;
align-items: center;
gap: 8px;
padding-top: 4px;
}
.admin-dept-form__switch-label {
font-size: var(--el-font-size-base);
color: var(--el-text-color-regular);
}
.admin-dept-form__hint {
font-size: var(--el-font-size-extra-small);
color: var(--el-text-color-secondary);
margin: 4px 0 0;
line-height: 1.5;
}
</style>
@@ -1,72 +0,0 @@
/**
* features/admin/modules/departments/components/DepartmentMembersModal.vue
* 用途:只读展示某个部门的员工数量和名单。
* 依赖:element-plus 对话框和表格、部门成员响应类型。
* 逻辑:DepartmentsPage 拉到名单后传入。本组件不请求接口,只展示和关闭。
*/
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import { ElButton, ElDialog, ElTable, ElTableColumn } from 'element-plus';
import type { AdminDepartmentMembersResponse } from '@/features/admin/types/admin.types';
defineProps<{
visible: boolean;
data: AdminDepartmentMembersResponse | null;
}>();
const emit = defineEmits<{ close: [] }>();
const { t } = useI18n();
/**
* 对话框关闭时通知页面收起。
* @param open - Element 对话框的打开状态
*/
function onVisibleChange(open: boolean): void {
if (!open) emit('close');
}
</script>
<template>
<ElDialog
:model-value="visible && !!data"
:title="data ? t('admin.dept.members.title', { name: data.department.name }) : ''"
width="680px"
align-center
append-to-body
:close-on-click-modal="false"
@update:model-value="onVisibleChange"
>
<template v-if="data">
<p class="section-desc">{{ t('admin.dept.members.count', { count: data.count }) }}</p>
<ElTable
class="dept-members-table"
:data="data.members"
row-key="id"
max-height="60vh"
:empty-text="t('admin.dept.members.empty')"
>
<ElTableColumn :label="t('admin.user.fields.realName')" min-width="140">
<template #default="{ row }">{{ row.real_name || row.username }}</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.user.fields.employeeId')" min-width="120">
<template #default="{ row }">{{ row.employee_id || '-' }}</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.user.fields.email')" min-width="180">
<template #default="{ row }">{{ row.email || '-' }}</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.user.headers.status')" min-width="100">
<template #default="{ row }">{{ row.status || '-' }}</template>
</ElTableColumn>
</ElTable>
</template>
<template #footer>
<ElButton @click="emit('close')">{{ t('admin.close') }}</ElButton>
</template>
</ElDialog>
</template>
<style scoped>
.dept-members-table {
margin-top: 16px;
}
</style>
@@ -1,8 +1,9 @@
/** /**
* features/admin/modules/departments/composables/useDepartmentsAdmin.ts * features/admin/modules/departments/composables/useDepartmentsAdmin.ts
* 用途:部门管理列表、搜索过滤、列排序、创建/编辑弹窗、删除。 * 用途:部门树加载、公司虚拟分组、展开/收起、搜索过滤、创建/编辑/删除。
* 依赖:admin.api、department.types、useMessage、useTableSort、element-plus 的确认框。 * 依赖:admin.api、department.types、useMessage、element-plus 的确认框。
* 逻辑:DepartmentsPage 调用本 composable。表头排序由页面把 Element 的 sort-change 交给 applySort,仍在本地对过滤后的列表排序。删除用 ElMessageBox,不再使用 DeleteConfirmDialog。 * 逻辑:DepartmentsPage 调用本 composable;数据来自 /admin/departments/tree(children 已按同级排序号排好);
* 公司层不入库,按顶级部门的 company 字段在前端虚拟分组;删除用 ElMessageBox,不再使用 DeleteConfirmDialog。
*/ */
import { computed, ref } from 'vue'; import { computed, ref } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
@@ -10,84 +11,310 @@ import { ElMessageBox } from 'element-plus';
import { import {
createAdminDepartment, createAdminDepartment,
deleteAdminDepartment, deleteAdminDepartment,
listAdminDepartments, listAdminDepartmentMembers,
listAdminDepartmentTree,
updateAdminDepartment, updateAdminDepartment,
} from '@/features/admin/api/admin.api'; } from '@/features/admin/api/admin.api';
import { useMessage } from '@/shared/composables/useMessage'; import { useMessage } from '@/shared/composables/useMessage';
import { useTableSort } from '@/shared/composables/useTableSort'; import type {
import type { SortDir } from '@/shared/utils/table-sort'; AdminDepartmentMembersResponse,
import type { AdminDepartmentRow } from '@/features/admin/types/admin.types'; AdminDepartmentTreeNode,
} from '@/features/admin/types/admin.types';
import { import {
createEmptyDepartmentForm, createEmptyDepartmentForm,
departmentRowToForm, departmentRowToForm,
type DepartmentFormState, type DepartmentFormState,
} from '@/features/admin/types/department.types'; } 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;
}
/**
* 部门管理页的列表、表单和删除状态。
* 核心逻辑:拉全量部门后在本地过滤和排序,保存与删除成功后再拉一次列表。
* @returns 页面绑定的状态和打开弹窗、排序、保存、删除方法
*/
export function useDepartmentsAdmin() { export function useDepartmentsAdmin() {
const { t } = useI18n(); const { t } = useI18n();
const msg = useMessage(); const msg = useMessage();
const departments = ref<AdminDepartmentRow[]>([]); const tree = ref<AdminDepartmentTreeNode[]>([]);
const form = ref<DepartmentFormState>(createEmptyDepartmentForm()); const form = ref<DepartmentFormState>(createEmptyDepartmentForm());
const searchQuery = ref(''); const searchQuery = ref('');
const { sortKey, sortDir, sortItems } = useTableSort<DeptSortKey>({
initialKey: 'name',
initialDir: 'asc',
});
const isLoading = ref(true); const isLoading = ref(true);
const isListLoading = ref(false);
const isSaving = ref(false); const isSaving = ref(false);
const showFormModal = ref(false); const showFormModal = ref(false);
/** /** 展开状态:部门节点 id 集合 / 公司分组 key 集合 */
* 先按关键词过滤,再按当前排序列排序。 const expandedIds = ref<Set<number>>(new Set());
* 核心逻辑:模糊匹配四字段 → useTableSort.sortItems。 const expandedCompanies = ref<Set<string>>(new Set());
*/
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,
);
});
/** /**
* 拉取部门列表并写入 departments。 * 拉取部门树并写入 tree。
* @returns Promise<void> * @returns Promise<void>
*/ */
/** 是否已做过首屏默认展开(只做一次,之后尊重用户的展开/收起操作) */
let expandSeeded = false;
const loadDepartments = async (): Promise<void> => { const loadDepartments = async (): Promise<void> => {
isListLoading.value = true;
try { try {
departments.value = await listAdminDepartments(); tree.value = (await listAdminDepartmentTree()) as AdminDepartmentTreeNode[];
} catch (e) { } catch (e) {
console.error('Failed to load departments', e); console.error('Failed to load department tree', e);
departments.value = []; tree.value = [];
} finally { }
isListLoading.value = false; // 首屏默认展开公司组与第一层部门:树内容填满栏高(对齐 OA 展开到第一级的习惯)
if (!expandSeeded && tree.value.length) {
expandSeeded = true;
expandedCompanies.value = new Set(tree.value.map((r) => r.company?.trim() || ''));
expandedIds.value = new Set(tree.value.map((r) => r.id));
} }
}; };
/** /**
* 页面初始化:加载部门列表并结束 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;
};
/** 在树中查找 id 的祖先路径(含自身,不含公司虚拟层)。 */
const findPath = (nodes: AdminDepartmentTreeNode[], id: number, trail: AdminDepartmentTreeNode[] = []): AdminDepartmentTreeNode[] | null => {
for (const n of nodes) {
const next = [...trail, n];
if (n.id === id) return next;
const hit = findPath(n.children || [], id, next);
if (hit) return hit;
}
return null;
};
// ---------- 右侧成员面板(OA 组织结构口径:点部门出成员列表) ----------
const selectedDeptId = ref<number | null>(null);
const memberData = ref<AdminDepartmentMembersResponse | null>(null);
const memberLoading = ref(false);
const memberKeyword = ref('');
const memberIncludeDescendants = ref(true);
const memberPage = ref(1);
const memberPageSize = ref(20);
// 竞态保护:仅采纳最后一次请求的结果(切部门/翻页/搜索连击时旧响应作废)
let memberRequestSeq = 0;
let memberKeywordTimer: ReturnType<typeof setTimeout> | null = null;
const MEMBER_KEYWORD_DEBOUNCE_MS = 300;
const selectedDept = computed<AdminDepartmentTreeNode | null>(() =>
selectedDeptId.value ? findNode(tree.value, selectedDeptId.value) : null,
);
/** 选中部门的祖先路径(面包屑:公司分组名 → … → 本部门)。 */
const selectedDeptPath = computed<string[]>(() => {
if (!selectedDeptId.value) return [];
const path = findPath(tree.value, selectedDeptId.value) || [];
const rootCompany = path[0]?.company?.trim() || t('admin.dept.noCompany');
return [rootCompany, ...path.map((n) => n.name)];
});
/** 拉取当前选中部门的分页成员名单。 */
const fetchMembers = async (): Promise<void> => {
if (!selectedDeptId.value) {
memberData.value = null;
return;
}
const seq = ++memberRequestSeq;
memberLoading.value = true;
try {
const data = (await listAdminDepartmentMembers(selectedDeptId.value, {
includeDescendants: memberIncludeDescendants.value,
keyword: memberKeyword.value,
page: memberPage.value,
pageSize: memberPageSize.value,
})) as AdminDepartmentMembersResponse;
if (seq === memberRequestSeq) memberData.value = data;
} catch (e) {
console.error('Failed to load department members', e);
if (seq === memberRequestSeq) {
memberData.value = null;
msg.error((e as Error).message || t('admin.msg.requestFailed'));
}
} finally {
if (seq === memberRequestSeq) memberLoading.value = false;
}
};
/**
* 选中树节点:右侧面板加载该部门成员。
* @param node - 被点击的部门节点
*/
const selectDept = (node: AdminDepartmentTreeNode): void => {
if (selectedDeptId.value === node.id) return;
selectedDeptId.value = node.id;
memberKeyword.value = '';
memberPage.value = 1;
void fetchMembers();
};
/** 成员关键词输入(300ms 防抖后回到第 1 页重新查询)。 */
const setMemberKeyword = (value: string): void => {
memberKeyword.value = value;
if (memberKeywordTimer) clearTimeout(memberKeywordTimer);
memberKeywordTimer = setTimeout(() => {
memberKeywordTimer = null;
memberPage.value = 1;
void fetchMembers();
}, MEMBER_KEYWORD_DEBOUNCE_MS);
};
/** 切换「含下级部门」口径:回到第 1 页重新查询。 */
const setMemberIncludeDescendants = (value: boolean): void => {
memberIncludeDescendants.value = value;
memberPage.value = 1;
void fetchMembers();
};
/** 翻页 / 调整每页条数。 */
const setMemberPage = (page: number): void => {
memberPage.value = Math.max(page, 1);
void fetchMembers();
};
const setMemberPageSize = (size: number): void => {
memberPageSize.value = size;
memberPage.value = 1;
void fetchMembers();
};
/** 选中部门被删除或树刷新后,校正成员面板状态。 */
const syncMemberPanelAfterTreeReload = (deletedId?: number): void => {
if (deletedId != null && deletedId === selectedDeptId.value) {
selectedDeptId.value = null;
memberData.value = null;
return;
}
if (selectedDeptId.value) void fetchMembers();
};
/** 表单弹窗「上级部门」选项:编辑时排除自身及子孙,避免把子树挂到自己下面 */
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> * @returns Promise<void>
*/ */
const loadAll = async (): Promise<void> => { const loadAll = async (): Promise<void> => {
@@ -96,32 +323,59 @@ export function useDepartmentsAdmin() {
isLoading.value = false; isLoading.value = false;
}; };
/** /** 切换部门节点展开/收起。 */
* 把 Element 表头排序写回本地排序状态。 const toggleNode = (id: number): void => {
* 核心逻辑:第三次点击清空排序时回到接口原顺序;有效列只排当前过滤结果,不请求接口。 const next = new Set(expandedIds.value);
* @param key - 名称、编码、公司;空字符串表示取消排序 if (next.has(id)) next.delete(id);
* @param dir - asc、desc,或空 else next.add(id);
*/ expandedIds.value = next;
const applySort = (key: DeptSortKey | '', dir: SortDir | ''): void => {
if (key === '' || dir === '') {
sortKey.value = undefined;
return;
}
sortKey.value = key;
sortDir.value = dir;
}; };
/** 打开「添加部门」弹窗并重置表单。 */ /** 切换公司虚拟分组展开/收起。 */
const openCreateModal = (): void => { 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 parent - 上级部门节点(添加子部门时传入);空 = 顶级
* @param company - 预填公司(公司虚拟分组行的「添加子部门」传入)
*/
const openCreateModal = (parent?: AdminDepartmentTreeNode | null, company?: string): void => {
form.value = createEmptyDepartmentForm(); form.value = createEmptyDepartmentForm();
form.value.parentId = parent ? parent.id : null;
form.value.company = company ?? parent?.company ?? '';
showFormModal.value = true; showFormModal.value = true;
}; };
/** /**
* 打开「编辑部门」弹窗并回填选中行数据。 * 打开「编辑部门」弹窗并回填选中行数据。
* @param dept - 待编辑的部门行 * @param dept - 待编辑的部门树节点
*/ */
const openEditModal = (dept: AdminDepartmentRow): void => { const openEditModal = (dept: AdminDepartmentTreeNode): void => {
form.value = departmentRowToForm(dept); form.value = departmentRowToForm(dept);
showFormModal.value = true; showFormModal.value = true;
}; };
@@ -134,7 +388,8 @@ export function useDepartmentsAdmin() {
/** /**
* 保存部门:有 id 则更新,否则新建。 * 保存部门:有 id 则更新,否则新建。
* 核心逻辑:校验名称 → 调 create/update API → 刷新列表并关闭弹窗。 * 核心逻辑:校验名称 → 组装含 parent_id/sort_order/is_hidden 的载荷 → 调 API → 刷新树并关闭弹窗。
* 后端负责同级查重、防成环等校验,失败抛 BusinessError(errors.json 四语言文案)。
* @returns Promise<void> * @returns Promise<void>
*/ */
const saveDepartment = async (): Promise<void> => { const saveDepartment = async (): Promise<void> => {
@@ -149,6 +404,9 @@ export function useDepartmentsAdmin() {
code: form.value.code?.trim() || '', code: form.value.code?.trim() || '',
company: form.value.company?.trim() || '', company: form.value.company?.trim() || '',
description: form.value.description?.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) { if (form.value.id) {
await updateAdminDepartment(form.value.id, payload); await updateAdminDepartment(form.value.id, payload);
@@ -157,6 +415,7 @@ export function useDepartmentsAdmin() {
} }
closeFormModal(); closeFormModal();
await loadDepartments(); await loadDepartments();
syncMemberPanelAfterTreeReload();
} catch (e) { } catch (e) {
msg.error((e as Error).message || t('admin.msg.failed')); msg.error((e as Error).message || t('admin.msg.failed'));
} finally { } finally {
@@ -165,8 +424,8 @@ export function useDepartmentsAdmin() {
}; };
/** /**
* 删除指定部门。先用 Element 确认框询问,取消则不请求。 * 删除指定部门:ElMessageBox 确认后调接口。
* 核心逻辑:MessageBox 在取消时 reject,这里吞掉;确定后再调删除接口并刷新列表。 * 有下级部门或名下仍有员工时后端返回 409(HAS_CHILDREN / HAS_MEMBERS),此处展示其文案。
* @param id - 部门主键 * @param id - 部门主键
*/ */
const deleteDepartment = async (id: number): Promise<void> => { const deleteDepartment = async (id: number): Promise<void> => {
@@ -182,6 +441,7 @@ export function useDepartmentsAdmin() {
try { try {
await deleteAdminDepartment(id); await deleteAdminDepartment(id);
await loadDepartments(); await loadDepartments();
syncMemberPanelAfterTreeReload(id);
} catch (e) { } catch (e) {
console.error(e); console.error(e);
msg.error((e as Error).message || t('admin.msg.requestFailed')); msg.error((e as Error).message || t('admin.msg.requestFailed'));
@@ -189,22 +449,38 @@ export function useDepartmentsAdmin() {
}; };
return { return {
departments, tree,
filteredDepartments, displayRows,
parentOptions,
form, form,
searchQuery, searchQuery,
sortKey,
sortDir,
isLoading, isLoading,
isListLoading,
isSaving, isSaving,
showFormModal, showFormModal,
loadAll, loadAll,
applySort, toggleNode,
toggleCompany,
expandAll,
collapseAll,
openCreateModal, openCreateModal,
openEditModal, openEditModal,
closeFormModal, closeFormModal,
saveDepartment, saveDepartment,
deleteDepartment, deleteDepartment,
// 成员面板(OA 口径:左树右成员列表)
selectedDeptId,
selectedDept,
selectedDeptPath,
memberData,
memberLoading,
memberKeyword,
memberIncludeDescendants,
memberPage,
memberPageSize,
selectDept,
setMemberKeyword,
setMemberIncludeDescendants,
setMemberPage,
setMemberPageSize,
}; };
} }
@@ -76,21 +76,40 @@ export interface AdminDepartmentRow {
code?: string; code?: string;
company?: string; company?: string;
description?: string; description?: string;
/** 上级部门主键;null/缺省表示顶级部门 */
parent_id?: number | null;
/** 同级排序号(升序),对应 ERP hrao09 */
sort_order?: number;
/** 是否在组织树中隐藏(对应 ERP hrao08;管理端仍可见并打标) */
is_hidden?: boolean;
member_count?: number; member_count?: number;
} }
/** 部门树节点:/admin/departments/tree 返回结构,children 已按同级排序号排好 */
export interface AdminDepartmentTreeNode extends AdminDepartmentRow {
/** 含全部下级部门的成员总数(递归汇总) */
total_member_count?: number;
children: AdminDepartmentTreeNode[];
}
export interface AdminDepartmentMember { export interface AdminDepartmentMember {
id: number; id: number;
username: string; username: string;
real_name?: string; real_name?: string;
employee_id?: string; employee_id?: string;
email?: string; email?: string;
phone_number?: string;
/** 成员所属部门名(含下级视图下用于区分来源部门) */
department?: string;
status?: string; status?: string;
} }
/** 部门成员分页响应(OA 组织面板口径:右侧成员列表) */
export interface AdminDepartmentMembersResponse { export interface AdminDepartmentMembersResponse {
department: AdminDepartmentRow; department: AdminDepartmentRow;
count: number; total: number;
page: number;
page_size: number;
members: AdminDepartmentMember[]; members: AdminDepartmentMember[];
} }
@@ -12,6 +12,12 @@ export interface DepartmentFormState {
code?: string; code?: string;
company?: string; company?: string;
description?: string; description?: string;
/** 上级部门主键;null 表示顶级部门 */
parentId?: number | null;
/** 同级排序号(升序) */
sortOrder?: number;
/** 是否在组织树中隐藏 */
isHidden?: boolean;
} }
/** /**
@@ -23,6 +29,9 @@ export const createEmptyDepartmentForm = (): DepartmentFormState => ({
code: '', code: '',
company: '', company: '',
description: '', description: '',
parentId: null,
sortOrder: 0,
isHidden: false,
}); });
/** /**
@@ -36,4 +45,7 @@ export const departmentRowToForm = (dept: AdminDepartmentRow): DepartmentFormSta
code: dept.code || '', code: dept.code || '',
company: dept.company || '', company: dept.company || '',
description: dept.description || '', description: dept.description || '',
parentId: dept.parent_id ?? null,
sortOrder: dept.sort_order ?? 0,
isHidden: !!dept.is_hidden,
}); });
@@ -9,6 +9,7 @@ import { requestJson } from '@/shared/api/client';
import type { import type {
AssetHistorySearchResult, AssetHistorySearchResult,
AssetImageResolveResult, AssetImageResolveResult,
ChatCapabilityListEntry,
ChatCrossAgentHistoryItem, ChatCrossAgentHistoryItem,
ChatMessage, ChatMessage,
ChatQueryPreviewPage, ChatQueryPreviewPage,
@@ -63,6 +64,16 @@ export const listChatMessages = async (conversationId: string, agentId: number)
: messages; : messages;
}; };
/**
* 获取当前应用的知识库内容清单(常用问题「能力清单条目」标准答案)。
* 用途:AI 回复命中知识库未命中兜底语句时,【知识库内容清单】按钮点击后调用。
* 核心逻辑:后端按 agent_id 过滤全局常用问题条目;未配置时抛 code=CHAT.CAPABILITY_LIST_NOT_FOUND。
* @param agentId - 当前聊天应用 ID(chatStore.currentAgentId),禁止传 0 或空值。
* @returns 含标准答案 answer 的清单条目。
*/
export const getAgentCapabilityList = (agentId: number) =>
requestJson<ChatCapabilityListEntry>(`/api/chat/capability-list?agent_id=${agentId}`, auth());
export const saveLocalChatMessage = (payload: Record<string, unknown>) => export const saveLocalChatMessage = (payload: Record<string, unknown>) =>
requestJson<{ conversation_id?: string; chat_log_id?: number }>('/api/chat/messages/local', { requestJson<{ conversation_id?: string; chat_log_id?: number }>('/api/chat/messages/local', {
method: 'POST', method: 'POST',
@@ -21,6 +21,8 @@ import { useRoute } from 'vue-router';
import { useAuthStore } from '@/features/auth/stores/auth.store'; import { useAuthStore } from '@/features/auth/stores/auth.store';
import { Maximize2 } from 'lucide-vue-next';
import ChatShell from '@/shared/layouts/ChatShell.vue'; import ChatShell from '@/shared/layouts/ChatShell.vue';
import ChatSidebar from '@/features/chat/components/ChatSidebar.vue'; import ChatSidebar from '@/features/chat/components/ChatSidebar.vue';
@@ -7,12 +7,19 @@
* 助手 Markdown 排版在本组件内收口:全局 base 只恢复标题字重,列表序号/圆点、 * 助手 Markdown 排版在本组件内收口:全局 base 只恢复标题字重,列表序号/圆点、
* 层级缩进与标题字号层级由 scoped 样式统一补齐,避免回答渲染成无结构平铺文本。 * 层级缩进与标题字号层级由 scoped 样式统一补齐,避免回答渲染成无结构平铺文本。
* 兼容:同时承接采购合同审查、库存映射、订单提取和 Mermaid 展示。 * 兼容:同时承接采购合同审查、库存映射、订单提取和 Mermaid 展示。
* 知识库未命中兜底回复按原始 content 检测触发标记,在正文下方渲染【知识库内容清单】按钮,
* 点击后弹窗展示常用问题「能力清单条目」标准答案。
*/ */
<script setup lang="ts"> <script setup lang="ts">
import { computed, nextTick, onMounted, ref, watch } from 'vue'; import { computed, nextTick, onMounted, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { Check, Copy, Download, Edit2, Eye, LayoutGrid, MessageSquareText, RotateCw, X } from 'lucide-vue-next'; import { BookOpen, Check, Copy, Download, Edit2, Eye, LayoutGrid, MessageSquareText, RotateCw, X } from 'lucide-vue-next';
import { useAuthStore } from '@/features/auth/stores/auth.store'; import { useAuthStore } from '@/features/auth/stores/auth.store';
import { useMessage } from '@/shared/composables/useMessage';
import { useChatStore } from '../../stores/chat.store';
import { getAgentCapabilityList } from '../../api/chat.api';
import { hasCapabilityListTrigger } from '../../utils/capabilityList';
import type { ChatCapabilityListEntry } from '../../types/chat.types';
import LeaveMessageBlock, { type LeaveMessageHandlers } from './LeaveMessageBlock.vue'; import LeaveMessageBlock, { type LeaveMessageHandlers } from './LeaveMessageBlock.vue';
import ChatMessageAttachmentList from './ChatMessageAttachmentList.vue'; import ChatMessageAttachmentList from './ChatMessageAttachmentList.vue';
import MaintenanceDeviceResultCard from './MaintenanceDeviceResultCard.vue'; import MaintenanceDeviceResultCard from './MaintenanceDeviceResultCard.vue';
@@ -216,6 +223,45 @@ watch(renderedMarkdown, () => { void renderMermaidCharts(); });
const inlineDownloadFiles = computed(() => ( const inlineDownloadFiles = computed(() => (
message.role === 'assistant' ? handlers.getInlineDownloadFiles(message.content).files : [] message.role === 'assistant' ? handlers.getInlineDownloadFiles(message.content).files : []
)); ));
// [知识库内容清单]:触发检测基于原始 content(标记剥离只发生在展示文本层),历史会话同样生效。
const chatStore = useChatStore();
const { error: showCapabilityError } = useMessage();
const capabilityListButtonVisible = computed(() => (
message.role === 'assistant' && hasCapabilityListTrigger(message.content)
));
const capabilityListLoading = ref(false);
const capabilityListEntry = ref<ChatCapabilityListEntry | null>(null);
/**
* 拉取并打开知识库内容清单弹窗。
* AI 触发时机:知识库未命中兜底回复正文下方的【知识库内容清单】按钮被点击时调用。
* 核心逻辑:按当前会话应用(chatStore.currentAgentId)请求常用问题「能力清单条目」标准答案,
* 成功后以弹窗展示;失败时优先复用 requestJson 抛出 BusinessError 的错误码本地化文案。
* 参数约束:agentId 一律取自路由级 chat store,组件不接收外部传入的应用 ID,禁止跨应用查询。
*/
async function openCapabilityListDialog(): Promise<void> {
if (capabilityListLoading.value) return;
const agentId = Number(chatStore.currentAgentId || 0);
if (!agentId) {
showCapabilityError(t('chat.capabilityList.notFound'));
return;
}
capabilityListLoading.value = true;
try {
capabilityListEntry.value = await getAgentCapabilityList(agentId);
} catch (error) {
showCapabilityError(error instanceof Error ? error.message : t('chat.capabilityList.notFound'));
} finally {
capabilityListLoading.value = false;
}
}
/** 关闭知识库内容清单弹窗并清空条目,避免下次打开闪现旧内容。 */
function closeCapabilityListDialog(): void {
capabilityListEntry.value = null;
}
const shippingParseReviewHandlers = computed<ShippingParseReviewHandlers>(() => ({ const shippingParseReviewHandlers = computed<ShippingParseReviewHandlers>(() => ({
getPayload: shippingHandlers.getParseReviewPayload, getPayload: shippingHandlers.getParseReviewPayload,
updateHeader: shippingHandlers.updateHeader, updateHeader: shippingHandlers.updateHeader,
@@ -865,6 +911,18 @@ function handleInlineDownload(file: InlineDownloadFile): void {
</button> </button>
</div> </div>
<div v-if="capabilityListButtonVisible" class="mt-4">
<button
type="button"
class="inline-flex items-center gap-2 rounded-xl border border-brand-200 bg-brand-50 px-3 py-2 text-xs font-medium text-brand-700 transition hover:bg-brand-100 disabled:cursor-not-allowed disabled:opacity-60"
:disabled="capabilityListLoading"
@click="openCapabilityListDialog"
>
<BookOpen class="h-3.5 w-3.5" />
{{ $t('chat.capabilityList.button') }}
</button>
</div>
</div> </div>
</div> </div>
@@ -1135,6 +1193,31 @@ function handleInlineDownload(file: InlineDownloadFile): void {
</div> </div>
</div> </div>
</Teleport> </Teleport>
<Teleport to="body">
<div
v-if="capabilityListEntry"
class="dialog-overlay z-[130] items-center"
@click.self="closeCapabilityListDialog"
>
<div class="dialog-panel flex max-h-[88vh] w-[min(96vw,760px)] flex-col">
<div class="dialog-header">
<div>
<h3 class="section-title">{{ $t('chat.capabilityList.dialogTitle') }}</h3>
<p class="section-desc mt-1">{{ capabilityListEntry.title }}</p>
</div>
<button type="button" class="btn-icon-ds" :aria-label="$t('common.close')" @click="closeCapabilityListDialog">
<X class="h-5 w-5" />
</button>
</div>
<div class="dialog-body min-h-0 flex-1 overflow-auto border-t-0 pt-4">
<div
class="markdown-body chat-markdown min-w-0 break-words text-sm leading-relaxed"
v-html="handlers.renderMarkdown(capabilityListEntry.answer)"
/>
</div>
</div>
</div>
</Teleport>
</template> </template>
<style scoped> <style scoped>
@@ -17,6 +17,7 @@ import {
parseFileCheckExcelRunId, parseFileCheckExcelRunId,
rewriteFileCheckExcelLinksForDisplay, rewriteFileCheckExcelLinksForDisplay,
} from '../utils/fileCheckExcelDownload'; } from '../utils/fileCheckExcelDownload';
import { stripCapabilityListMarker } from '../utils/capabilityList';
marked.setOptions({ gfm: true, breaks: true }); marked.setOptions({ gfm: true, breaks: true });
@@ -472,7 +473,9 @@ export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
/** /**
* 将聊天正文转换为展示 HTML,并在渲染前剥离内嵌文件 JSON 块。 * 将聊天正文转换为展示 HTML,并在渲染前剥离内嵌文件 JSON 块。
* 核心逻辑:先抽取 FILE_START/FILE_END 文件,再走既有 Markdown 清洗与 marked 渲染,保证聊天气泡只展示可读文本。 * 核心逻辑:先抽取 FILE_START/FILE_END 文件,再剥离知识库未命中兜底回复的 [知识库能力清单]
* 触发标记(按钮由 ChatMessageBubble 按原始 content 渲染),最后走既有 Markdown 清洗与
* marked 渲染,保证聊天气泡只展示可读文本。
* @param text - 原始聊天文本。 * @param text - 原始聊天文本。
* @returns 供 v-html 使用的安全展示字符串。 * @returns 供 v-html 使用的安全展示字符串。
*/ */
@@ -480,7 +483,7 @@ export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
if (!text) return ''; if (!text) return '';
const extracted = safeExtractInlineDownloadFiles(text); const extracted = safeExtractInlineDownloadFiles(text);
const displayText = rewriteFileCheckExcelLinksForDisplay( const displayText = rewriteFileCheckExcelLinksForDisplay(
ctx.prepareMarkdownDisplayText(extracted.cleanedText), ctx.prepareMarkdownDisplayText(stripCapabilityListMarker(extracted.cleanedText)),
); );
try { try {
const rendered = marked.parse(displayText, { renderer: chatMarkdownRenderer }); const rendered = marked.parse(displayText, { renderer: chatMarkdownRenderer });
@@ -373,3 +373,12 @@ export interface ChatQueryPreviewPage {
has_more: boolean; has_more: boolean;
query?: string; query?: string;
} }
/** 知识库内容清单条目:常用问题中「<应用名>·能力清单条目」的标准答案(GET /api/chat/capability-list)。 */
export interface ChatCapabilityListEntry {
id: number;
agent_id: number;
title: string;
question: string;
answer: string;
}
@@ -0,0 +1,55 @@
/**
* features/chat/utils/capabilityList.spec.ts
* 用途:验证知识库未命中兜底回复的触发识别与标记剥离规则。
* 依赖:vitest、capabilityList 纯函数。
* 逻辑:覆盖完整标记、兼容写法、历史无标记兜底原句、流式半截标记与普通消息不误伤五类场景。
*/
import { describe, expect, it } from 'vitest';
import { hasCapabilityListTrigger, stripCapabilityListMarker } from './capabilityList';
describe('hasCapabilityListTrigger', () => {
it('命中完整标记(圈2 草稿形态)', () => {
expect(hasCapabilityListTrigger('持续补充; [知识库能力清单]。')).toBe(true);
});
it('兼容「内容清单」写法', () => {
expect(hasCapabilityListTrigger('持续补充;[知识库内容清单]。')).toBe(true);
});
it('命中无标记的历史兜底原句(圈1 已发布形态)', () => {
expect(hasCapabilityListTrigger(
'这个问题超出了当前知识库的收录范围,所以没能找到答案。欢迎点击页面左下角的【意见反馈】按钮,把想查询的内容告诉我们,我们会根据反馈持续补充;',
)).toBe(true);
});
it('流式阶段未闭合的半截标记也视为触发', () => {
expect(hasCapabilityListTrigger('持续补充; [知识库能力清')).toBe(true);
});
it('普通回答不误伤', () => {
expect(hasCapabilityListTrigger('公司年假共 10 天,请查看 [考勤制度] 文档。')).toBe(false);
expect(hasCapabilityListTrigger('')).toBe(false);
});
});
describe('stripCapabilityListMarker', () => {
it('剥离完整标记并清理前导分号与句末句号', () => {
expect(stripCapabilityListMarker('我们会根据反馈持续补充; [知识库能力清单]。'))
.toBe('我们会根据反馈持续补充');
});
it('剥离中文分号与句号组合', () => {
expect(stripCapabilityListMarker('我们会根据反馈持续补充;[知识库内容清单]。'))
.toBe('我们会根据反馈持续补充');
});
it('裁剪流式阶段未闭合的半截标记', () => {
expect(stripCapabilityListMarker('我们会根据反馈持续补充; [知识库能力清'))
.toBe('我们会根据反馈持续补充;');
});
it('无标记文本原样返回', () => {
const text = '这个问题超出了当前知识库的收录范围,所以没能找到答案。';
expect(stripCapabilityListMarker(text)).toBe(text);
});
});
@@ -0,0 +1,47 @@
/**
* features/chat/utils/capabilityList.ts
* 用途:识别 Dify 知识库未命中兜底回复中的「知识库内容清单」触发条件,并负责展示文本清洗。
* 依赖:无(纯函数,供 useChatPageMarkdown 与 ChatMessageBubble 复用)。
* 逻辑:Dify「直接回复」节点在兜底语句末尾追加 [知识库能力清单] 标记时,前端据此渲染按钮并
* 从正文剥离标记;对未加标记的已发布兜底语句(旧回复、历史会话),按兜底语句稳定特征
* 片段兜底识别。检测作用于原始 content,剥离只影响 Markdown 展示文本。
*/
/** Dify 兜底回复末尾的触发标记,兼容「能力清单 / 内容清单」两种写法及其前导标点与句末句号。 */
const CAPABILITY_LIST_MARKER_REGEX = /\s*[;;,,、]?\s*\[知识库(?:能力|内容)清单\]\s*。?/g;
/** 流式渲染阶段可能只到达一半的未闭合标记(如「[知识库能力清」),按前缀裁剪避免原始符号闪现。 */
const CAPABILITY_LIST_MARKER_PARTIAL_REGEX = /\s*\[知识库[^[\]]*$/;
/** 已上线兜底语句的稳定特征片段(圈1 原句「这个问题超出了当前知识库的收录范围…」)。 */
const KB_FALLBACK_PHRASE = '超出了当前知识库的收录范围';
/**
* 判断一条助手消息是否应展示【知识库内容清单】按钮。
* AI 触发时机:渲染助手消息正文下方按钮前调用,用于决定按钮显隐。
* 核心逻辑:命中完整标记(含流式半截标记)或兜底语句特征片段即视为触发;用户消息由调用方
* 保证不进入本判断。
* 参数约束:传入消息原始 content(未剥标记),禁止传入已渲染 HTML。
* @param content - 消息原始文本。
* @returns 是否展示【知识库内容清单】按钮。
*/
export function hasCapabilityListTrigger(content: string): boolean {
const raw = String(content || '');
if (!raw) return false;
if (raw.includes(KB_FALLBACK_PHRASE)) return true;
return /\[知识库(?:能力|内容)清单\]/.test(raw) || /\[知识库[^[\]]*$/.test(raw);
}
/**
* 从展示文本中剥离「知识库内容清单」触发标记,保留其余正文。
* 核心逻辑:先移除完整标记(连同其前导标点与句末句号,避免留下「; 。」类残渣),再裁剪
* 流式阶段未闭合的半截标记;无标记时原样返回。
* 参数约束:仅用于 Markdown 渲染前的展示文本清洗,不落库、不回写消息 content。
* @param text - 待渲染的展示文本。
* @returns 剥离标记后的展示文本。
*/
export function stripCapabilityListMarker(text: string): string {
const raw = String(text || '');
if (!raw) return '';
return raw.replace(CAPABILITY_LIST_MARKER_REGEX, '').replace(CAPABILITY_LIST_MARKER_PARTIAL_REGEX, '');
}
+33 -5
View File
@@ -1292,6 +1292,12 @@
"subtitle": "Manage organization structure", "subtitle": "Manage organization structure",
"edit": "Edit Department", "edit": "Edit Department",
"add": "Add New 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.", "noDepts": "No departments configured.",
"noSearchResults": "No matching departments found", "noSearchResults": "No matching departments found",
"searchPlaceholder": "Search by name, code, or company…", "searchPlaceholder": "Search by name, code, or company…",
@@ -1304,14 +1310,30 @@
}, },
"actions": { "actions": {
"edit": "Edit", "edit": "Edit",
"delete": "Delete", "delete": "Delete"
"viewMembers": "View department members"
}, },
"members": { "members": {
"title": "{name} Members", "empty": "No members in this department",
"count": "{count} members", "includeDescendants": "Include sub-departments",
"empty": "No members" "searchPlaceholder": "Search name / employee ID / email / phone",
"total": "{total} people in total",
"hint": "Click a department on the left to view its members",
"prevPage": "Previous page",
"nextPage": "Next page",
"columns": {
"name": "Name",
"contact": "Contact",
"employeeId": "Employee ID",
"department": "Department",
"status": "Status"
},
"status": {
"active": "Active",
"pending": "Pending",
"rejected": "Rejected"
}
}, },
"tags": { "hidden": "Hidden" },
"fields": { "fields": {
"name": "Name", "name": "Name",
"namePlaceholder": "e.g. IT Department", "namePlaceholder": "e.g. IT Department",
@@ -1320,6 +1342,12 @@
"company": "Company", "company": "Company",
"companyPlaceholder": "e.g. HQ", "companyPlaceholder": "e.g. HQ",
"description": "Description", "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..." "descriptionPlaceholder": "Department description..."
}, },
"confirmDelete": "Delete this department?", "confirmDelete": "Delete this department?",
+5
View File
@@ -3604,6 +3604,11 @@
"libraryNotConfigured": "Fixed-asset image library is not configured. Contact an admin.", "libraryNotConfigured": "Fixed-asset image library is not configured. Contact an admin.",
"noPhotoUploaded": "No photo has been uploaded by the device admin yet~" "noPhotoUploaded": "No photo has been uploaded by the device admin yet~"
}, },
"capabilityList": {
"button": "KB Content List",
"dialogTitle": "Knowledge Base Content List",
"notFound": "No knowledge base content list is configured for this agent"
},
"queryPreview": { "queryPreview": {
"title": "Full query result preview", "title": "Full query result preview",
"viewAll": "View full preview", "viewAll": "View full preview",
+8
View File
@@ -151,6 +151,7 @@
"AUTH_SSO_ASSERTION_ISSUE_FAILED": "The peer-service login assertion could not be issued. Please retry.", "AUTH_SSO_ASSERTION_ISSUE_FAILED": "The peer-service login assertion could not be issued. Please retry.",
"AUTH_FORBIDDEN": "You do not have permission to perform this action.", "AUTH_FORBIDDEN": "You do not have permission to perform this action.",
"CHAT.USER_ATTACHMENTS_LIMIT_EXCEEDED": "Too many attachments (maximum 200). Remove some and try again.", "CHAT.USER_ATTACHMENTS_LIMIT_EXCEEDED": "Too many attachments (maximum 200). Remove some and try again.",
"CHAT.CAPABILITY_LIST_NOT_FOUND": "No knowledge base content list is configured for this agent. Ask an administrator to maintain its 'capability list' FAQ entry.",
"CONTRACT_PAYMENT_FORBIDDEN": "You do not have access to contract payment alerts.", "CONTRACT_PAYMENT_FORBIDDEN": "You do not have access to contract payment alerts.",
"CONTRACT_PAYMENT_ADMIN_REQUIRED": "Only administrators can sync, scan, or send contract payment alerts.", "CONTRACT_PAYMENT_ADMIN_REQUIRED": "Only administrators can sync, scan, or send contract payment alerts.",
"CONTRACT_PAYMENT_ATTACHMENT_UNAVAILABLE": "The contract file was removed and could not be downloaded again from the source system. Sync OA data and try again.", "CONTRACT_PAYMENT_ATTACHMENT_UNAVAILABLE": "The contract file was removed and could not be downloaded again from the source system. Sync OA data and try again.",
@@ -621,6 +622,13 @@
"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.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.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.",
"SHIPPING.CUSTOMER_REBIND_BLOCKED": "Customer cannot be changed after a shipping notice/Excel has been generated — undo it first", "SHIPPING.CUSTOMER_REBIND_BLOCKED": "Customer cannot be changed after a shipping notice/Excel has been generated — undo it first",
"SHIPPING.CUSTOMER_REBIND_SAME_CUSTOMER": "The selected customer is already the confirmed customer", "SHIPPING.CUSTOMER_REBIND_SAME_CUSTOMER": "The selected customer is already the confirmed customer",
"SHIPPING.CUSTOMER_RESOLUTION_REQUIRED": "Confirm the customer identification first", "SHIPPING.CUSTOMER_RESOLUTION_REQUIRED": "Confirm the customer identification first",
+33 -5
View File
@@ -1292,6 +1292,12 @@
"subtitle": "จัดการโครงสร้างองค์กร", "subtitle": "จัดการโครงสร้างองค์กร",
"edit": "แก้ไขแผนก", "edit": "แก้ไขแผนก",
"add": "เพิ่มแผนกใหม่", "add": "เพิ่มแผนกใหม่",
"addChild": "เพิ่มแผนกย่อย",
"expandAll": "ขยายทั้งหมด",
"collapseAll": "ยุบทั้งหมด",
"expand": "ขยาย",
"collapse": "ยุบ",
"noCompany": "ยังไม่ระบุบริษัท",
"noDepts": "ยังไม่มีการกำหนดค่าแผนก", "noDepts": "ยังไม่มีการกำหนดค่าแผนก",
"noSearchResults": "ไม่พบแผนกที่ตรงกัน", "noSearchResults": "ไม่พบแผนกที่ตรงกัน",
"searchPlaceholder": "ค้นหาชื่อ รหัส หรือบริษัท…", "searchPlaceholder": "ค้นหาชื่อ รหัส หรือบริษัท…",
@@ -1304,9 +1310,9 @@
}, },
"actions": { "actions": {
"edit": "แก้ไข", "edit": "แก้ไข",
"delete": "ลบ", "delete": "ลบ"
"viewMembers": "View department members"
}, },
"tags": { "hidden": "ซ่อนอยู่" },
"fields": { "fields": {
"name": "ชื่อ", "name": "ชื่อ",
"namePlaceholder": "เช่น แผนกไอที", "namePlaceholder": "เช่น แผนกไอที",
@@ -1315,6 +1321,12 @@
"company": "บริษัท", "company": "บริษัท",
"companyPlaceholder": "เช่น สำนักงานใหญ่", "companyPlaceholder": "เช่น สำนักงานใหญ่",
"description": "คำอธิบาย", "description": "คำอธิบาย",
"parent": "แผนกแม่",
"parentRoot": "(เป็นแผนกระดับบนสุด)",
"sort": "ลำดับภายในระดับเดียวกัน",
"visibility": "การแสดงผล",
"hidden": "ซ่อนในผังองค์กร",
"hiddenHint": "ซ่อนจากผังองค์กรแต่ผู้ดูแลระบบยังมองเห็น (ตรงกับ ERP \"แสดงในผังองค์กรหรือไม่\")",
"descriptionPlaceholder": "กรอกรายละเอียดแผนก..." "descriptionPlaceholder": "กรอกรายละเอียดแผนก..."
}, },
"confirmDelete": "ลบแผนกนี้หรือไม่?", "confirmDelete": "ลบแผนกนี้หรือไม่?",
@@ -1322,9 +1334,25 @@
"nameRequired": "กรุณากรอกชื่อแผนก" "nameRequired": "กรุณากรอกชื่อแผนก"
}, },
"members": { "members": {
"title": "{name} Members", "empty": "แผนกนี้ยังไม่มีพนักงาน",
"count": "{count} members", "includeDescendants": "รวมแผนกย่อย",
"empty": "No members" "searchPlaceholder": "ค้นหาชื่อ / รหัสพนักงาน / อีเมล / โทรศัพท์",
"total": "รวม {total} คน",
"hint": "คลิกแผนกด้านซ้ายเพื่อดูพนักงาน",
"prevPage": "หน้าก่อนหน้า",
"nextPage": "หน้าถัดไป",
"columns": {
"name": "ชื่อ",
"contact": "ช่องทางติดต่อ",
"employeeId": "รหัสพนักงาน",
"department": "แผนก",
"status": "สถานะ"
},
"status": {
"active": "ใช้งาน",
"pending": "รออนุมัติ",
"rejected": "ปฏิเสธ"
}
} }
}, },
"agent": { "agent": {
+5
View File
@@ -3604,6 +3604,11 @@
"libraryNotConfigured": "ยังไม่ได้ตั้งค่าคลังรูปภาพสินทรัพย์ถาวร กรุณาติดต่อผู้ดูแลระบบ", "libraryNotConfigured": "ยังไม่ได้ตั้งค่าคลังรูปภาพสินทรัพย์ถาวร กรุณาติดต่อผู้ดูแลระบบ",
"noPhotoUploaded": "ผู้ดูแลอุปกรณ์ยังไม่ได้อัปโหลดรูปภาพ~" "noPhotoUploaded": "ผู้ดูแลอุปกรณ์ยังไม่ได้อัปโหลดรูปภาพ~"
}, },
"capabilityList": {
"button": "รายการเนื้อหาคลังความรู้",
"dialogTitle": "รายการเนื้อหาคลังความรู้",
"notFound": "ยังไม่ได้ตั้งค่ารายการเนื้อหาคลังความรู้สำหรับเอเจนต์นี้"
},
"queryPreview": { "queryPreview": {
"title": "ดูผลลัพธ์การค้นหาทั้งหมด", "title": "ดูผลลัพธ์การค้นหาทั้งหมด",
"viewAll": "ดูตัวอย่างทั้งหมด", "viewAll": "ดูตัวอย่างทั้งหมด",
+8
View File
@@ -151,6 +151,7 @@
"AUTH_SSO_ASSERTION_ISSUE_FAILED": "ไม่สามารถออกข้อมูลยืนยันการเข้าสู่ระบบสำหรับบริการในผลิตภัณฑ์ได้ โปรดลองใหม่", "AUTH_SSO_ASSERTION_ISSUE_FAILED": "ไม่สามารถออกข้อมูลยืนยันการเข้าสู่ระบบสำหรับบริการในผลิตภัณฑ์ได้ โปรดลองใหม่",
"AUTH_FORBIDDEN": "คุณไม่มีสิทธิ์ดำเนินการนี้", "AUTH_FORBIDDEN": "คุณไม่มีสิทธิ์ดำเนินการนี้",
"CHAT.USER_ATTACHMENTS_LIMIT_EXCEEDED": "ไฟล์แนบเกินจำนวนที่อนุญาต (สูงสุด 200 ไฟล์) โปรดลดจำนวนแล้วลองใหม่", "CHAT.USER_ATTACHMENTS_LIMIT_EXCEEDED": "ไฟล์แนบเกินจำนวนที่อนุญาต (สูงสุด 200 ไฟล์) โปรดลดจำนวนแล้วลองใหม่",
"CHAT.CAPABILITY_LIST_NOT_FOUND": "ยังไม่ได้ตั้งค่ารายการเนื้อหาคลังความรู้สำหรับเอเจนต์นี้ โปรดให้ผู้ดูแลระบบเพิ่มรายการ 'capability list' ในคำถามที่พบบ่อย",
"CONTRACT_PAYMENT_FORBIDDEN": "คุณไม่มีสิทธิ์เข้าถึงการแจ้งเตือนการชำระเงินตามสัญญา", "CONTRACT_PAYMENT_FORBIDDEN": "คุณไม่มีสิทธิ์เข้าถึงการแจ้งเตือนการชำระเงินตามสัญญา",
"CONTRACT_PAYMENT_ADMIN_REQUIRED": "เฉพาะผู้ดูแลระบบเท่านั้นที่ซิงก์ สแกน หรือส่งการแจ้งเตือนการชำระเงินตามสัญญาได้", "CONTRACT_PAYMENT_ADMIN_REQUIRED": "เฉพาะผู้ดูแลระบบเท่านั้นที่ซิงก์ สแกน หรือส่งการแจ้งเตือนการชำระเงินตามสัญญาได้",
"CONTRACT_PAYMENT_ATTACHMENT_UNAVAILABLE": "ไฟล์ต้นฉบับของสัญญาถูกลบไปแล้ว และไม่สามารถดาวน์โหลดใหม่จากระบบต้นทางได้ โปรดซิงก์ข้อมูล OA แล้วลองอีกครั้ง", "CONTRACT_PAYMENT_ATTACHMENT_UNAVAILABLE": "ไฟล์ต้นฉบับของสัญญาถูกลบไปแล้ว และไม่สามารถดาวน์โหลดใหม่จากระบบต้นทางได้ โปรดซิงก์ข้อมูล OA แล้วลองอีกครั้ง",
@@ -621,6 +622,13 @@
"INTEGRATION.BINDING_LEGACY_PUT_REJECTED": "ฟิลด์ขั้นตอนเดียวแบบเดิมจะตัดทอนสูตรหลายขั้นตอนของการผูกนี้ โปรดส่งขั้นตอนตามลำดับด้วย steps_json แทน", "INTEGRATION.BINDING_LEGACY_PUT_REJECTED": "ฟิลด์ขั้นตอนเดียวแบบเดิมจะตัดทอนสูตรหลายขั้นตอนของการผูกนี้ โปรดส่งขั้นตอนตามลำดับด้วย steps_json แทน",
"INTEGRATION.CALL_NOT_FOUND": "ไม่พบระเบียนการเรียกใช้งานการผสานรวม", "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": "แผนกนี้ยังมีพนักงานอยู่ จึงไม่สามารถลบได้",
"SHIPPING.CUSTOMER_REBIND_BLOCKED": "มีการแจ้งเตือน/Excel แล้ว ไม่สามารถเปลี่ยนลูกค้าได้ โปรดยกเลิกก่อน", "SHIPPING.CUSTOMER_REBIND_BLOCKED": "มีการแจ้งเตือน/Excel แล้ว ไม่สามารถเปลี่ยนลูกค้าได้ โปรดยกเลิกก่อน",
"SHIPPING.CUSTOMER_REBIND_SAME_CUSTOMER": "ลูกค้าที่เลือกเป็นลูกค้าที่ยืนยันอยู่แล้ว", "SHIPPING.CUSTOMER_REBIND_SAME_CUSTOMER": "ลูกค้าที่เลือกเป็นลูกค้าที่ยืนยันอยู่แล้ว",
"SHIPPING.CUSTOMER_RESOLUTION_REQUIRED": "โปรดยืนยันการระบุลูกค้าก่อน", "SHIPPING.CUSTOMER_RESOLUTION_REQUIRED": "โปรดยืนยันการระบุลูกค้าก่อน",
+33 -5
View File
@@ -1423,6 +1423,12 @@
"subtitle": "管理组织架构", "subtitle": "管理组织架构",
"edit": "编辑部门", "edit": "编辑部门",
"add": "添加部门", "add": "添加部门",
"addChild": "添加子部门",
"expandAll": "全部展开",
"collapseAll": "全部收起",
"expand": "展开",
"collapse": "收起",
"noCompany": "未分配公司",
"noDepts": "暂无部门配置", "noDepts": "暂无部门配置",
"noSearchResults": "未找到匹配的部门", "noSearchResults": "未找到匹配的部门",
"searchPlaceholder": "搜索名称、编码或公司…", "searchPlaceholder": "搜索名称、编码或公司…",
@@ -1435,14 +1441,30 @@
}, },
"actions": { "actions": {
"edit": "编辑", "edit": "编辑",
"delete": "删除", "delete": "删除"
"viewMembers": "查看部门员工"
}, },
"members": { "members": {
"title": "{name}员工", "empty": "该部门暂无员工",
"count": "共 {count} 人", "includeDescendants": "含下级部门",
"empty": "暂无员工" "searchPlaceholder": "搜索姓名 / 工号 / 邮箱 / 手机",
"total": "共 {total} 人",
"hint": "点击左侧部门查看员工",
"prevPage": "上一页",
"nextPage": "下一页",
"columns": {
"name": "姓名",
"contact": "联系方式",
"employeeId": "工号",
"department": "部门",
"status": "状态"
},
"status": {
"active": "启用",
"pending": "待审核",
"rejected": "已拒绝"
}
}, },
"tags": { "hidden": "已隐藏" },
"fields": { "fields": {
"name": "名称", "name": "名称",
"namePlaceholder": "例如:信息技术部", "namePlaceholder": "例如:信息技术部",
@@ -1451,6 +1473,12 @@
"company": "公司", "company": "公司",
"companyPlaceholder": "例如:总部", "companyPlaceholder": "例如:总部",
"description": "描述", "description": "描述",
"parent": "上级部门",
"parentRoot": "(作为顶级部门)",
"sort": "同级排序",
"visibility": "显示设置",
"hidden": "在组织树中隐藏",
"hiddenHint": "隐藏后不在组织树中展示,管理端仍可见(对应 ERP「在组织框架图中显示否」)",
"descriptionPlaceholder": "请输入部门描述..." "descriptionPlaceholder": "请输入部门描述..."
}, },
"confirmDelete": "确定删除该部门吗?", "confirmDelete": "确定删除该部门吗?",
+5
View File
@@ -3604,6 +3604,11 @@
"libraryNotConfigured": "当前系统暂未配置固定资产图片文档库,暂时无法查看图片,请联系管理员处理。", "libraryNotConfigured": "当前系统暂未配置固定资产图片文档库,暂时无法查看图片,请联系管理员处理。",
"noPhotoUploaded": "设备管理员还未上传照片~" "noPhotoUploaded": "设备管理员还未上传照片~"
}, },
"capabilityList": {
"button": "知识库内容清单",
"dialogTitle": "知识库内容清单",
"notFound": "该应用尚未配置知识库内容清单"
},
"queryPreview": { "queryPreview": {
"title": "查询结果全量预览", "title": "查询结果全量预览",
"viewAll": "查看全部预览", "viewAll": "查看全部预览",
+8
View File
@@ -151,6 +151,7 @@
"AUTH_SSO_ASSERTION_ISSUE_FAILED": "平级服务登录声明签发失败,请重试。", "AUTH_SSO_ASSERTION_ISSUE_FAILED": "平级服务登录声明签发失败,请重试。",
"AUTH_FORBIDDEN": "你没有权限执行该操作。", "AUTH_FORBIDDEN": "你没有权限执行该操作。",
"CHAT.USER_ATTACHMENTS_LIMIT_EXCEEDED": "附件数量超过上限(最多 200 个),请减少后重试。", "CHAT.USER_ATTACHMENTS_LIMIT_EXCEEDED": "附件数量超过上限(最多 200 个),请减少后重试。",
"CHAT.CAPABILITY_LIST_NOT_FOUND": "该应用尚未配置知识库内容清单,请在管理端常用问题中为它维护「能力清单条目」。",
"CONTRACT_PAYMENT_FORBIDDEN": "你没有合同付款预警的访问权限。", "CONTRACT_PAYMENT_FORBIDDEN": "你没有合同付款预警的访问权限。",
"CONTRACT_PAYMENT_ADMIN_REQUIRED": "仅管理员可执行合同付款预警的同步、扫描或发送操作。", "CONTRACT_PAYMENT_ADMIN_REQUIRED": "仅管理员可执行合同付款预警的同步、扫描或发送操作。",
"CONTRACT_PAYMENT_ATTACHMENT_UNAVAILABLE": "合同原文已被清理,且无法从原系统重新下载。请先同步 OA 数据后再试。", "CONTRACT_PAYMENT_ATTACHMENT_UNAVAILABLE": "合同原文已被清理,且无法从原系统重新下载。请先同步 OA 数据后再试。",
@@ -621,6 +622,13 @@
"INTEGRATION.BINDING_LEGACY_PUT_REJECTED": "旧单步字段会截断该绑定的多步配方,请改用 steps_json 提交有序步骤。", "INTEGRATION.BINDING_LEGACY_PUT_REJECTED": "旧单步字段会截断该绑定的多步配方,请改用 steps_json 提交有序步骤。",
"INTEGRATION.CALL_NOT_FOUND": "集成调用记录不存在。", "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": "该部门名下仍有员工,无法删除。",
"SHIPPING.CUSTOMER_REBIND_BLOCKED": "已产生发货通知/Excel,无法修改客户,请先走撤销流程", "SHIPPING.CUSTOMER_REBIND_BLOCKED": "已产生发货通知/Excel,无法修改客户,请先走撤销流程",
"SHIPPING.CUSTOMER_REBIND_SAME_CUSTOMER": "新客户与当前确认客户相同", "SHIPPING.CUSTOMER_REBIND_SAME_CUSTOMER": "新客户与当前确认客户相同",
"SHIPPING.CUSTOMER_RESOLUTION_REQUIRED": "请先完成客户识别确认", "SHIPPING.CUSTOMER_RESOLUTION_REQUIRED": "请先完成客户识别确认",
+33 -5
View File
@@ -1292,6 +1292,12 @@
"subtitle": "管理組織架構", "subtitle": "管理組織架構",
"edit": "編輯部門", "edit": "編輯部門",
"add": "添加部門", "add": "添加部門",
"addChild": "添加子部門",
"expandAll": "全部展開",
"collapseAll": "全部收起",
"expand": "展開",
"collapse": "收起",
"noCompany": "未分配公司",
"noDepts": "暫無部門配置", "noDepts": "暫無部門配置",
"noSearchResults": "未找到匹配的部門", "noSearchResults": "未找到匹配的部門",
"searchPlaceholder": "搜尋名稱、編碼或公司…", "searchPlaceholder": "搜尋名稱、編碼或公司…",
@@ -1304,9 +1310,9 @@
}, },
"actions": { "actions": {
"edit": "編輯", "edit": "編輯",
"delete": "刪除", "delete": "刪除"
"viewMembers": "View department members"
}, },
"tags": { "hidden": "已隱藏" },
"fields": { "fields": {
"name": "名稱", "name": "名稱",
"namePlaceholder": "例如:資訊技術部", "namePlaceholder": "例如:資訊技術部",
@@ -1315,6 +1321,12 @@
"company": "公司", "company": "公司",
"companyPlaceholder": "例如:總部", "companyPlaceholder": "例如:總部",
"description": "描述", "description": "描述",
"parent": "上級部門",
"parentRoot": "(作為頂級部門)",
"sort": "同級排序",
"visibility": "顯示設定",
"hidden": "在組織樹中隱藏",
"hiddenHint": "隱藏後不在組織樹中展示,管理端仍可見(對應 ERP「在組織框架圖中顯示否」)",
"descriptionPlaceholder": "請輸入部門描述..." "descriptionPlaceholder": "請輸入部門描述..."
}, },
"confirmDelete": "確定刪除該部門嗎?", "confirmDelete": "確定刪除該部門嗎?",
@@ -1322,9 +1334,25 @@
"nameRequired": "部門名稱必填" "nameRequired": "部門名稱必填"
}, },
"members": { "members": {
"title": "{name} Members", "empty": "該部門暫無員工",
"count": "{count} members", "includeDescendants": "含下級部門",
"empty": "No members" "searchPlaceholder": "搜尋姓名 / 工號 / 郵箱 / 手機",
"total": "共 {total} 人",
"hint": "點擊左側部門查看員工",
"prevPage": "上一頁",
"nextPage": "下一頁",
"columns": {
"name": "姓名",
"contact": "聯絡方式",
"employeeId": "工號",
"department": "部門",
"status": "狀態"
},
"status": {
"active": "啟用",
"pending": "待審核",
"rejected": "已拒絕"
}
} }
}, },
"agent": { "agent": {
+5
View File
@@ -3604,6 +3604,11 @@
"libraryNotConfigured": "當前系統暫未設定固定資產圖片文件庫,暫時無法查看圖片,請聯絡管理員處理。", "libraryNotConfigured": "當前系統暫未設定固定資產圖片文件庫,暫時無法查看圖片,請聯絡管理員處理。",
"noPhotoUploaded": "設備管理員尚未上傳照片~" "noPhotoUploaded": "設備管理員尚未上傳照片~"
}, },
"capabilityList": {
"button": "知識庫內容清單",
"dialogTitle": "知識庫內容清單",
"notFound": "該應用尚未配置知識庫內容清單"
},
"queryPreview": { "queryPreview": {
"title": "查詢結果全量預覽", "title": "查詢結果全量預覽",
"viewAll": "查看全部預覽", "viewAll": "查看全部預覽",
+8
View File
@@ -151,6 +151,7 @@
"AUTH_SSO_ASSERTION_ISSUE_FAILED": "平級服務登入聲明簽發失敗,請重試。", "AUTH_SSO_ASSERTION_ISSUE_FAILED": "平級服務登入聲明簽發失敗,請重試。",
"AUTH_FORBIDDEN": "你沒有權限執行此操作。", "AUTH_FORBIDDEN": "你沒有權限執行此操作。",
"CHAT.USER_ATTACHMENTS_LIMIT_EXCEEDED": "附件數量超過上限(最多 200 個),請減少後重試。", "CHAT.USER_ATTACHMENTS_LIMIT_EXCEEDED": "附件數量超過上限(最多 200 個),請減少後重試。",
"CHAT.CAPABILITY_LIST_NOT_FOUND": "該應用尚未配置知識庫內容清單,請在管理端常用問題中為它維護「能力清單條目」。",
"CONTRACT_PAYMENT_FORBIDDEN": "你沒有合約付款預警的存取權限。", "CONTRACT_PAYMENT_FORBIDDEN": "你沒有合約付款預警的存取權限。",
"CONTRACT_PAYMENT_ADMIN_REQUIRED": "僅管理員可執行合約付款預警的同步、掃描或發送操作。", "CONTRACT_PAYMENT_ADMIN_REQUIRED": "僅管理員可執行合約付款預警的同步、掃描或發送操作。",
"CONTRACT_PAYMENT_ATTACHMENT_UNAVAILABLE": "合約原文已被清理,且無法從原系統重新下載。請先同步 OA 資料後再試。", "CONTRACT_PAYMENT_ATTACHMENT_UNAVAILABLE": "合約原文已被清理,且無法從原系統重新下載。請先同步 OA 資料後再試。",
@@ -621,6 +622,13 @@
"INTEGRATION.BINDING_LEGACY_PUT_REJECTED": "舊單步欄位會截斷該繫結的多步配方,請改用 steps_json 提交有序步驟。", "INTEGRATION.BINDING_LEGACY_PUT_REJECTED": "舊單步欄位會截斷該繫結的多步配方,請改用 steps_json 提交有序步驟。",
"INTEGRATION.CALL_NOT_FOUND": "整合調用記錄不存在。", "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": "該部門名下仍有員工,無法刪除。",
"SHIPPING.CUSTOMER_REBIND_BLOCKED": "已產生發貨通知/Excel,無法修改客戶,請先走撤銷流程", "SHIPPING.CUSTOMER_REBIND_BLOCKED": "已產生發貨通知/Excel,無法修改客戶,請先走撤銷流程",
"SHIPPING.CUSTOMER_REBIND_SAME_CUSTOMER": "新客戶與當前確認客戶相同", "SHIPPING.CUSTOMER_REBIND_SAME_CUSTOMER": "新客戶與當前確認客戶相同",
"SHIPPING.CUSTOMER_RESOLUTION_REQUIRED": "請先完成客戶識別確認", "SHIPPING.CUSTOMER_RESOLUTION_REQUIRED": "請先完成客戶識別確認",
+7
View File
@@ -6,6 +6,9 @@ import vue from '@vitejs/plugin-vue'
const rootDir = path.dirname(fileURLToPath(import.meta.url)) const rootDir = path.dirname(fileURLToPath(import.meta.url))
const frontendPort = Number(process.env.HXOPS_FRONTEND_PORT || '8881') const frontendPort = Number(process.env.HXOPS_FRONTEND_PORT || '8881')
const apiProxyTarget = process.env.HXOPS_API_PROXY_TARGET || 'http://127.0.0.1:5052' const apiProxyTarget = process.env.HXOPS_API_PROXY_TARGET || 'http://127.0.0.1:5052'
// Windows 下杀软实时扫描/系统睡眠可能使文件事件丢失(表现为“改了不生效、刷新也拿旧代码”),
// 设置 HXOPS_VITE_POLLING=1 改用轮询监听:不依赖系统文件事件,稳定但略耗 CPU,按机器自选
const usePolling = process.env.HXOPS_VITE_POLLING === '1'
// https://vite.dev/config/ // https://vite.dev/config/
export default defineConfig({ export default defineConfig({
@@ -18,6 +21,10 @@ export default defineConfig({
server: { server: {
port: frontendPort, // 默认 8881,允许本地通过环境变量覆盖,避免与其它仓库冲突 port: frontendPort, // 默认 8881,允许本地通过环境变量覆盖,避免与其它仓库冲突
strictPort: true, // 端口被占用时直接失败,由 start_local.ps1 先释放旧进程 strictPort: true, // 端口被占用时直接失败,由 start_local.ps1 先释放旧进程
watch: {
usePolling,
interval: 300
},
allowedHosts: ['hx.benl.cn'], allowedHosts: ['hx.benl.cn'],
proxy: { proxy: {
'/api': { '/api': {