feat: 优化岗位权限,岗位菜单

This commit is contained in:
2026-08-15 15:15:56 +08:00
parent 64c38a4928
commit 0418b40aea
11 changed files with 985 additions and 858 deletions
@@ -0,0 +1,17 @@
-- 对齐职位相关菜单组件路径到 views/org/position/*
UPDATE `sys_menu`
SET `path` = '/organization/position',
`component` = 'org/position/list/index'
WHERE `name` = '职位管理';
UPDATE `sys_menu`
SET `path` = '/organization/position-menu',
`component` = 'org/position/menu/index',
`title` = '职位菜单分配'
WHERE `name` = '职位菜单分配';
UPDATE `sys_menu`
SET `path` = '/organization/position-permission',
`component` = 'org/position/permission/index',
`title` = '职位权限分配'
WHERE `name` = '职位权限分配';
@@ -446,15 +446,15 @@ SELECT 11002, (SELECT id FROM `sys_menu` WHERE `name` = '组织管理' LIMIT 1),
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `name` = '部门管理');
INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`)
SELECT 11003, (SELECT id FROM `sys_menu` WHERE `name` = '组织管理' LIMIT 1), 0, '职位管理', '职位管理', '/position', '/organization/position/index', '', 'lucide:tablet', 'menu', 1, 1, 0, 16
SELECT 11003, (SELECT id FROM `sys_menu` WHERE `name` = '组织管理' LIMIT 1), 0, '职位管理', '职位管理', '/organization/position', 'org/position/list/index', '', 'lucide:tablet', 'menu', 1, 1, 0, 16
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `name` = '职位管理');
INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`)
SELECT 11004, (SELECT id FROM `sys_menu` WHERE `name` = '组织管理' LIMIT 1), 0, '职位菜单分配', '职位菜单分配', '/organization/position-permission', '/organization/position-permission/index', '', 'lucide:lock', 'menu', 1, 1, 0, 17
SELECT 11004, (SELECT id FROM `sys_menu` WHERE `name` = '组织管理' LIMIT 1), 0, '职位菜单分配', '职位菜单分配', '/organization/position-menu', 'org/position/menu/index', '', 'lucide:lock', 'menu', 1, 1, 0, 17
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `name` = '职位菜单分配');
INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`)
SELECT 11005, (SELECT id FROM `sys_menu` WHERE `name` = '组织管理' LIMIT 1), 0, '职位权限分配', '职位权限分配', '/organization/position-permission-assign', '/organization/position-permission-assign/index', '', 'lucide:shield-check', 'menu', 1, 1, 0, 18
SELECT 11005, (SELECT id FROM `sys_menu` WHERE `name` = '组织管理' LIMIT 1), 0, '职位权限分配', '职位权限分配', '/organization/position-permission', 'org/position/permission/index', '', 'lucide:shield-check', 'menu', 1, 1, 0, 18
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `name` = '职位权限分配');
INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`)
@@ -0,0 +1,21 @@
import { requestClient } from '#/api/request';
/**
* 职位菜单管理 API(侧边栏菜单分配)
*/
/** 获取职位已分配菜单 ID */
export async function getPositionMenuIdsApi(positionId: number) {
return requestClient.get<number[]>(`/position-menu/menu-ids/${positionId}`);
}
/** 批量更新职位菜单 */
export async function batchUpdatePositionMenusApi(
positionId: number,
menuIds: number[],
) {
return requestClient.post<void>(
`/position-menu/batch-update/${positionId}`,
menuIds,
);
}
@@ -0,0 +1 @@
export * from './apis';
@@ -1,47 +1,30 @@
import { requestClient } from '#/api/request';
/**
* 职位权限分配API
* 用于管理职位分配的精确权限码(控制接口访问)
* @deprecated 请优先使用 `#/api/org/position/permission`
* 职位权限分配 API(兼容旧路径)
*/
/**
* 获取岗位所有权限ID列表
*/
export async function getPositionPermissionIdsApi(positionId: number) {
return requestClient.get<number[]>(`/position-permission/permission-ids/${positionId}`);
}
export {
batchUpdatePositionPermissionsApi,
getPositionPermissionIdsApi,
} from '../permission/apis';
/**
* 获取岗位所有权限码列表
*/
/** 获取岗位所有权限码列表 */
export async function getPositionPermissionCodesApi(positionId: number) {
return requestClient.get<string[]>(`/position-permission/permission-codes/${positionId}`);
}
/**
* 获取职位权限列表(含详情)
*/
export async function getPositionPermissionsApi(positionId: number) {
return requestClient.get<any[]>(`/position-permission/permissions/${positionId}`);
}
/**
* 批量更新职位权限
*/
export async function batchUpdatePositionPermissionsApi(
positionId: number,
permissionIds: number[],
) {
return requestClient.post<void>(
`/position-permission/batch-update/${positionId}`,
permissionIds,
return requestClient.get<string[]>(
`/position-permission/permission-codes/${positionId}`,
);
}
/**
* 检查岗位是否有指定权限
*/
/** 获取职位权限列表(含详情) */
export async function getPositionPermissionsApi(positionId: number) {
return requestClient.get<any[]>(
`/position-permission/permissions/${positionId}`,
);
}
/** 检查岗位是否有指定权限 */
export async function checkPositionPermissionApi(
positionId: number,
permissionId: number,
@@ -50,13 +33,3 @@ export async function checkPositionPermissionApi(
`/position-permission/check/${positionId}/${permissionId}`,
);
}
/**
* 获取系统所有权限(用于分配)
*/
export async function getAllPermissionsApi() {
return requestClient.post<any>('/permission/list', {
page: 1,
pageSize: 1000,
});
}
@@ -1,20 +1,23 @@
import { requestClient } from '#/api/request';
/**
* 职位菜单管理API
* 用于管理职位分配的菜单(控制侧边栏展示)
* 职位权限分配 API(接口权限码)
*/
/**
* 获取岗位所有菜单ID
*/
export async function getPositionMenuIdsApi(positionId: number) {
return requestClient.get<number[]>(`/position-menu/menu-ids/${positionId}`);
/** 获取职位已分配权限 ID */
export async function getPositionPermissionIdsApi(positionId: number) {
return requestClient.get<number[]>(
`/position-permission/permission-ids/${positionId}`,
);
}
/**
* 批量更新职位菜单
*/
export async function batchUpdatePositionMenusApi(positionId: number, menuIds: number[]) {
return requestClient.post<void>(`/position-menu/batch-update/${positionId}`, menuIds);
/** 批量更新职位权限 */
export async function batchUpdatePositionPermissionsApi(
positionId: number,
permissionIds: number[],
) {
return requestClient.post<void>(
`/position-permission/batch-update/${positionId}`,
permissionIds,
);
}
@@ -1,396 +0,0 @@
<script setup lang="ts">
import type { PositionVO } from '#/api/org/position/types';
import type { PermissionVO } from '#/api/sys/permission/types';
import { computed, onMounted, ref } from 'vue';
import { Page } from '@vben/common-ui';
import {
Button,
Card,
Flex,
Input,
message,
Pagination,
Select,
Spin,
Tag,
} from 'ant-design-vue';
import { getPositionPageApi } from '#/api/org/position';
import {
batchUpdatePositionPermissionsApi,
getPositionPermissionIdsApi,
} from '#/api/org/position/permission-assign/apis';
import { getCompanyVisiblePermissionTreeApi } from '#/api/sys/permission';
import TreeNodeContent from '#/views/company/permission/components/TreeNodeContent.vue';
defineOptions({ name: 'PositionPermissionAssignPage' });
// 搜索表单
const searchForm = ref({ name: '', status: undefined as number | undefined });
// 职位列表
const positionList = ref<PositionVO.PositionInfoVO[]>([]);
const positionLoading = ref(false);
const positionPagination = ref({ current: 1, pageSize: 10, total: 0 });
// 当前选中的职位
const currentPosition = ref<null | PositionVO.PositionInfoVO>(null);
// 权限树数据
const permissionTree = ref<PermissionVO.PermissionInfoVO[]>([]);
const permissionLoading = ref(false);
// 职位原始已分配的权限ID
const assignedPermissionIds = ref<number[]>([]);
// 用户当前选中的权限ID
const selectedPermissionIds = ref<number[]>([]);
// 展开状态
const expandedIds = ref<Set<number>>(new Set());
// 统计
const stats = computed(() => ({
total: countLeafPermissions(permissionTree.value),
assigned: assignedPermissionIds.value.length,
selected: selectedPermissionIds.value.length,
changed: !sameArray(selectedPermissionIds.value, assignedPermissionIds.value),
}));
function sameArray(a: number[], b: number[]): boolean {
if (a.length !== b.length) return false;
const sa = new Set(a);
return b.every((id) => sa.has(id));
}
// 搜索职位列表
async function searchPositions() {
positionLoading.value = true;
try {
const result = await getPositionPageApi({
page: positionPagination.value.current,
pageSize: positionPagination.value.pageSize,
filters: { name: searchForm.value.name || undefined, status: searchForm.value.status },
});
positionList.value = result.records;
positionPagination.value.total = result.total;
} catch (error: any) {
message.error(error?.message || '获取职位列表失败');
} finally {
positionLoading.value = false;
}
}
// 选择职位(切换公司时重载权限树,同公司内只更新已选状态)
async function selectPosition(position: PositionVO.PositionInfoVO) {
const isCompanyChanged = currentPosition.value?.companyId !== position.companyId;
currentPosition.value = position;
await loadAssignedPermissions();
if (isCompanyChanged) {
await loadPermissionTree();
}
}
// 加载职位已分配的权限ID
async function loadAssignedPermissions() {
if (!currentPosition.value?.id) return;
permissionLoading.value = true;
try {
const result = await getPositionPermissionIdsApi(currentPosition.value.id);
assignedPermissionIds.value = result || [];
selectedPermissionIds.value = [...assignedPermissionIds.value];
} catch (error: any) {
message.error(error?.message || '获取职位权限失败');
} finally {
permissionLoading.value = false;
}
}
// 加载权限树(公司的可见权限树,职位只能分配公司已有的权限)
async function loadPermissionTree() {
if (!currentPosition.value?.companyId) return;
try {
const result = await getCompanyVisiblePermissionTreeApi();
permissionTree.value = result || [];
expandedIds.value = new Set(result?.map((n: PermissionVO.PermissionInfoVO) => n.id) || []);
} catch (error: any) {
message.error(error?.message || '获取权限树失败');
}
}
// 保存权限分配(只保存叶子权限节点,模块节点仅作视觉分组)
async function savePermissions() {
if (!currentPosition.value?.id) return;
// 过滤掉模块节点,只保留叶子权限
const leafIds = selectedPermissionIds.value.filter((id) => {
const node = findNode(permissionTree.value, id);
return node && (!node.children || node.children.length === 0);
});
try {
await batchUpdatePositionPermissionsApi(currentPosition.value.id, leafIds);
message.success('权限分配保存成功');
assignedPermissionIds.value = [...leafIds];
selectedPermissionIds.value = [...leafIds];
} catch (error: any) {
message.error(error?.message || '保存失败');
}
}
function resetSearch() {
searchForm.value = { name: '', status: undefined };
positionPagination.value.current = 1;
searchPositions();
}
function handlePageChange(page: number, pageSize: number) {
positionPagination.value.current = page;
positionPagination.value.pageSize = pageSize;
searchPositions();
}
// 统计叶子权限数
function countLeafPermissions(nodes: PermissionVO.PermissionInfoVO[]): number {
let count = 0;
for (const node of nodes) {
if (node.children && node.children.length > 0) count += countLeafPermissions(node.children);
else count++;
}
return count;
}
// 获取所有叶子权限ID
function getAllLeafIds(nodes: PermissionVO.PermissionInfoVO[]): number[] {
const result: number[] = [];
for (const node of nodes) {
if (!node.children || node.children.length === 0) result.push(node.id);
else result.push(...getAllLeafIds(node.children));
}
return result;
}
// 全选
function selectAll() {
selectedPermissionIds.value = getAllLeafIds(permissionTree.value);
}
// 取消全选
function selectNone() {
selectedPermissionIds.value = [];
}
// 单个 checkbox 变化
function onCheck(permissionId: number, checked: boolean) {
if (checked) {
const toAdd = new Set<number>([permissionId]);
getParentChain(permissionTree.value, permissionId).forEach((id) => toAdd.add(id));
getDescendantIds(permissionTree.value, permissionId).forEach((id) => toAdd.add(id));
const newSet = new Set(selectedPermissionIds.value);
toAdd.forEach((id) => newSet.add(id));
selectedPermissionIds.value = Array.from(newSet);
} else {
const toRemove = new Set<number>([permissionId, ...getDescendantIds(permissionTree.value, permissionId)]);
selectedPermissionIds.value = selectedPermissionIds.value.filter((id) => !toRemove.has(id));
}
}
// 递归获取父节点链
function getParentChain(nodes: PermissionVO.PermissionInfoVO[], targetId: number, path: number[] = []): number[] {
for (const node of nodes) {
if (node.id === targetId) return [...path, node.id];
if (node.children) {
const found = getParentChain(node.children, targetId, [...path, node.id]);
if (found.length > 0) return found;
}
}
return [];
}
// 递归获取某节点下所有子孙ID
function getDescendantIds(nodes: PermissionVO.PermissionInfoVO[], permissionId: number): number[] {
const node = findNode(nodes, permissionId);
if (!node || !node.children) return [];
const result: number[] = [];
function collect(n: PermissionVO.PermissionInfoVO) {
if (n.children) {
for (const child of n.children) {
result.push(child.id);
collect(child);
}
}
}
for (const child of node.children) {
result.push(child.id);
collect(child);
}
return result;
}
// 递归查找节点
function findNode(nodes: PermissionVO.PermissionInfoVO[], id: number): PermissionVO.PermissionInfoVO | null {
for (const node of nodes) {
if (node.id === id) return node;
if (node.children) {
const found = findNode(node.children, id);
if (found) return found;
}
}
return null;
}
// 展开/收起
function toggleExpand(nodeId: number) {
const newSet = new Set(expandedIds.value);
if (newSet.has(nodeId)) newSet.delete(nodeId);
else newSet.add(nodeId);
expandedIds.value = newSet;
}
onMounted(() => {
searchPositions();
});
</script>
<template>
<Page :auto-content-height="true">
<Flex gap="middle" class="h-full">
<!-- 左栏:职位列表 -->
<Card
title="职位列表"
class="flex h-full max-w-[400px] flex-col"
:body-style="{ height: '100%', display: 'flex', flexDirection: 'column', gap: '10px' }"
>
<Flex class="flex-wrap gap-2">
<Input
v-model:value="searchForm.name"
placeholder="请输入职位名称"
allow-clear
style="width: 200px; margin-right: 8px"
/>
<Select
v-model:value="searchForm.status"
placeholder="请选择状态"
allow-clear
style="width: 120px; margin-right: 8px"
>
<Select.Option :value="1">启用</Select.Option>
<Select.Option :value="0">禁用</Select.Option>
</Select>
<Button type="primary" @click="searchPositions">搜索</Button>
<Button @click="resetSearch">重置</Button>
</Flex>
<Flex vertical class="flex-1">
<Spin :spinning="positionLoading">
<div class="flex-1">
<Card
v-for="position in positionList"
:key="position.id"
hoverable
size="small"
:body-style="{ padding: '10px 12px' }"
class="mb-2 cursor-pointer transition-all duration-200"
:class="[currentPosition?.id === position.id && 'ring-primary shadow ring-1']"
@click="selectPosition(position)"
>
<div class="flex items-start justify-between gap-2">
<div class="min-w-0">
<div class="mb-1 flex items-center gap-2">
<span
class="inline-block h-2 w-2 rounded-full"
:class="position.status === 1 ? 'bg-green-500' : 'bg-red-500'"
></span>
<span class="truncate text-sm font-semibold text-[var(--text-primary)]">
{{ position.name }}
</span>
</div>
<div class="text-xs text-[var(--text-secondary)]">编码:{{ position.code }}</div>
</div>
<Tag :color="position.status === 1 ? 'green' : 'red'">
{{ position.status === 1 ? '启用' : '禁用' }}
</Tag>
</div>
</Card>
</div>
</Spin>
<Flex justify="center" class="mt-2">
<Pagination
v-model:current="positionPagination.current"
v-model:page-size="positionPagination.pageSize"
:total="positionPagination.total"
:show-size-changer="true"
:show-quick-jumper="true"
@change="handlePageChange"
/>
</Flex>
</Flex>
</Card>
<!-- 右栏:职位权限分配 -->
<Card
title="职位权限分配"
class="flex h-full flex-1 flex-col"
:body-style="{ height: '100%' }"
>
<template v-if="currentPosition">
<!-- 头部 -->
<div class="mb-4 rounded bg-gray-50 p-4 dark:bg-neutral-800">
<div class="mb-3 flex items-center justify-between gap-2">
<div class="flex items-center gap-2">
<span class="text-base font-semibold">{{ currentPosition.name }}</span>
<Tag :color="currentPosition.status === 1 ? 'green' : 'red'">
{{ currentPosition.status === 1 ? '启用' : '禁用' }}
</Tag>
</div>
<div class="flex items-center gap-2">
<Button @click="selectNone">取消全选</Button>
<Button type="primary" @click="selectAll">一键全选</Button>
<Button type="primary" :disabled="!stats.changed" @click="savePermissions">
保存权限
</Button>
</div>
</div>
<div class="flex items-center gap-6 text-xs text-gray-500">
<span>编码:{{ currentPosition.code }}</span>
<span>全部叶子权限:<span class="font-semibold">{{ stats.total }}</span></span>
<span>已分配:<span class="font-semibold text-green-600">{{ stats.assigned }}</span></span>
<span>当前选择:<span class="font-semibold" :class="stats.changed ? 'text-orange-500' : 'text-green-600'">{{ stats.selected }}</span></span>
<span v-if="stats.changed" class="text-orange-500">(有未保存的更改)</span>
</div>
</div>
<!-- 权限树 -->
<div class="min-h-0 flex-1 overflow-y-auto">
<Spin :spinning="permissionLoading">
<div v-if="permissionTree.length > 0" class="py-2">
<TreeNodeContent
v-for="node in permissionTree"
:key="node.id"
:node="node"
:level="0"
:expanded-ids="expandedIds"
:selected-ids="selectedPermissionIds"
@toggle="toggleExpand"
@check="onCheck"
/>
</div>
<div v-else-if="!permissionLoading" class="py-8 text-center text-gray-500">
暂无可分配的权限
</div>
</Spin>
</div>
</template>
<div v-else class="flex h-full flex-1 items-center justify-center text-gray-500">
<div class="text-center">
<div class="mb-4 text-5xl">👈</div>
<div class="text-base">请先选择一个职位</div>
</div>
</div>
</Card>
</Flex>
</Page>
</template>
@@ -0,0 +1,542 @@
<script setup lang="ts">
import type { CompanyMenuVO } from '#/api/company/menu/types';
import type { PositionVO } from '#/api/org/position/types';
import { computed, onMounted, ref } from 'vue';
import { Page } from '@vben/common-ui';
import { createIconifyIcon } from '@vben/icons';
import {
Button,
Card,
Empty,
Flex,
Input,
message,
Select,
Space,
Spin,
Tag,
Tree,
} from 'ant-design-vue';
import { getCompanyMenuTreeApi } from '#/api/company/menu';
import { getPositionPageApi } from '#/api/org/position';
import {
batchUpdatePositionMenusApi,
getPositionMenuIdsApi,
} from '#/api/org/position/menu';
defineOptions({
name: 'PositionMenuManagePage',
});
const BriefcaseIcon = createIconifyIcon('lucide:briefcase');
const searchForm = ref({
name: '',
status: undefined as number | undefined,
});
const positionList = ref<PositionVO.PositionInfoVO[]>([]);
const positionLoading = ref(false);
const positionPagination = ref({
current: 1,
pageSize: 20,
total: 0,
});
const currentPosition = ref<null | PositionVO.PositionInfoVO>(null);
const companyMenuTree = ref<CompanyMenuVO.CompanyMenuInfo[]>([]);
const menuTreeLoading = ref(false);
const positionMenuIds = ref<number[]>([]);
const permissionLoading = ref(false);
const checkedKeys = ref<number[]>([]);
const expandedKeys = ref<number[]>([]);
const menuTreeData = computed(() => convertToTreeData(companyMenuTree.value));
const positionTotalPages = computed(() => {
const { total, pageSize } = positionPagination.value;
return Math.max(1, Math.ceil(total / pageSize) || 1);
});
const stats = computed(() => {
const totalMenus = getAllSelectableMenus().length;
const positionMenus = positionMenuIds.value.length;
const selectedMenus = ensureParentMenuIds(checkedKeys.value).length;
return {
total: totalMenus,
position: positionMenus,
selected: selectedMenus,
changed: !sameArray(
ensureParentMenuIds(checkedKeys.value),
positionMenuIds.value,
),
};
});
function sameArray(a: number[], b: number[]): boolean {
if (a.length !== b.length) return false;
const sa = new Set(a);
return b.every((id) => sa.has(id));
}
async function searchPositions() {
positionLoading.value = true;
try {
const result = await getPositionPageApi({
page: positionPagination.value.current,
pageSize: positionPagination.value.pageSize,
filters: {
name: searchForm.value.name || undefined,
status: searchForm.value.status,
},
});
positionList.value = result.records;
positionPagination.value.total = result.total;
} catch (error: any) {
message.error(error?.message || '获取职位列表失败');
} finally {
positionLoading.value = false;
}
}
async function loadCompanyMenuTree() {
menuTreeLoading.value = true;
try {
const result = await getCompanyMenuTreeApi();
companyMenuTree.value = result;
expandedKeys.value = getAllMenuIds(result);
} catch (error: any) {
message.error(error?.message || '获取菜单树失败');
} finally {
menuTreeLoading.value = false;
}
}
function getAllMenuIds(menus: CompanyMenuVO.CompanyMenuInfo[]): number[] {
const ids: number[] = [];
function traverse(menuList: CompanyMenuVO.CompanyMenuInfo[]) {
menuList.forEach((menu) => {
ids.push(menu.id);
if (menu.children && menu.children.length > 0) {
traverse(menu.children);
}
});
}
traverse(menus);
return ids;
}
function convertToTreeData(menus: CompanyMenuVO.CompanyMenuInfo[]): any[] {
return menus.map((menu) => ({
key: menu.id,
title: menu.name,
type: menu.type,
superMenu: menu.superMenu,
status: menu.status,
disabled: menu.status === 0,
children:
menu.children && menu.children.length > 0
? convertToTreeData(menu.children)
: undefined,
}));
}
async function selectPosition(position: PositionVO.PositionInfoVO) {
currentPosition.value = position;
await loadPositionPermissions();
}
async function loadPositionPermissions() {
if (!currentPosition.value?.id) return;
permissionLoading.value = true;
try {
const result = await getPositionMenuIdsApi(currentPosition.value.id);
positionMenuIds.value = result;
checkedKeys.value = cleanRootNodes(result);
} catch (error: any) {
message.error(error?.message || '获取职位菜单失败');
} finally {
permissionLoading.value = false;
}
}
/** 只保留叶子节点,供 Tree 勾选回显 */
function cleanRootNodes(menuIds: number[]): number[] {
return menuIds.filter((menuId) => {
const menu = findMenuById(menuId);
if (!menu) return false;
return !hasMenuChildren(menuId);
});
}
function findMenuById(menuId: number): CompanyMenuVO.CompanyMenuInfo | null {
function search(
menus: CompanyMenuVO.CompanyMenuInfo[],
): CompanyMenuVO.CompanyMenuInfo | null {
for (const menu of menus) {
if (menu.id === menuId) return menu;
if (menu.children && menu.children.length > 0) {
const found = search(menu.children);
if (found) return found;
}
}
return null;
}
return search(companyMenuTree.value);
}
function hasMenuChildren(menuId: number): boolean {
const menu = findMenuById(menuId);
return !!(menu?.children && menu.children.length > 0);
}
function ensureParentMenuIds(menuIds: number[]): number[] {
const result = new Set(menuIds);
function addAllParentIds(menuId: number) {
const menu = findMenuById(menuId);
if (menu && menu.parentId) {
result.add(menu.parentId);
addAllParentIds(menu.parentId);
}
}
menuIds.forEach((menuId) => {
addAllParentIds(menuId);
});
return [...result];
}
async function savePositionPermissions() {
if (!currentPosition.value?.id) return;
try {
const finalMenuIds = ensureParentMenuIds(checkedKeys.value);
await batchUpdatePositionMenusApi(currentPosition.value.id, finalMenuIds);
message.success('权限配置保存成功');
await loadPositionPermissions();
} catch (error: any) {
message.error(error?.message || '保存菜单失败');
}
}
function handleSelectAll() {
const leafMenus = getAllSelectableMenus().filter(
(menu) => !hasMenuChildren(menu.id),
);
checkedKeys.value = leafMenus.map((menu) => menu.id);
}
function handleSelectNone() {
checkedKeys.value = [];
}
function getAllSelectableMenus(): CompanyMenuVO.CompanyMenuInfo[] {
const result: CompanyMenuVO.CompanyMenuInfo[] = [];
function traverse(menus: CompanyMenuVO.CompanyMenuInfo[]) {
menus.forEach((menu) => {
if (menu.status === 1) {
result.push(menu);
}
if (menu.children && menu.children.length > 0) {
traverse(menu.children);
}
});
}
traverse(companyMenuTree.value);
return result;
}
function handleTreeCheckChange(
checked:
| (number | string)[]
| { checked: (number | string)[]; halfChecked: (number | string)[] },
) {
const keys = Array.isArray(checked) ? checked : checked.checked;
checkedKeys.value = keys.map((k) => Number(k));
}
function resetSearch() {
searchForm.value = {
name: '',
status: undefined,
};
positionPagination.value.current = 1;
searchPositions();
}
function handlePageChange(page: number, pageSize: number) {
positionPagination.value.current = page;
positionPagination.value.pageSize = pageSize;
searchPositions();
}
function goPositionPage(page: number) {
const next = Math.min(positionTotalPages.value, Math.max(1, page));
if (next === positionPagination.value.current) {
return;
}
handlePageChange(next, positionPagination.value.pageSize);
}
onMounted(() => {
searchPositions();
loadCompanyMenuTree();
});
</script>
<template>
<Page title="职位菜单分配" :auto-content-height="true">
<template #description>
<div class="text-foreground/80 mt-2">
左侧选择职位,右侧勾选并保存该职位可访问的菜单。
</div>
</template>
<template #extra>
<Space>
<Button :disabled="!currentPosition" @click="handleSelectNone">
取消全选
</Button>
<Button
type="primary"
:disabled="!currentPosition"
@click="handleSelectAll"
>
一键全选
</Button>
<Button
type="primary"
:disabled="!currentPosition || !stats.changed"
@click="savePositionPermissions"
>
保存配置
</Button>
</Space>
</template>
<Flex gap="middle" class="h-full min-h-0 overflow-hidden">
<!-- 左:职位 -->
<Card
class="flex h-full w-[320px] shrink-0 flex-col overflow-hidden"
:body-style="{
height: '100%',
display: 'flex',
flexDirection: 'column',
gap: '8px',
minHeight: 0,
minWidth: 0,
overflow: 'hidden',
padding: '12px',
}"
>
<template #title>
<span class="flex items-center gap-2 text-base font-semibold">
<BriefcaseIcon class="h-4 w-4" />
职位
</span>
</template>
<div class="flex min-w-0 shrink-0 flex-col gap-2">
<Input
v-model:value="searchForm.name"
placeholder="职位名称"
allow-clear
class="w-full min-w-0"
@press-enter="searchPositions"
/>
<div class="flex min-w-0 items-center gap-2">
<Select
v-model:value="searchForm.status"
placeholder="状态"
allow-clear
class="min-w-0 flex-1"
:options="[
{ label: '启用', value: 1 },
{ label: '禁用', value: 0 },
]"
/>
<Button type="primary" class="shrink-0" @click="searchPositions">
搜索
</Button>
<Button class="shrink-0" @click="resetSearch">重置</Button>
</div>
</div>
<div class="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden">
<div class="min-h-0 flex-1 overflow-y-auto">
<Spin :spinning="positionLoading">
<Empty
v-if="!positionLoading && positionList.length === 0"
class="py-8"
description="暂无职位"
/>
<template v-else>
<Card
v-for="position in positionList"
:key="position.id"
size="small"
:body-style="{ padding: '10px 12px' }"
class="mb-2 cursor-pointer !shadow-none last:mb-0 hover:border-primary"
:class="
currentPosition?.id === position.id
? 'border-primary bg-primary/5'
: undefined
"
@click="selectPosition(position)"
>
<div class="flex items-start justify-between gap-2">
<div class="min-w-0">
<div class="truncate text-sm font-medium">
{{ position.name }}
</div>
<div class="mt-0.5 truncate text-xs text-muted-foreground">
编码:{{ position.code }}
</div>
<div
v-if="position.remark"
class="mt-0.5 truncate text-xs text-muted-foreground"
>
{{ position.remark }}
</div>
</div>
<Tag
class="m-0 shrink-0"
:color="position.status === 1 ? 'green' : 'red'"
>
{{ position.status === 1 ? '启用' : '禁用' }}
</Tag>
</div>
</Card>
</template>
</Spin>
</div>
<div
class="mt-2 flex w-full min-w-0 shrink-0 items-center justify-between gap-2"
>
<Button
size="small"
class="shrink-0"
:disabled="positionPagination.current <= 1 || positionLoading"
@click="goPositionPage(positionPagination.current - 1)"
>
上一页
</Button>
<span
class="min-w-0 flex-1 truncate text-center text-xs text-muted-foreground"
>
{{ positionPagination.current }} / {{ positionTotalPages }}
<span class="ml-1 opacity-70"
>({{ positionPagination.total }})</span
>
</span>
<Button
size="small"
class="shrink-0"
:disabled="
positionPagination.current >= positionTotalPages ||
positionLoading
"
@click="goPositionPage(positionPagination.current + 1)"
>
下一页
</Button>
</div>
</div>
</Card>
<!-- 右:菜单分配 -->
<Card
class="flex h-full min-h-0 min-w-0 flex-1 flex-col"
:body-style="{
height: '100%',
minHeight: 0,
padding: 0,
display: 'flex',
flexDirection: 'column',
}"
>
<template #title>
<span class="text-base font-semibold">菜单分配</span>
</template>
<div
class="shrink-0 border-t border-border px-4 py-2 text-xs text-muted-foreground"
>
当前:
<template v-if="currentPosition">
{{ currentPosition.name }}
<Tag
class="ml-2"
:color="currentPosition.status === 1 ? 'green' : 'red'"
>
{{ currentPosition.status === 1 ? '启用' : '禁用' }}
</Tag>
<span class="ml-3">
系统菜单 {{ stats.total }} · 已配置
<strong class="text-green-600">{{ stats.position }}</strong> ·
当前选择
<strong class="text-blue-600">{{ stats.selected }}</strong>
<span v-if="stats.changed" class="text-orange-500"
>(有未保存更改)</span
>
</span>
</template>
<template v-else>请先选择职位</template>
</div>
<div
v-if="!currentPosition"
class="flex min-h-0 flex-1 items-center justify-center"
>
<Empty description="请从左侧选择职位以配置菜单" />
</div>
<div v-else class="min-h-0 flex-1 overflow-y-auto px-4 py-3 sm:px-5">
<Spin :spinning="permissionLoading || menuTreeLoading">
<Tree
v-if="menuTreeData.length > 0"
v-model:checked-keys="checkedKeys"
v-model:expanded-keys="expandedKeys"
:tree-data="menuTreeData"
checkable
block-node
:selectable="false"
@check="handleTreeCheckChange"
>
<template #title="{ title, status, disabled }">
<div class="flex min-w-0 items-center gap-2">
<span class="min-w-0 truncate font-medium">{{ title }}</span>
<Tag
v-if="status === 0 || disabled"
color="default"
class="m-0 shrink-0"
>
{{ status === 0 ? '已禁用' : '不可选择' }}
</Tag>
</div>
</template>
</Tree>
<Empty
v-else-if="!menuTreeLoading"
class="py-8"
description="暂无可分配的菜单"
/>
</Spin>
</div>
</Card>
</Flex>
</Page>
</template>
@@ -1,80 +1,156 @@
<script setup lang="ts">
import type { CompanyMenuVO } from '#/api/company/menu/types';
import type { PositionVO } from '#/api/org/position/types';
import type { PermissionVO } from '#/api/sys/permission/types';
import { computed, onMounted, ref } from 'vue';
import { Page } from '@vben/common-ui';
import { createIconifyIcon } from '@vben/icons';
import {
Button,
Card,
Empty,
Flex,
Input,
message,
Pagination,
Select,
Space,
Spin,
Tag,
Tree,
} from 'ant-design-vue';
import { getCompanyMenuTreeApi } from '#/api/company/menu';
import { getPositionPageApi } from '#/api/org/position';
import {
batchUpdatePositionMenusApi,
getPositionMenuIdsApi,
batchUpdatePositionPermissionsApi,
getPositionPermissionIdsApi,
} from '#/api/org/position/permission';
import { getCompanyVisiblePermissionTreeApi } from '#/api/sys/permission';
defineOptions({
name: 'PositionPermissionPage',
});
defineOptions({ name: 'PositionPermissionManagePage' });
const BriefcaseIcon = createIconifyIcon('lucide:briefcase');
type PermissionTreeNode = {
key: number;
title: string;
code?: string;
type?: string;
children?: PermissionTreeNode[];
};
// 搜索表单
const searchForm = ref({
name: '',
status: undefined as number | undefined,
});
// 职位列表
const positionList = ref<PositionVO.PositionInfoVO[]>([]);
const positionLoading = ref(false);
const positionPagination = ref({
current: 1,
pageSize: 10,
total: 0,
});
const positionPagination = ref({ current: 1, pageSize: 20, total: 0 });
// 当前选中的职位
const currentPosition = ref<null | PositionVO.PositionInfoVO>(null);
// 公司菜单树数据
const companyMenuTree = ref<CompanyMenuVO.CompanyMenuInfo[]>([]);
const menuTreeLoading = ref(false);
// 职位权限菜单ID列表
const positionMenuIds = ref<number[]>([]);
const permissionTree = ref<PermissionVO.PermissionInfoVO[]>([]);
const treeLoading = ref(false);
const permissionLoading = ref(false);
// 选中的菜单ID(用于树形控件)
const checkedKeys = ref<number[]>([]);
const savedPermissionIds = ref<number[]>([]);
const selectedPermissionIds = ref<number[]>([]);
const expandedKeys = ref<number[]>([]);
// 不区分超管与普通菜单
const permissionTreeData = computed(() =>
mapPermissionToTreeData(permissionTree.value),
);
const positionTotalPages = computed(() => {
const { total, pageSize } = positionPagination.value;
return Math.max(1, Math.ceil(total / pageSize) || 1);
});
const selectedLeafCount = computed(() => {
const selected = new Set(selectedPermissionIds.value);
return getAllLeafIds(permissionTree.value).filter((id) => selected.has(id))
.length;
});
const stats = computed(() => ({
total: countLeafPermissions(permissionTree.value),
saved: savedPermissionIds.value.length,
selected: selectedLeafCount.value,
changed: !sameArray(
getAllLeafIds(permissionTree.value).filter((id) =>
selectedPermissionIds.value.includes(id),
),
getAllLeafIds(permissionTree.value).filter((id) =>
savedPermissionIds.value.includes(id),
),
),
}));
function sameArray(a: number[], b: number[]): boolean {
if (a.length !== b.length) return false;
const sa = new Set(a);
return b.every((id) => sa.has(id));
}
function mapPermissionToTreeData(
nodes: PermissionVO.PermissionInfoVO[],
): PermissionTreeNode[] {
return nodes.map((node) => ({
key: node.id,
title: node.name,
code: node.code,
type: node.type,
children:
node.children && node.children.length > 0
? mapPermissionToTreeData(node.children)
: undefined,
}));
}
function collectExpandableKeys(nodes: PermissionVO.PermissionInfoVO[]): number[] {
const keys: number[] = [];
for (const node of nodes) {
if (node.children && node.children.length > 0) {
keys.push(node.id);
keys.push(...collectExpandableKeys(node.children));
}
}
return keys;
}
function countLeafPermissions(nodes: PermissionVO.PermissionInfoVO[]): number {
let count = 0;
for (const node of nodes) {
if (node.children && node.children.length > 0) {
count += countLeafPermissions(node.children);
} else {
count++;
}
}
return count;
}
function getAllLeafIds(nodes: PermissionVO.PermissionInfoVO[]): number[] {
const result: number[] = [];
for (const node of nodes) {
if (!node.children || node.children.length === 0) result.push(node.id);
else result.push(...getAllLeafIds(node.children));
}
return result;
}
// 搜索职位列表
async function searchPositions() {
positionLoading.value = true;
try {
const params = {
const result = await getPositionPageApi({
page: positionPagination.value.current,
pageSize: positionPagination.value.pageSize,
filters: {
name: searchForm.value.name || undefined,
status: searchForm.value.status,
},
};
const result = await getPositionPageApi(params);
});
positionList.value = result.records;
positionPagination.value.total = result.total;
} catch (error: any) {
@@ -84,438 +160,328 @@ async function searchPositions() {
}
}
// 加载公司菜单树
async function loadCompanyMenuTree() {
menuTreeLoading.value = true;
async function loadPermissionTree() {
treeLoading.value = true;
try {
const result = await getCompanyMenuTreeApi();
companyMenuTree.value = result;
// 自动展开所有节点
expandedKeys.value = getAllMenuIds(result);
const result = await getCompanyVisiblePermissionTreeApi();
permissionTree.value = result || [];
expandedKeys.value = collectExpandableKeys(result || []);
} catch (error: any) {
message.error(error?.message || '获取菜单树失败');
message.error(error?.message || '获取权限树失败');
} finally {
menuTreeLoading.value = false;
treeLoading.value = false;
}
}
// 获取所有菜单ID(递归)
function getAllMenuIds(menus: CompanyMenuVO.CompanyMenuInfo[]): number[] {
const ids: number[] = [];
function traverse(menuList: CompanyMenuVO.CompanyMenuInfo[]) {
menuList.forEach((menu) => {
ids.push(menu.id);
if (menu.children && menu.children.length > 0) {
traverse(menu.children);
}
});
}
traverse(menus);
return ids;
}
// 将菜单数据转换为Tree组件需要的格式
function convertToTreeData(menus: CompanyMenuVO.CompanyMenuInfo[]): any[] {
return menus.map((menu) => ({
key: menu.id,
title: menu.name,
type: menu.type,
superMenu: menu.superMenu,
status: menu.status,
disabled: menu.status === 0,
children:
menu.children && menu.children.length > 0
? convertToTreeData(menu.children)
: undefined,
}));
}
// 选择职位
async function selectPosition(position: PositionVO.PositionInfoVO) {
currentPosition.value = position;
await loadPositionPermissions();
}
// 加载职位权限
async function loadPositionPermissions() {
if (!currentPosition.value?.id) return;
permissionLoading.value = true;
try {
const result = await getPositionMenuIdsApi(currentPosition.value.id);
positionMenuIds.value = result;
// 清理根节点,只保留叶子节点
const leafMenuIds = cleanRootNodes(result);
checkedKeys.value = leafMenuIds;
const result = await getPositionPermissionIdsApi(currentPosition.value.id);
savedPermissionIds.value = result || [];
selectedPermissionIds.value = [...savedPermissionIds.value];
} catch (error: any) {
message.error(error?.message || '获取职位菜单失败');
message.error(error?.message || '加载职位权限失败');
} finally {
permissionLoading.value = false;
}
}
// 清理根节点,只保留叶子节点
function cleanRootNodes(menuIds: number[]): number[] {
return menuIds.filter((menuId) => {
const menu = findMenuById(menuId);
if (!menu) return false;
// 检查是否有其他菜单将此菜单作为父菜单
const hasChildren = hasMenuChildren(menuId);
// 只保留叶子节点(没有子节点的菜单)
return !hasChildren;
});
function handleTreeCheckChange(
checked:
| (number | string)[]
| { checked: (number | string)[]; halfChecked: (number | string)[] },
) {
const keys = Array.isArray(checked) ? checked : checked.checked;
selectedPermissionIds.value = keys.map((k) => Number(k));
}
// 根据ID查找菜单
function findMenuById(menuId: number): CompanyMenuVO.CompanyMenuInfo | null {
function search(
menus: CompanyMenuVO.CompanyMenuInfo[],
): CompanyMenuVO.CompanyMenuInfo | null {
for (const menu of menus) {
if (menu.id === menuId) return menu;
if (menu.children && menu.children.length > 0) {
const found = search(menu.children);
if (found) return found;
}
}
return null;
}
return search(companyMenuTree.value);
}
// 检查菜单是否有子菜单
function hasMenuChildren(menuId: number): boolean {
function search(menus: CompanyMenuVO.CompanyMenuInfo[]): boolean {
for (const menu of menus) {
if (menu.children && menu.children.length > 0) {
if (menu.children.some((child) => child.id === menuId)) return true;
if (search(menu.children)) return true;
}
}
return false;
}
return search(companyMenuTree.value);
}
// 确保提交时包含必要的父菜单ID(递归添加所有层级的父菜单)
function ensureParentMenuIds(menuIds: number[]): number[] {
const result = new Set(menuIds);
// 递归添加所有父菜单ID
function addAllParentIds(menuId: number) {
const menu = findMenuById(menuId);
if (menu && menu.parentId) {
result.add(menu.parentId);
// 递归添加父菜单的父菜单
addAllParentIds(menu.parentId);
}
}
// 为每个选中的菜单添加其所有父菜单ID
menuIds.forEach((menuId) => {
addAllParentIds(menuId);
});
return [...result];
}
// 保存职位权限
async function savePositionPermissions() {
async function handleSave() {
if (!currentPosition.value?.id) return;
try {
// 确保提交时包含必要的父菜单ID
const finalMenuIds = ensureParentMenuIds(checkedKeys.value);
await batchUpdatePositionMenusApi(currentPosition.value.id, finalMenuIds);
message.success('权限配置保存成功');
// 重新加载权限数据
await loadPositionPermissions();
} catch (error: any) {
message.error(error?.message || '保存菜单失败');
}
}
// 一键全选
function handleSelectAll() {
// 获取所有可选择的菜单ID(排除禁用的)
const selectableMenus = getAllSelectableMenus();
// 只选择叶子节点(没有子节点的菜单)
const leafMenus = selectableMenus.filter((menu) => {
return !hasMenuChildren(menu.id);
});
// 全选所有叶子节点
checkedKeys.value = leafMenus.map((menu) => menu.id);
}
// 取消全选
function handleSelectNone() {
// 取消所有叶子节点的选中状态
const allLeafMenuIds = new Set(
getAllSelectableMenus()
.filter((menu) => !hasMenuChildren(menu.id))
.map((menu) => menu.id),
const leafIds = getAllLeafIds(permissionTree.value).filter((id) =>
selectedPermissionIds.value.includes(id),
);
checkedKeys.value = checkedKeys.value.filter((id) => !allLeafMenuIds.has(id));
}
// 获取所有可选择的菜单
function getAllSelectableMenus(): CompanyMenuVO.CompanyMenuInfo[] {
const result: CompanyMenuVO.CompanyMenuInfo[] = [];
function traverse(menus: CompanyMenuVO.CompanyMenuInfo[]) {
menus.forEach((menu) => {
if (menu.status === 1) {
// 只包含启用的菜单
result.push(menu);
}
if (menu.children && menu.children.length > 0) {
traverse(menu.children);
}
});
try {
await batchUpdatePositionPermissionsApi(currentPosition.value.id, leafIds);
message.success('权限配置保存成功');
savedPermissionIds.value = [...leafIds];
selectedPermissionIds.value = [...leafIds];
} catch (error: any) {
message.error(error?.message || '保存失败');
}
traverse(companyMenuTree.value);
return result;
}
// 处理树形控件的选中变化
function handleTreeCheckChange(checkedKeysValue: any) {
checkedKeys.value = checkedKeysValue;
function selectAll() {
selectedPermissionIds.value = getAllLeafIds(permissionTree.value);
}
// 计算统计信息
const stats = computed(() => {
const totalMenus = getAllSelectableMenus().length;
const positionMenus = positionMenuIds.value.length;
const selectedMenus = ensureParentMenuIds(checkedKeys.value).length;
return {
total: totalMenus,
position: positionMenus,
selected: selectedMenus,
};
});
function selectNone() {
selectedPermissionIds.value = [];
}
// 重置搜索
function resetSearch() {
searchForm.value = {
name: '',
status: undefined,
};
searchForm.value = { name: '', status: undefined };
positionPagination.value.current = 1;
searchPositions();
}
// 分页变化
function handlePageChange(page: number, pageSize: number) {
positionPagination.value.current = page;
positionPagination.value.pageSize = pageSize;
searchPositions();
}
// 初始化
function goPositionPage(page: number) {
const next = Math.min(positionTotalPages.value, Math.max(1, page));
if (next === positionPagination.value.current) {
return;
}
handlePageChange(next, positionPagination.value.pageSize);
}
onMounted(() => {
searchPositions();
loadCompanyMenuTree();
loadPermissionTree();
});
</script>
<template>
<Page :auto-content-height="true">
<Flex gap="middle" class="h-full">
<!-- 左栏:职位列表 -->
<Page title="职位权限分配" :auto-content-height="true">
<template #description>
<div class="text-foreground/80 mt-2">
左侧选择职位,右侧勾选并保存该职位可使用的接口权限(可选范围为本公司已分配权限)。
</div>
</template>
<template #extra>
<Space>
<Button :disabled="!currentPosition" @click="selectNone">取消全选</Button>
<Button type="primary" :disabled="!currentPosition" @click="selectAll">
一键全选
</Button>
<Button
type="primary"
:disabled="!currentPosition || !stats.changed"
@click="handleSave"
>
保存配置
</Button>
</Space>
</template>
<Flex gap="middle" class="h-full min-h-0 overflow-hidden">
<Card
title="职位列表"
class="flex h-full max-w-[400px] flex-col"
class="flex h-full w-[320px] shrink-0 flex-col overflow-hidden"
:body-style="{
height: '100%',
display: 'flex',
flexDirection: 'column',
gap: '10px',
gap: '8px',
minHeight: 0,
minWidth: 0,
overflow: 'hidden',
padding: '12px',
}"
>
<!-- 搜索区域 -->
<Flex class="flex-wrap gap-2">
<Input
v-model:value="searchForm.name"
placeholder="请输入职位名称"
allow-clear
style="width: 200px; margin-right: 8px"
/>
<Select
v-model:value="searchForm.status"
placeholder="请选择状态"
allow-clear
style="width: 120px; margin-right: 8px"
>
<Select.Option :value="1">启用</Select.Option>
<Select.Option :value="0">禁用</Select.Option>
</Select>
<Button type="primary" @click="searchPositions"> 搜索 </Button>
<Button @click="resetSearch"> 重置 </Button>
</Flex>
<!-- 职位列表区域 -->
<Flex vertical class="flex-1">
<!-- 职位列表 -->
<Flex vertical class="flex-1">
<Spin :spinning="positionLoading">
<Card
v-for="position in positionList"
:key="position.id"
hoverable
size="small"
:body-style="{ padding: '10px 12px' }"
class="group mb-2 cursor-pointer transition-all duration-200"
:class="[
currentPosition?.id === position.id &&
'ring-primary shadow ring-1',
]"
@click="selectPosition(position)"
>
<div class="flex items-start justify-between gap-2">
<div class="min-w-0">
<div class="mb-1 flex items-center gap-2">
<span
class="inline-block h-2 w-2 rounded-full"
:class="
position.status === 1 ? 'bg-green-500' : 'bg-red-500'
"
></span>
<span
class="truncate text-sm font-semibold text-[var(--text-primary)]"
>
{{ position.name }}
</span>
</div>
<div class="mb-1 text-xs text-[var(--text-secondary)]">
编码:{{ position.code }}
</div>
<div
v-if="position.remark"
class="truncate text-xs text-[var(--text-secondary)]"
>
{{ position.remark }}
</div>
</div>
<Tag :color="position.status === 1 ? 'green' : 'red'">
{{ position.status === 1 ? '启用' : '禁用' }}
</Tag>
</div>
</Card>
</Spin>
</Flex>
<!-- 分页器 -->
<Flex justify="center">
<Pagination
v-model:current="positionPagination.current"
v-model:page-size="positionPagination.pageSize"
:total="positionPagination.total"
:show-size-changer="true"
:show-quick-jumper="true"
:show-total="(total) => `共 ${total} 条`"
@change="handlePageChange"
/>
</Flex>
</Flex>
</Card>
<!-- 右栏:权限管理 -->
<Card
title="职位菜单分配"
class="flex h-full flex-1 flex-col"
:body-style="{ height: '100%' }"
>
<template v-if="currentPosition">
<!-- 职位信息 + 统计与操作 -->
<div class="mb-4 rounded bg-gray-50 p-4 dark:bg-neutral-800">
<div class="mb-3 flex items-center justify-between gap-2">
<div class="flex items-center gap-2">
<span class="text-base font-semibold">{{
currentPosition.name
}}</span>
</div>
<div class="flex items-center gap-2">
<Button @click="handleSelectNone">取消全选</Button>
<Button type="primary" @click="handleSelectAll">
一键全选
</Button>
<Button type="primary" @click="savePositionPermissions">
保存菜单
</Button>
</div>
</div>
<div class="flex items-center gap-6 text-xs text-gray-500">
<span>编码:{{ currentPosition.code }}</span>
<span class="flex items-center gap-1">
<span class="text-[var(--text-secondary)]">系统菜单:</span>
<span class="text-sm font-semibold">{{ stats.total }}</span>
</span>
<span class="flex items-center gap-1">
<span class="text-[var(--text-secondary)]">已配置:</span>
<span class="text-sm font-semibold text-[var(--success)]">{{
stats.position
}}</span>
</span>
<span class="flex items-center gap-1">
<span class="text-[var(--text-secondary)]">当前选择:</span>
<span class="text-sm font-semibold text-[var(--primary)]">{{
stats.selected
}}</span>
</span>
</div>
</div>
<!-- 菜单树 -->
<div class="min-h-0 flex-1 overflow-y-auto">
<Spin :spinning="permissionLoading">
<Tree
v-model:checked-keys="checkedKeys"
v-model:expanded-keys="expandedKeys"
:tree-data="convertToTreeData(companyMenuTree)"
checkable
block-node
class="rounded border"
@check="handleTreeCheckChange"
>
<template #title="{ title, status, disabled }">
<div class="flex items-center gap-2">
<span class="font-medium">{{ title }}</span>
<span
v-if="status === 0"
class="rounded bg-red-50 px-1.5 py-0.5 text-xs text-red-600 dark:bg-red-900/30"
>
已禁用
</span>
<span
v-if="disabled"
class="rounded bg-red-50 px-1.5 py-0.5 text-xs text-red-600 dark:bg-red-900/30"
>
不可选择
</span>
</div>
</template>
</Tree>
</Spin>
</div>
<template #title>
<span class="flex items-center gap-2 text-base font-semibold">
<BriefcaseIcon class="h-4 w-4" />
职位
</span>
</template>
<div v-else class="flex h-full flex-1 items-center justify-center">
<div class="text-center text-gray-500">
<div class="mb-4 text-5xl">👈</div>
<div class="text-base">请先选择一个职位</div>
<div class="flex min-w-0 shrink-0 flex-col gap-2">
<Input
v-model:value="searchForm.name"
placeholder="职位名称"
allow-clear
class="w-full min-w-0"
@press-enter="searchPositions"
/>
<div class="flex min-w-0 items-center gap-2">
<Select
v-model:value="searchForm.status"
placeholder="状态"
allow-clear
class="min-w-0 flex-1"
:options="[
{ label: '启用', value: 1 },
{ label: '禁用', value: 0 },
]"
/>
<Button type="primary" class="shrink-0" @click="searchPositions">
搜索
</Button>
<Button class="shrink-0" @click="resetSearch">重置</Button>
</div>
</div>
<div class="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden">
<div class="min-h-0 flex-1 overflow-y-auto">
<Spin :spinning="positionLoading">
<Empty
v-if="!positionLoading && positionList.length === 0"
class="py-8"
description="暂无职位"
/>
<template v-else>
<Card
v-for="position in positionList"
:key="position.id"
size="small"
:body-style="{ padding: '10px 12px' }"
class="mb-2 cursor-pointer !shadow-none last:mb-0 hover:border-primary"
:class="
currentPosition?.id === position.id
? 'border-primary bg-primary/5'
: undefined
"
@click="selectPosition(position)"
>
<div class="flex items-start justify-between gap-2">
<div class="min-w-0">
<div class="truncate text-sm font-medium">
{{ position.name }}
</div>
<div class="mt-0.5 truncate text-xs text-muted-foreground">
编码:{{ position.code }}
</div>
</div>
<Tag
class="m-0 shrink-0"
:color="position.status === 1 ? 'green' : 'red'"
>
{{ position.status === 1 ? '启用' : '禁用' }}
</Tag>
</div>
</Card>
</template>
</Spin>
</div>
<div
class="mt-2 flex w-full min-w-0 shrink-0 items-center justify-between gap-2"
>
<Button
size="small"
class="shrink-0"
:disabled="positionPagination.current <= 1 || positionLoading"
@click="goPositionPage(positionPagination.current - 1)"
>
上一页
</Button>
<span
class="min-w-0 flex-1 truncate text-center text-xs text-muted-foreground"
>
{{ positionPagination.current }} / {{ positionTotalPages }}
<span class="ml-1 opacity-70"
>({{ positionPagination.total }})</span
>
</span>
<Button
size="small"
class="shrink-0"
:disabled="
positionPagination.current >= positionTotalPages ||
positionLoading
"
@click="goPositionPage(positionPagination.current + 1)"
>
下一页
</Button>
</div>
</div>
</Card>
<Card
class="flex h-full min-h-0 min-w-0 flex-1 flex-col"
:body-style="{
height: '100%',
minHeight: 0,
padding: 0,
display: 'flex',
flexDirection: 'column',
}"
>
<template #title>
<span class="text-base font-semibold">权限分配</span>
</template>
<div
class="shrink-0 border-t border-border px-4 py-2 text-xs text-muted-foreground"
>
当前:
<template v-if="currentPosition">
{{ currentPosition.name }}
<Tag
class="ml-2"
:color="currentPosition.status === 1 ? 'green' : 'red'"
>
{{ currentPosition.status === 1 ? '启用' : '禁用' }}
</Tag>
<span class="ml-3">
可分配叶子权限 {{ stats.total }} · 已配置
<strong class="text-green-600">{{ stats.saved }}</strong> · 当前选择
<strong class="text-blue-600">{{ stats.selected }}</strong>
<span v-if="stats.changed" class="text-orange-500"
>(有未保存更改)</span
>
</span>
</template>
<template v-else>请先选择职位</template>
</div>
<div
v-if="!currentPosition"
class="flex min-h-0 flex-1 items-center justify-center"
>
<Empty description="请从左侧选择职位以配置权限" />
</div>
<div v-else class="min-h-0 flex-1 overflow-y-auto px-4 py-3 sm:px-5">
<Spin :spinning="permissionLoading || treeLoading">
<Tree
v-if="permissionTreeData.length > 0"
v-model:checked-keys="selectedPermissionIds"
v-model:expanded-keys="expandedKeys"
:tree-data="permissionTreeData"
checkable
block-node
:selectable="false"
@check="handleTreeCheckChange"
>
<template #title="{ title, code, type }">
<div class="flex min-w-0 items-center gap-2">
<span class="min-w-0 truncate font-medium">{{ title }}</span>
<span
v-if="code"
class="shrink-0 text-xs text-muted-foreground"
>
{{ code }}
</span>
<Tag
v-if="type === 'module'"
color="purple"
class="m-0 shrink-0"
>
模块
</Tag>
</div>
</template>
</Tree>
<Empty
v-else-if="!treeLoading"
class="py-8"
description="暂无可分配权限(请先为公司分配权限)"
/>
</Spin>
</div>
</Card>
</Flex>
<!-- <div class="flex h-full gap-4 max-lg:flex-col">
</div> -->
</Page>
</template>