feat(admin): 部门管理改造为组织树形结构

This commit is contained in:
HTEWJ\26070045 committed 2026-10-08 09:38:36 +08:00
1 parent c5b7cc662b
commit 48fe19ed71
21 files changed
+1086 -234

No files matched your search

+4 -3
View File
@@ -576,10 +576,11 @@ export const updateAdminUserPermissions = (userId: number, agentIds: number[]) =
body: JSON.stringify({ agent_ids: agentIds }),
});
// Departments
// Departments(树形结构:/tree 返回 children 嵌套,成员支持含下级)
export const listAdminDepartments = () => requestJson<any[]>('/api/admin/departments', auth());
export const listAdminDepartmentMembers = (id: number) =>
requestJson(`/api/admin/departments/${id}/members`, auth());
export const listAdminDepartmentTree = () => requestJson<any[]>('/api/admin/departments/tree', auth());
export const listAdminDepartmentMembers = (id: number, includeDescendants = false) =>
requestJson(`/api/admin/departments/${id}/members${includeDescendants ? '?include_descendants=1' : ''}`, auth());
export const createAdminDepartment = (payload: Record<string, unknown>) =>
requestJson('/api/admin/departments', { method: 'POST', ...jsonAuth(), body: JSON.stringify(payload) });
export const updateAdminDepartment = (id: number, payload: Record<string, unknown>) =>
@@ -1,40 +1,56 @@
/**
* features/admin/modules/departments/DepartmentsPage.vue
* 用途:部门管理独立页面——全宽表格列表 + 列排序 + 创建/编辑居中弹窗。
* 依赖:useDepartmentsAdmin、SortableTableHeader、DepartmentFormModal、DeleteConfirmDialog。
* 逻辑:路由 /admin/departments;表头排序复用 shared SortableTableHeader + useTableSort。
* 用途:部门管理独立页面——树形表格(公司虚拟分组 + 部门层级缩进展开)+ 搜索 + 创建/编辑弹窗。
* 依赖:useDepartmentsAdmin、DepartmentFormModal、DepartmentMembersModal、DeleteConfirmDialog。
* 逻辑:路由 /admin/departments;数据来自 /admin/departments/tree;公司层为前端按 company 字段虚拟分组。
*/
<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { Edit, Plus, Search, Trash2, Users } from 'lucide-vue-next';
import {
Building2,
ChevronDown,
ChevronRight,
Edit,
EyeOff,
FolderPlus,
ListTree,
Plus,
Search,
Trash2,
Users,
} from 'lucide-vue-next';
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
import SortableTableHeader from '@/shared/components/SortableTableHeader.vue';
import DepartmentFormModal from './components/DepartmentFormModal.vue';
import DepartmentMembersModal from './components/DepartmentMembersModal.vue';
import { useDepartmentsAdmin } from './composables/useDepartmentsAdmin';
import { listAdminDepartmentMembers } from '@/features/admin/api/admin.api';
import type { AdminDepartmentMembersResponse } from '@/features/admin/types/admin.types';
import type { AdminDepartmentMembersResponse, AdminDepartmentTreeNode } from '@/features/admin/types/admin.types';
import { useMessage } from '@/shared/composables/useMessage';
const { t } = useI18n();
const msg = useMessage();
const showMembersModal = ref(false);
const departmentMembers = ref<AdminDepartmentMembersResponse | null>(null);
/** 成员弹窗当前部门 id 与「含下级」开关 */
const membersDeptId = ref<number | null>(null);
const includeDescendants = ref(false);
const {
filteredDepartments,
displayRows,
parentOptions,
form,
searchQuery,
sortKey,
sortDir,
isLoading,
isSaving,
showFormModal,
showDeleteConfirmDialog,
deleteConfirmMessage,
loadAll,
toggleSort,
toggleNode,
toggleCompany,
expandAll,
collapseAll,
openCreateModal,
openEditModal,
closeFormModal,
@@ -48,15 +64,29 @@ onMounted(() => {
void loadAll();
});
/** 加载并展示指定部门的员工名单。 */
const openDepartmentMembers = async (departmentId: number): Promise<void> => {
/** 加载并展示指定部门的员工名单(includeDescendants 控制是否含下级)。 */
const openDepartmentMembers = async (departmentId: number, include = false): Promise<void> => {
try {
departmentMembers.value = await listAdminDepartmentMembers(departmentId) as AdminDepartmentMembersResponse;
membersDeptId.value = departmentId;
includeDescendants.value = include;
departmentMembers.value = await listAdminDepartmentMembers(
departmentId,
include,
) as AdminDepartmentMembersResponse;
showMembersModal.value = true;
} catch (error) {
msg.error((error as Error).message || t('admin.msg.requestFailed'));
}
};
/** 切换成员弹窗「含下级部门」口径并重新拉取名单。 */
const toggleIncludeDescendants = (value: boolean): void => {
if (membersDeptId.value == null) return;
void openDepartmentMembers(membersDeptId.value, value);
};
/** 公司虚拟分组行 key 去前缀,得到分组 key(用于展开状态)。 */
const companyGroupKey = (rowKey: string): string => rowKey.slice('company:'.length);
</script>
<template>
@@ -74,7 +104,7 @@ const openDepartmentMembers = async (departmentId: number): Promise<void> => {
<button
type="button"
class="flex items-center gap-2 px-4 py-2 bg-brand-600 text-white rounded-xl hover:bg-brand-700 transition-all shadow-lg shadow-brand-200 active:scale-95 text-sm font-medium"
@click="openCreateModal"
@click="openCreateModal()"
>
<Plus class="w-4 h-4" />
<span>{{ t('admin.dept.add') }}</span>
@@ -91,103 +121,159 @@ const openDepartmentMembers = async (departmentId: number): Promise<void> => {
:placeholder="t('admin.dept.searchPlaceholder')"
/>
</div>
<div class="flex items-center gap-1">
<button
type="button"
class="p-2 text-muted hover:text-primary hover:bg-subtle rounded-lg transition-colors"
:title="t('admin.dept.expandAll')"
@click="expandAll"
><ListTree class="w-4 h-4" /></button>
<button
type="button"
class="p-2 text-muted hover:text-primary hover:bg-subtle rounded-lg transition-colors"
:title="t('admin.dept.collapseAll')"
@click="collapseAll"
><ChevronDown class="w-4 h-4" /></button>
</div>
</div>
<div class="admin-table-wrap">
<!-- 列宽:名称 / 编码 / 公司 / 员工 / 操作 -->
<!-- 列宽:名称(树)/ 编码 / 公司 / 员工 / 操作 -->
<table class="admin-table table-fixed">
<colgroup>
<col class="w-[25%]" />
<col class="w-[20%]" />
<col class="w-[30%]" />
<col class="w-[40%]" />
<col class="w-[14%]" />
<col class="w-[19%]" />
<col class="w-[12%]" />
<col class="w-[13%]" />
<col class="w-[15%]" />
</colgroup>
<thead>
<tr>
<th class="px-6 py-4 text-left text-xs">
<SortableTableHeader
column-key="name"
:label="t('admin.dept.headers.name')"
:active-key="sortKey"
:direction="sortDir"
@sort="toggleSort"
/>
</th>
<th class="px-6 py-4 text-left text-xs">
<SortableTableHeader
column-key="code"
:label="t('admin.dept.headers.code')"
:active-key="sortKey"
:direction="sortDir"
@sort="toggleSort"
/>
</th>
<th class="px-6 py-4 text-left text-xs">
<SortableTableHeader
column-key="company"
:label="t('admin.dept.headers.company')"
:active-key="sortKey"
:direction="sortDir"
@sort="toggleSort"
/>
</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.dept.headers.name') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.dept.headers.code') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.dept.headers.company') }}</th>
<th class="px-6 py-4 text-center text-xs">{{ t('admin.dept.headers.members') }}</th>
<th class="px-6 py-4 text-right text-xs">{{ t('admin.dept.headers.actions') }}</th>
</tr>
</thead>
<tbody>
<tr v-if="filteredDepartments.length === 0">
<tr v-if="displayRows.length === 0">
<td colspan="5" class="px-6 admin-table-empty">
{{ searchQuery.trim() ? t('admin.dept.noSearchResults') : t('admin.dept.noDepts') }}
</td>
</tr>
<tr v-for="d in filteredDepartments" :key="d.id" class="group">
<td class="px-6 py-4">
<div class="font-medium text-primary text-sm truncate" :title="d.name">{{ d.name }}</div>
<div
v-if="d.description"
class="text-xs text-muted truncate mt-0.5"
:title="d.description"
>
{{ d.description }}
</div>
</td>
<td class="px-6 py-4 text-sm text-muted font-mono whitespace-nowrap truncate" :title="d.code || '-'">
{{ d.code || '-' }}
</td>
<td class="px-6 py-4 text-sm text-muted truncate" :title="d.company || '-'">
{{ d.company || '-' }}
</td>
<td class="px-6 py-4 text-center">
<button
type="button"
class="inline-flex items-center justify-center rounded-lg bg-blue-50 p-2 text-blue-600 hover:bg-blue-100"
:title="t('admin.dept.actions.viewMembers')"
@click="openDepartmentMembers(d.id)"
><Users class="w-5 h-5" /><span class="ml-1 text-xs">{{ d.member_count || 0 }}</span></button>
</td>
<td class="px-6 py-4">
<div class="flex justify-end gap-1">
<template v-for="row in displayRows" :key="row.key">
<!-- 公司虚拟分组行(不入库,前端按 company 字段归堆) -->
<tr v-if="row.kind === 'company'" class="bg-subtle/40 cursor-pointer select-none" @click="toggleCompany(companyGroupKey(row.key))">
<td class="px-6 py-3">
<div class="flex items-center gap-2">
<component
:is="row.expanded ? ChevronDown : ChevronRight"
class="w-4 h-4 text-muted shrink-0"
/>
<Building2 class="w-4 h-4 text-brand-600 shrink-0" />
<span class="font-semibold text-primary text-sm truncate" :title="row.company">{{ row.company }}</span>
</div>
</td>
<td class="px-6 py-3 text-xs text-muted">—</td>
<td class="px-6 py-3 text-xs text-muted">
<span class="inline-flex items-center px-2 py-0.5 rounded-full bg-brand-50 text-brand-700">{{ t('admin.dept.headers.company') }}</span>
</td>
<td class="px-6 py-3 text-center">
<span class="inline-flex items-center text-sm text-muted" :title="t('admin.dept.members.countTitle', { count: row.totalMembers })">
<Users class="w-4 h-4 mr-1" />{{ row.totalMembers }}
</span>
</td>
<td class="px-6 py-3">
<div class="flex justify-end">
<button
type="button"
class="p-1.5 text-indigo-600 hover:bg-indigo-50 rounded-lg transition-colors"
:title="t('admin.dept.addChild')"
@click.stop="openCreateModal(null, row.company)"
>
<FolderPlus class="w-4 h-4" />
</button>
</div>
</td>
</tr>
<!-- 部门行(层级缩进) -->
<tr v-else class="group">
<td class="px-6 py-4">
<div
class="flex items-center gap-2 min-w-0"
:style="{ paddingLeft: `${(row.depth - 1) * 20}px` }"
>
<button
v-if="row.hasChildren"
type="button"
class="p-0.5 text-muted hover:text-primary rounded transition-colors shrink-0"
:title="row.expanded ? t('admin.dept.collapse') : t('admin.dept.expand')"
@click="toggleNode(row.node!.id)"
>
<component :is="row.expanded ? ChevronDown : ChevronRight" class="w-4 h-4" />
</button>
<span v-else class="w-5 h-5 shrink-0 inline-block rounded-full border border-dashed border-subtle" />
<span class="font-medium text-primary text-sm truncate" :title="row.node!.name">{{ row.node!.name }}</span>
<span
v-if="row.node!.is_hidden"
class="inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] bg-amber-50 text-amber-700 shrink-0"
:title="t('admin.dept.fields.hiddenHint')"
><EyeOff class="w-3 h-3" />{{ t('admin.dept.tags.hidden') }}</span>
</div>
<div
v-if="row.node!.description"
class="text-xs text-muted truncate mt-0.5"
:style="{ paddingLeft: `${(row.depth - 1) * 20 + 28}px` }"
:title="row.node!.description"
>
{{ row.node!.description }}
</div>
</td>
<td class="px-6 py-4 text-sm text-muted font-mono whitespace-nowrap truncate" :title="row.node!.code || '-'">
{{ row.node!.code || '-' }}
</td>
<td class="px-6 py-4 text-sm text-muted truncate" :title="row.node!.company || '-'">
{{ row.node!.company || '-' }}
</td>
<td class="px-6 py-4 text-center">
<button
type="button"
class="p-1.5 text-indigo-600 hover:bg-indigo-50 rounded-lg transition-colors"
:title="t('admin.dept.actions.edit')"
@click="openEditModal(d)"
>
<Edit class="w-4 h-4" />
</button>
<button
type="button"
class="p-1.5 text-red-600 hover:bg-red-50 rounded-lg transition-colors"
:title="t('admin.dept.actions.delete')"
@click="deleteDepartment(d.id)"
>
<Trash2 class="w-4 h-4" />
</button>
</div>
</td>
</tr>
class="inline-flex items-center justify-center rounded-lg bg-blue-50 p-2 text-blue-600 hover:bg-blue-100"
:title="t('admin.dept.actions.viewMembers')"
@click="openDepartmentMembers(row.node!.id, false)"
><Users class="w-5 h-5" /><span class="ml-1 text-xs">{{ row.totalMembers }}</span></button>
</td>
<td class="px-6 py-4">
<div class="flex justify-end gap-1">
<button
type="button"
class="p-1.5 text-emerald-600 hover:bg-emerald-50 rounded-lg transition-colors"
:title="t('admin.dept.addChild')"
@click="openCreateModal(row.node as AdminDepartmentTreeNode)"
>
<FolderPlus class="w-4 h-4" />
</button>
<button
type="button"
class="p-1.5 text-indigo-600 hover:bg-indigo-50 rounded-lg transition-colors"
:title="t('admin.dept.actions.edit')"
@click="openEditModal(row.node!)"
>
<Edit class="w-4 h-4" />
</button>
<button
type="button"
class="p-1.5 text-red-600 hover:bg-red-50 rounded-lg transition-colors"
:title="t('admin.dept.actions.delete')"
@click="deleteDepartment(row.node!.id)"
>
<Trash2 class="w-4 h-4" />
</button>
</div>
</td>
</tr>
</template>
</tbody>
</table>
</div>
@@ -196,6 +282,7 @@ const openDepartmentMembers = async (departmentId: number): Promise<void> => {
<DepartmentFormModal
:visible="showFormModal"
:form="form"
:parent-options="parentOptions"
:is-saving="isSaving"
@close="closeFormModal"
@save="saveDepartment"
@@ -203,7 +290,9 @@ const openDepartmentMembers = async (departmentId: number): Promise<void> => {
<DepartmentMembersModal
:visible="showMembersModal"
:data="departmentMembers"
:include-descendants="includeDescendants"
@close="showMembersModal = false"
@set-include="toggleIncludeDescendants"
/>
<DeleteConfirmDialog
@@ -1,16 +1,18 @@
/**
/**
* features/admin/modules/departments/components/DepartmentFormModal.vue
* 用途:部门创建/编辑居中弹窗。
* 依赖:DepartmentFormState、admin 通用 modal 样式。
* 逻辑:DepartmentsPage 打开本组件;提交时 emit save,由 useDepartmentsAdmin 调 API。
* 用途:部门创建/编辑居中弹窗(含上级部门选择、同级排序、隐藏标记)。
* 依赖:DepartmentFormState、DeptParentOption、admin 通用 modal 样式。
* 逻辑:DepartmentsPage 打开本组件;上级选项由父级传入(编辑时已排除自身及子孙);提交时 emit save。
*/
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import type { DepartmentFormState } from '@/features/admin/types/department.types';
import type { DeptParentOption } from '../composables/useDepartmentsAdmin';
defineProps<{
visible: boolean;
form: DepartmentFormState;
parentOptions: DeptParentOption[];
isSaving: boolean;
}>();
@@ -31,6 +33,19 @@ const { t } = useI18n();
</h3>
</div>
<div class="px-5 sm:px-8 py-5 space-y-4 overflow-y-auto">
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.dept.fields.parent') }}</label>
<select v-model="form.parentId" class="input-field text-sm">
<option
v-for="option in parentOptions"
:key="String(option.id)"
:value="option.id"
:disabled="option.disabled"
>
{{ option.label }}
</option>
</select>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.dept.fields.name') }}</label>
<input
@@ -60,6 +75,25 @@ const { t } = useI18n();
/>
</div>
</div>
<div class="grid grid-cols-1 sm:grid-cols-2 gap-4 items-start">
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.dept.fields.sort') }}</label>
<input
v-model.number="form.sortOrder"
type="number"
class="input-field text-sm"
:placeholder="'0'"
/>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.dept.fields.visibility') }}</label>
<label class="flex items-center gap-2 text-sm text-muted cursor-pointer select-none py-2">
<input v-model="form.isHidden" type="checkbox" class="accent-brand-600 w-4 h-4" />
{{ t('admin.dept.fields.hidden') }}
</label>
<p class="text-xs text-muted">{{ t('admin.dept.fields.hiddenHint') }}</p>
</div>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.dept.fields.description') }}</label>
<textarea
@@ -1,26 +1,40 @@
/**
/**
* features/admin/modules/departments/components/DepartmentMembersModal.vue
* 用途:展示部门对应的员工数量和名单。
* 用途:展示部门对应的员工数量和名单(支持「含下级部门」口径切换)。
* 依赖:部门成员只读 API 响应与 Vue 事件。
* 逻辑:DepartmentsPage 点击员工图标后传入数据,本组件只负责呈现与关闭。
* 逻辑:DepartmentsPage 点击员工图标后传入数据;切换含下级开关时 emit set-include 由父级重新拉取。
*/
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import { Users, X } from 'lucide-vue-next';
import type { AdminDepartmentMembersResponse } from '@/features/admin/types/admin.types';
defineProps<{ visible: boolean; data: AdminDepartmentMembersResponse | null }>();
const emit = defineEmits<{ close: [] }>();
defineProps<{
visible: boolean;
data: AdminDepartmentMembersResponse | null;
/** 当前是否为「含下级部门」口径 */
includeDescendants: boolean;
}>();
const emit = defineEmits<{ close: []; setInclude: [value: boolean] }>();
const { t } = useI18n();
</script>
<template>
<div v-if="visible && data" class="admin-modal-overlay items-center" @click.self="emit('close')">
<section class="admin-modal-panel max-w-2xl max-h-[90vh] animate-fade-in-up">
<header class="px-8 py-6 border-b border-subtle flex items-center justify-between">
<div>
<h3 class="text-lg font-bold text-primary">{{ t('admin.dept.members.title', { name: data.department.name }) }}</h3>
<header class="px-8 py-6 border-b border-subtle flex items-start justify-between gap-4">
<div class="min-w-0">
<h3 class="text-lg font-bold text-primary truncate">{{ t('admin.dept.members.title', { name: data.department.name }) }}</h3>
<p class="text-sm text-muted mt-1">{{ t('admin.dept.members.count', { count: data.count }) }}</p>
<label class="flex items-center gap-2 text-sm text-muted cursor-pointer select-none mt-2">
<input
type="checkbox"
class="accent-brand-600 w-4 h-4"
:checked="includeDescendants"
@change="emit('setInclude', ($event.target as HTMLInputElement).checked)"
/>
{{ t('admin.dept.members.includeDescendants') }}
</label>
</div>
<button type="button" class="btn-icon-ds rounded-full" :title="t('admin.close')" @click="emit('close')"><X class="w-5 h-5" /></button>
</header>
@@ -33,7 +47,12 @@ const { t } = useI18n();
<li v-for="member in data.members" :key="member.id" class="py-3 flex items-center justify-between gap-4">
<div class="min-w-0">
<p class="font-medium text-primary">{{ member.real_name || member.username }}</p>
<p class="text-xs text-muted truncate">{{ member.employee_id || member.username }} · {{ member.email || '-' }}</p>
<p class="text-xs text-muted truncate">
{{ member.employee_id || member.username }} · {{ member.email || '-' }}
<template v-if="includeDescendants && member.department && member.department !== data.department.name">
· {{ t('admin.dept.members.fromDepartment', { department: member.department }) }}
</template>
</p>
</div>
<span class="text-xs text-muted whitespace-nowrap">{{ member.status }}</span>
</li>
@@ -1,40 +1,55 @@
/**
/**
* features/admin/modules/departments/composables/useDepartmentsAdmin.ts
* 用途:部门管理列表、搜索过滤、列排序、创建/编辑弹窗、删除。
* 依赖:admin.api、department.types、useMessage、useTableSort。
* 逻辑:DepartmentsPage 调用本 composable;排序状态委托 shared useTableSort。
* 用途:部门树加载、公司虚拟分组、展开/收起、搜索过滤、创建/编辑/删除。
* 依赖:admin.api、department.types、useMessage。
* 逻辑:DepartmentsPage 调用本 composable;数据来自 /admin/departments/tree(children 已按同级排序号排好);
* 公司层不入库,按顶级部门的 company 字段在前端虚拟分组。
*/
import { computed, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import {
createAdminDepartment,
deleteAdminDepartment,
listAdminDepartments,
listAdminDepartmentTree,
updateAdminDepartment,
} from '@/features/admin/api/admin.api';
import { useMessage } from '@/shared/composables/useMessage';
import { useTableSort } from '@/shared/composables/useTableSort';
import type { AdminDepartmentRow } from '@/features/admin/types/admin.types';
import type { AdminDepartmentTreeNode } from '@/features/admin/types/admin.types';
import {
createEmptyDepartmentForm,
departmentRowToForm,
type DepartmentFormState,
} from '@/features/admin/types/department.types';
/** 部门表可排序列 */
export type DeptSortKey = 'name' | 'code' | 'company';
/** 表单弹窗「上级部门」下拉选项(编辑时排除自身及子孙,防成环) */
export interface DeptParentOption {
id: number | null;
label: string;
disabled: boolean;
}
/** 树表展开后的一行:company 为公司虚拟分组行,dept 为部门行 */
export interface DeptTreeDisplayRow {
kind: 'company' | 'dept';
key: string;
/** 缩进层级:公司组为 0,顶级部门为 1,逐层 +1 */
depth: number;
company?: string;
/** dept 行对应的部门节点 */
node?: AdminDepartmentTreeNode;
expanded: boolean;
hasChildren: boolean;
/** 含下级递归汇总的成员数 */
totalMembers: number;
}
export function useDepartmentsAdmin() {
const { t } = useI18n();
const msg = useMessage();
const departments = ref<AdminDepartmentRow[]>([]);
const tree = ref<AdminDepartmentTreeNode[]>([]);
const form = ref<DepartmentFormState>(createEmptyDepartmentForm());
const searchQuery = ref('');
const { sortKey, sortDir, toggleSort, sortItems } = useTableSort<DeptSortKey>({
initialKey: 'name',
initialDir: 'asc',
});
const isLoading = ref(true);
const isSaving = ref(false);
const showFormModal = ref(false);
@@ -43,44 +58,139 @@ export function useDepartmentsAdmin() {
const deleteConfirmMessage = ref('');
let deleteConfirmAction: (() => Promise<void> | void) | null = null;
/**
* 先按关键词过滤,再按当前排序列排序。
* 核心逻辑:模糊匹配四字段 → useTableSort.sortItems。
*/
const filteredDepartments = computed(() => {
const q = searchQuery.value.trim().toLowerCase();
const filtered = q
? departments.value.filter((d) => {
const haystack = [d.name, d.code, d.company, d.description]
.filter(Boolean)
.join(' ')
.toLowerCase();
return haystack.includes(q);
})
: departments.value;
return sortItems(
filtered,
(row, key) => row[key],
(a, b) => a.id - b.id,
);
});
/** 展开状态:部门节点 id 集合 / 公司分组 key 集合 */
const expandedIds = ref<Set<number>>(new Set());
const expandedCompanies = ref<Set<string>>(new Set());
/**
* 拉取部门列表并写入 departments。
* 拉取部门树并写入 tree。
* @returns Promise<void>
*/
const loadDepartments = async (): Promise<void> => {
try {
departments.value = await listAdminDepartments();
tree.value = (await listAdminDepartmentTree()) as AdminDepartmentTreeNode[];
} catch (e) {
console.error('Failed to load departments', e);
departments.value = [];
console.error('Failed to load department tree', e);
tree.value = [];
}
};
/**
* 页面初始化:加载部门列表并结束 loading。
* 按关键词过滤树:命中节点及其祖先保留;搜索态下全部自动展开。
* 核心逻辑:递归 filterTree → 命中自身或子孙的节点保留。
*/
const displayRows = computed<DeptTreeDisplayRow[]>(() => {
const q = searchQuery.value.trim().toLowerCase();
const filterTree = (nodes: AdminDepartmentTreeNode[]): AdminDepartmentTreeNode[] => {
const out: AdminDepartmentTreeNode[] = [];
for (const n of nodes) {
const children = filterTree(n.children || []);
const haystack = [n.name, n.code, n.company, n.description]
.filter(Boolean)
.join(' ')
.toLowerCase();
if (!q || haystack.includes(q) || children.length) {
out.push({ ...n, children });
}
}
return out;
};
const activeTree = q ? filterTree(tree.value) : tree.value;
const rows: DeptTreeDisplayRow[] = [];
/** 递归铺开部门行;搜索态全展开,常态按 expandedIds */
const appendDeptRows = (nodes: AdminDepartmentTreeNode[], depth: number): void => {
for (const n of nodes) {
const children = n.children || [];
const expanded = q ? true : expandedIds.value.has(n.id);
rows.push({
kind: 'dept',
key: `dept:${n.id}`,
depth,
node: n,
expanded,
hasChildren: children.length > 0,
totalMembers: n.total_member_count || 0,
company: n.company,
});
if (expanded && children.length) appendDeptRows(children, depth + 1);
}
};
// 树顶公司虚拟分组:顶级部门按 company 文本归堆(未填公司归入「未分配公司」)
const groups = new Map<string, AdminDepartmentTreeNode[]>();
for (const root of activeTree) {
const key = root.company?.trim() || '';
if (!groups.has(key)) groups.set(key, []);
groups.get(key)!.push(root);
}
const groupKeys = [...groups.keys()].sort((a, b) => a.localeCompare(b, 'zh-Hans-CN'));
for (const key of groupKeys) {
const roots = groups.get(key)!;
const companyOpen = q ? true : expandedCompanies.value.has(key);
rows.push({
kind: 'company',
key: `company:${key}`,
depth: 0,
company: key || t('admin.dept.noCompany'),
expanded: companyOpen,
hasChildren: true,
totalMembers: roots.reduce((sum, r) => sum + (r.total_member_count || 0), 0),
});
if (companyOpen) appendDeptRows(roots, 1);
}
return rows;
});
/** 在树中按 id 查找节点。 */
const findNode = (
nodes: AdminDepartmentTreeNode[],
id: number,
): AdminDepartmentTreeNode | null => {
for (const n of nodes) {
if (n.id === id) return n;
const hit = findNode(n.children || [], id);
if (hit) return hit;
}
return null;
};
/** 表单弹窗「上级部门」选项:编辑时排除自身及子孙,避免把子树挂到自己下面 */
const parentOptions = computed<DeptParentOption[]>(() => {
const options: DeptParentOption[] = [
{ id: null, label: t('admin.dept.fields.parentRoot'), disabled: false },
];
const exclude = new Set<number>();
if (form.value.id) {
const stack: number[] = [form.value.id];
const target = findNode(tree.value, form.value.id);
const collect = (nodes: AdminDepartmentTreeNode[]): void => {
for (const n of nodes) {
stack.push(n.id);
collect(n.children || []);
}
};
if (target) collect(target.children || []);
while (stack.length) exclude.add(stack.pop()!);
}
const walk = (nodes: AdminDepartmentTreeNode[], depth: number): void => {
for (const n of nodes) {
options.push({
id: n.id,
label: `${' '.repeat(depth)}${n.name}`,
disabled: exclude.has(n.id),
});
walk(n.children || [], depth + 1);
}
};
walk(tree.value, 0);
return options;
});
/**
* 页面初始化:加载部门树并结束 loading。
* @returns Promise<void>
*/
const loadAll = async (): Promise<void> => {
@@ -89,6 +199,42 @@ export function useDepartmentsAdmin() {
isLoading.value = false;
};
/** 切换部门节点展开/收起。 */
const toggleNode = (id: number): void => {
const next = new Set(expandedIds.value);
if (next.has(id)) next.delete(id);
else next.add(id);
expandedIds.value = next;
};
/** 切换公司虚拟分组展开/收起。 */
const toggleCompany = (key: string): void => {
const next = new Set(expandedCompanies.value);
if (next.has(key)) next.delete(key);
else next.add(key);
expandedCompanies.value = next;
};
/** 全部展开(含所有公司组与部门节点)。 */
const expandAll = (): void => {
const ids = new Set<number>();
const walk = (nodes: AdminDepartmentTreeNode[]): void => {
for (const n of nodes) {
ids.add(n.id);
walk(n.children || []);
}
};
walk(tree.value);
expandedIds.value = ids;
expandedCompanies.value = new Set(tree.value.map((r) => r.company?.trim() || ''));
};
/** 全部收起(仅保留公司组层)。 */
const collapseAll = (): void => {
expandedIds.value = new Set();
expandedCompanies.value = new Set();
};
/**
* 打开删除确认对话框并绑定确认后的删除动作。
* @param message - 确认文案
@@ -119,17 +265,23 @@ export function useDepartmentsAdmin() {
}
};
/** 打开「添加部门」弹窗并重置表单。 */
const openCreateModal = (): void => {
/**
* 打开「添加部门」弹窗。
* @param parent - 上级部门节点(添加子部门时传入);空 = 顶级
* @param company - 预填公司(公司虚拟分组行的「添加子部门」传入)
*/
const openCreateModal = (parent?: AdminDepartmentTreeNode | null, company?: string): void => {
form.value = createEmptyDepartmentForm();
form.value.parentId = parent ? parent.id : null;
form.value.company = company ?? parent?.company ?? '';
showFormModal.value = true;
};
/**
* 打开「编辑部门」弹窗并回填选中行数据。
* @param dept - 待编辑的部门行
* @param dept - 待编辑的部门树节点
*/
const openEditModal = (dept: AdminDepartmentRow): void => {
const openEditModal = (dept: AdminDepartmentTreeNode): void => {
form.value = departmentRowToForm(dept);
showFormModal.value = true;
};
@@ -142,7 +294,8 @@ export function useDepartmentsAdmin() {
/**
* 保存部门:有 id 则更新,否则新建。
* 核心逻辑:校验名称 → 调 create/update API → 刷新列表并关闭弹窗。
* 核心逻辑:校验名称 → 组装含 parent_id/sort_order/is_hidden 的载荷 → 调 API → 刷新树并关闭弹窗。
* 后端负责同级查重、防成环等校验,失败抛 BusinessError(errors.json 四语言文案)。
* @returns Promise<void>
*/
const saveDepartment = async (): Promise<void> => {
@@ -157,6 +310,9 @@ export function useDepartmentsAdmin() {
code: form.value.code?.trim() || '',
company: form.value.company?.trim() || '',
description: form.value.description?.trim() || '',
parent_id: form.value.parentId ?? null,
sort_order: form.value.sortOrder ?? 0,
is_hidden: !!form.value.isHidden,
};
if (form.value.id) {
await updateAdminDepartment(form.value.id, payload);
@@ -174,6 +330,7 @@ export function useDepartmentsAdmin() {
/**
* 删除指定部门,删除前弹出确认框。
* 有下级部门或名下仍有员工时后端返回 409(HAS_CHILDREN / HAS_MEMBERS),此处展示其文案。
* @param id - 部门主键
*/
const deleteDepartment = (id: number): void => {
@@ -189,19 +346,21 @@ export function useDepartmentsAdmin() {
};
return {
departments,
filteredDepartments,
tree,
displayRows,
parentOptions,
form,
searchQuery,
sortKey,
sortDir,
isLoading,
isSaving,
showFormModal,
showDeleteConfirmDialog,
deleteConfirmMessage,
loadAll,
toggleSort,
toggleNode,
toggleCompany,
expandAll,
collapseAll,
openCreateModal,
openEditModal,
closeFormModal,
@@ -73,15 +73,30 @@ export interface AdminDepartmentRow {
code?: string;
company?: string;
description?: string;
/** 上级部门主键;null/缺省表示顶级部门 */
parent_id?: number | null;
/** 同级排序号(升序),对应 ERP hrao09 */
sort_order?: number;
/** 是否在组织树中隐藏(对应 ERP hrao08;管理端仍可见并打标) */
is_hidden?: boolean;
member_count?: number;
}
/** 部门树节点:/admin/departments/tree 返回结构,children 已按同级排序号排好 */
export interface AdminDepartmentTreeNode extends AdminDepartmentRow {
/** 含全部下级部门的成员总数(递归汇总) */
total_member_count?: number;
children: AdminDepartmentTreeNode[];
}
export interface AdminDepartmentMember {
id: number;
username: string;
real_name?: string;
employee_id?: string;
email?: string;
/** 成员所属部门名(含下级视图下用于区分来源部门) */
department?: string;
status?: string;
}
@@ -12,6 +12,12 @@ export interface DepartmentFormState {
code?: string;
company?: string;
description?: string;
/** 上级部门主键;null 表示顶级部门 */
parentId?: number | null;
/** 同级排序号(升序) */
sortOrder?: number;
/** 是否在组织树中隐藏 */
isHidden?: boolean;
}
/**
@@ -23,6 +29,9 @@ export const createEmptyDepartmentForm = (): DepartmentFormState => ({
code: '',
company: '',
description: '',
parentId: null,
sortOrder: 0,
isHidden: false,
});
/**
@@ -36,4 +45,7 @@ export const departmentRowToForm = (dept: AdminDepartmentRow): DepartmentFormSta
code: dept.code || '',
company: dept.company || '',
description: dept.description || '',
parentId: dept.parent_id ?? null,
sortOrder: dept.sort_order ?? 0,
isHidden: !!dept.is_hidden,
});
+16
View File
@@ -1244,6 +1244,12 @@
"subtitle": "Manage organization structure",
"edit": "Edit Department",
"add": "Add New Department",
"addChild": "Add sub-department",
"expandAll": "Expand all",
"collapseAll": "Collapse all",
"expand": "Expand",
"collapse": "Collapse",
"noCompany": "Unassigned company",
"noDepts": "No departments configured.",
"noSearchResults": "No matching departments found",
"searchPlaceholder": "Search by name, code, or company…",
@@ -1262,8 +1268,12 @@
"members": {
"title": "{name} Members",
"count": "{count} members",
"includeDescendants": "Include sub-departments",
"fromDepartment": "From: {department}",
"countTitle": "{count} people in total (incl. sub-departments)",
"empty": "No members"
},
"tags": { "hidden": "Hidden" },
"fields": {
"name": "Name",
"namePlaceholder": "e.g. IT Department",
@@ -1272,6 +1282,12 @@
"company": "Company",
"companyPlaceholder": "e.g. HQ",
"description": "Description",
"parent": "Parent department",
"parentRoot": "(As top-level department)",
"sort": "Sibling order",
"visibility": "Visibility",
"hidden": "Hide in organization tree",
"hiddenHint": "Hidden departments are excluded from the organization tree but remain visible here (maps to ERP \"show in org chart\")",
"descriptionPlaceholder": "Department description..."
},
"confirmDelete": "Delete this department?",
+8 -1
View File
@@ -598,6 +598,13 @@
"TRANSFER.DOCUMENT_NOT_FOUND": "Transfer ticket not found.",
"INTEGRATION.BINDING_LEGACY_PUT_REJECTED": "Legacy single-step fields would truncate this binding's multi-step recipe; submit ordered steps via steps_json instead.",
"INTEGRATION.CALL_NOT_FOUND": "Integration call not found.",
"INTEGRATION.BINDING_STEPS_INVALID": "Binding steps invalid: steps_json is required, must be a non-empty array of objects."
"INTEGRATION.BINDING_STEPS_INVALID": "Binding steps invalid: steps_json is required, must be a non-empty array of objects.",
"DEPT.NAME_REQUIRED": "Department name is required.",
"DEPT.PARENT_INVALID": "Parent department does not exist or has been deleted.",
"DEPT.NAME_EXISTS": "A sibling department with the same name already exists.",
"DEPT.CODE_EXISTS": "Department code is already used by another department.",
"DEPT.CYCLE_FORBIDDEN": "A department cannot be its own parent or descendant.",
"DEPT.HAS_CHILDREN": "This department has child departments; move or delete them first.",
"DEPT.HAS_MEMBERS": "This department still has members and cannot be deleted."
}
}
+16
View File
@@ -1244,6 +1244,12 @@
"subtitle": "จัดการโครงสร้างองค์กร",
"edit": "แก้ไขแผนก",
"add": "เพิ่มแผนกใหม่",
"addChild": "เพิ่มแผนกย่อย",
"expandAll": "ขยายทั้งหมด",
"collapseAll": "ยุบทั้งหมด",
"expand": "ขยาย",
"collapse": "ยุบ",
"noCompany": "ยังไม่ระบุบริษัท",
"noDepts": "ยังไม่มีการกำหนดค่าแผนก",
"noSearchResults": "ไม่พบแผนกที่ตรงกัน",
"searchPlaceholder": "ค้นหาชื่อ รหัส หรือบริษัท…",
@@ -1259,6 +1265,7 @@
"delete": "ลบ",
"viewMembers": "View department members"
},
"tags": { "hidden": "ซ่อนอยู่" },
"fields": {
"name": "ชื่อ",
"namePlaceholder": "เช่น แผนกไอที",
@@ -1267,6 +1274,12 @@
"company": "บริษัท",
"companyPlaceholder": "เช่น สำนักงานใหญ่",
"description": "คำอธิบาย",
"parent": "แผนกแม่",
"parentRoot": "(เป็นแผนกระดับบนสุด)",
"sort": "ลำดับภายในระดับเดียวกัน",
"visibility": "การแสดงผล",
"hidden": "ซ่อนในผังองค์กร",
"hiddenHint": "ซ่อนจากผังองค์กรแต่ผู้ดูแลระบบยังมองเห็น (ตรงกับ ERP \"แสดงในผังองค์กรหรือไม่\")",
"descriptionPlaceholder": "กรอกรายละเอียดแผนก..."
},
"confirmDelete": "ลบแผนกนี้หรือไม่?",
@@ -1276,6 +1289,9 @@
"members": {
"title": "{name} Members",
"count": "{count} members",
"includeDescendants": "รวมแผนกย่อย",
"fromDepartment": "จาก: {department}",
"countTitle": "รวมทั้งหมด {count} คน (รวมแผนกย่อย)",
"empty": "No members"
}
},
+8 -1
View File
@@ -598,6 +598,13 @@
"TRANSFER.DOCUMENT_NOT_FOUND": "ไม่พบตั๋วโอนย้าย",
"INTEGRATION.BINDING_LEGACY_PUT_REJECTED": "ฟิลด์ขั้นตอนเดียวแบบเดิมจะตัดทอนสูตรหลายขั้นตอนของการผูกนี้ โปรดส่งขั้นตอนตามลำดับด้วย steps_json แทน",
"INTEGRATION.CALL_NOT_FOUND": "ไม่พบระเบียนการเรียกใช้งานการผสานรวม",
"INTEGRATION.BINDING_STEPS_INVALID": "การกำหนดค่าขั้นตอนการเชื่อมโยงไม่ถูกต้อง: steps_json จำเป็นต้องมีและเป็นอาร์เรย์ที่ไม่ว่าง โดยแต่ละรายการต้องเป็นออบเจกต์"
"INTEGRATION.BINDING_STEPS_INVALID": "การกำหนดค่าขั้นตอนการเชื่อมโยงไม่ถูกต้อง: steps_json จำเป็นต้องมีและเป็นอาร์เรย์ที่ไม่ว่าง โดยแต่ละรายการต้องเป็นออบเจกต์",
"DEPT.NAME_REQUIRED": "กรุณากรอกชื่อแผนก",
"DEPT.PARENT_INVALID": "ไม่พบแผนกแม่หรือแผนกแม่ถูกลบแล้ว",
"DEPT.NAME_EXISTS": "มีแผนกชื่อเดียวกันอยู่ภายใต้แผนกแม่เดียวกันแล้ว",
"DEPT.CODE_EXISTS": "รหัสแผนกนี้ถูกใช้โดยแผนกอื่นแล้ว",
"DEPT.CYCLE_FORBIDDEN": "แผนกไม่สามารถเป็นแผนกแม่ของตัวเองหรือแผนกย่อยของตัวเองได้",
"DEPT.HAS_CHILDREN": "แผนกนี้มีแผนกย่อย กรุณาจัดการแผนกย่อยก่อนจึงจะลบได้",
"DEPT.HAS_MEMBERS": "แผนกนี้ยังมีพนักงานอยู่ จึงไม่สามารถลบได้"
}
}
+16
View File
@@ -1372,6 +1372,12 @@
"subtitle": "管理组织架构",
"edit": "编辑部门",
"add": "添加部门",
"addChild": "添加子部门",
"expandAll": "全部展开",
"collapseAll": "全部收起",
"expand": "展开",
"collapse": "收起",
"noCompany": "未分配公司",
"noDepts": "暂无部门配置",
"noSearchResults": "未找到匹配的部门",
"searchPlaceholder": "搜索名称、编码或公司…",
@@ -1390,8 +1396,12 @@
"members": {
"title": "{name}员工",
"count": "共 {count} 人",
"includeDescendants": "含下级部门",
"fromDepartment": "来自:{department}",
"countTitle": "含下级共 {count} 人",
"empty": "暂无员工"
},
"tags": { "hidden": "已隐藏" },
"fields": {
"name": "名称",
"namePlaceholder": "例如:信息技术部",
@@ -1400,6 +1410,12 @@
"company": "公司",
"companyPlaceholder": "例如:总部",
"description": "描述",
"parent": "上级部门",
"parentRoot": "(作为顶级部门)",
"sort": "同级排序",
"visibility": "显示设置",
"hidden": "在组织树中隐藏",
"hiddenHint": "隐藏后不在组织树中展示,管理端仍可见(对应 ERP「在组织框架图中显示否」)",
"descriptionPlaceholder": "请输入部门描述..."
},
"confirmDelete": "确定删除该部门吗?",
+8 -1
View File
@@ -598,6 +598,13 @@
"TRANSFER.DOCUMENT_NOT_FOUND": "调拨票不存在。",
"INTEGRATION.BINDING_LEGACY_PUT_REJECTED": "旧单步字段会截断该绑定的多步配方,请改用 steps_json 提交有序步骤。",
"INTEGRATION.CALL_NOT_FOUND": "集成调用记录不存在。",
"INTEGRATION.BINDING_STEPS_INVALID": "绑定步骤配置不合法:steps_json 必填且为非空数组,每项须为对象。"
"INTEGRATION.BINDING_STEPS_INVALID": "绑定步骤配置不合法:steps_json 必填且为非空数组,每项须为对象。",
"DEPT.NAME_REQUIRED": "部门名称必填。",
"DEPT.PARENT_INVALID": "上级部门不存在或已被删除。",
"DEPT.NAME_EXISTS": "同一上级部门下已存在同名部门。",
"DEPT.CODE_EXISTS": "部门编码已被其他部门使用。",
"DEPT.CYCLE_FORBIDDEN": "上级部门不能选择自己或自己的下级部门。",
"DEPT.HAS_CHILDREN": "该部门存在下级部门,请先处理下级部门后再删除。",
"DEPT.HAS_MEMBERS": "该部门名下仍有员工,无法删除。"
}
}
+16
View File
@@ -1244,6 +1244,12 @@
"subtitle": "管理組織架構",
"edit": "編輯部門",
"add": "添加部門",
"addChild": "添加子部門",
"expandAll": "全部展開",
"collapseAll": "全部收起",
"expand": "展開",
"collapse": "收起",
"noCompany": "未分配公司",
"noDepts": "暫無部門配置",
"noSearchResults": "未找到匹配的部門",
"searchPlaceholder": "搜尋名稱、編碼或公司…",
@@ -1259,6 +1265,7 @@
"delete": "刪除",
"viewMembers": "View department members"
},
"tags": { "hidden": "已隱藏" },
"fields": {
"name": "名稱",
"namePlaceholder": "例如:資訊技術部",
@@ -1267,6 +1274,12 @@
"company": "公司",
"companyPlaceholder": "例如:總部",
"description": "描述",
"parent": "上級部門",
"parentRoot": "(作為頂級部門)",
"sort": "同級排序",
"visibility": "顯示設定",
"hidden": "在組織樹中隱藏",
"hiddenHint": "隱藏後不在組織樹中展示,管理端仍可見(對應 ERP「在組織框架圖中顯示否」)",
"descriptionPlaceholder": "請輸入部門描述..."
},
"confirmDelete": "確定刪除該部門嗎?",
@@ -1276,6 +1289,9 @@
"members": {
"title": "{name} Members",
"count": "{count} members",
"includeDescendants": "含下級部門",
"fromDepartment": "來自:{department}",
"countTitle": "含下級共 {count} 人",
"empty": "No members"
}
},
+8 -1
View File
@@ -598,6 +598,13 @@
"TRANSFER.DOCUMENT_NOT_FOUND": "調撥票不存在。",
"INTEGRATION.BINDING_LEGACY_PUT_REJECTED": "舊單步欄位會截斷該繫結的多步配方,請改用 steps_json 提交有序步驟。",
"INTEGRATION.CALL_NOT_FOUND": "整合調用記錄不存在。",
"INTEGRATION.BINDING_STEPS_INVALID": "綁定步驟配置不合法:steps_json 必填且為非空陣列,每項須為物件。"
"INTEGRATION.BINDING_STEPS_INVALID": "綁定步驟配置不合法:steps_json 必填且為非空陣列,每項須為物件。",
"DEPT.NAME_REQUIRED": "部門名稱必填。",
"DEPT.PARENT_INVALID": "上級部門不存在或已被刪除。",
"DEPT.NAME_EXISTS": "同一上級部門下已存在同名部門。",
"DEPT.CODE_EXISTS": "部門編碼已被其他部門使用。",
"DEPT.CYCLE_FORBIDDEN": "上級部門不能選擇自己或自己的下級部門。",
"DEPT.HAS_CHILDREN": "該部門存在下級部門,請先處理下級部門後再刪除。",
"DEPT.HAS_MEMBERS": "該部門名下仍有員工,無法刪除。"
}
}