mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 01:19:19 +08:00
feat: 菜单权限管理
This commit is contained in:
+6
-6
@@ -6,6 +6,7 @@ import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.model.dto.menu.BatchSortMenuDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.model.dto.menu.CreateMenuDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.model.dto.menu.UpdateMenuDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.model.vo.MenuVO;
|
||||
@@ -72,12 +73,11 @@ public class MenuController {
|
||||
return ApiResponse.success(menuVO);
|
||||
}
|
||||
|
||||
@Operation(summary = "根据角色获取菜单树", description = "根据用户角色获取对应的菜单树")
|
||||
@GetMapping("/tree/role/{userRole}")
|
||||
public ApiResponse<List<MenuVO>> getMenuTreeByRole(
|
||||
@Parameter(description = "用户角色") @PathVariable String userRole) {
|
||||
List<MenuVO> menuTree = menuService.getMenuTreeByRole(userRole);
|
||||
return ApiResponse.success(menuTree);
|
||||
@Operation(summary = "批量菜单排序", description = "批量更新菜单的排序值")
|
||||
@PostMapping("/batch-sort")
|
||||
public ApiResponse<Void> batchSortMenu(@Valid @RequestBody BatchSortMenuDTO batchSortMenuDTO) {
|
||||
menuService.batchSortMenu(batchSortMenuDTO);
|
||||
return ApiResponse.success();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.sys.controller;
|
||||
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.model.dto.menu_permission.AddMenuPermissionDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.model.dto.menu_permission.RemoveMenuPermissionDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.model.vo.MenuPermissionVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.service.MenuPermissionService;
|
||||
|
||||
|
||||
/**
|
||||
* 菜单权限映射控制器
|
||||
*/
|
||||
@Tag(name = "系统-菜单权限映射管理", description = "菜单权限映射的增删接口")
|
||||
@RestController
|
||||
@RequestMapping("/menu-permission")
|
||||
public class MenuPermissionController {
|
||||
|
||||
private final MenuPermissionService menuPermissionService;
|
||||
|
||||
public MenuPermissionController(MenuPermissionService menuPermissionService) {
|
||||
this.menuPermissionService = menuPermissionService;
|
||||
}
|
||||
|
||||
@Operation(summary = "添加菜单权限映射", description = "为指定菜单添加权限映射")
|
||||
@PostMapping("/add")
|
||||
public ApiResponse<MenuPermissionVO> addMenuPermission(@Valid @RequestBody AddMenuPermissionDTO addMenuPermissionDTO) {
|
||||
MenuPermissionVO menuPermissionVO = menuPermissionService.addMenuPermission(addMenuPermissionDTO);
|
||||
return ApiResponse.success(menuPermissionVO);
|
||||
}
|
||||
|
||||
@Operation(summary = "删除菜单权限映射", description = "删除指定菜单的权限映射")
|
||||
@PostMapping("/remove")
|
||||
public ApiResponse<Void> removeMenuPermission(@Valid @RequestBody RemoveMenuPermissionDTO removeMenuPermissionDTO) {
|
||||
menuPermissionService.removeMenuPermission(removeMenuPermissionDTO);
|
||||
return ApiResponse.success();
|
||||
}
|
||||
|
||||
}
|
||||
+12
@@ -2,11 +2,23 @@ package top.xyquan.ecomdmbbackend.modules.sys.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.model.po.MenuPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.model.vo.PermissionVO;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 系统菜单Mapper
|
||||
*/
|
||||
@Mapper
|
||||
public interface MenuMapper extends BaseMapper<MenuPO> {
|
||||
|
||||
/**
|
||||
* 根据菜单ID查询权限列表
|
||||
*
|
||||
* @param menuId 菜单ID
|
||||
* @return 权限列表
|
||||
*/
|
||||
List<PermissionVO> selectPermissionsByMenuId(@Param("menuId") Long menuId);
|
||||
}
|
||||
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.sys.model.dto.menu;
|
||||
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 批量菜单排序DTO
|
||||
*/
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class BatchSortMenuDTO {
|
||||
|
||||
/**
|
||||
* 菜单排序项列表
|
||||
*/
|
||||
@NotNull(message = "菜单排序项列表不能为空")
|
||||
private List<MenuSortItem> sortItems;
|
||||
|
||||
/**
|
||||
* 菜单排序项
|
||||
*/
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public static class MenuSortItem {
|
||||
|
||||
/**
|
||||
* 菜单ID
|
||||
*/
|
||||
@NotNull(message = "菜单ID不能为空")
|
||||
private Long menuId;
|
||||
|
||||
/**
|
||||
* 排序值
|
||||
*/
|
||||
@NotNull(message = "排序值不能为空")
|
||||
private Integer order;
|
||||
}
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.sys.model.dto.menu_permission;
|
||||
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
/**
|
||||
* 添加菜单权限映射DTO
|
||||
*/
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class AddMenuPermissionDTO {
|
||||
|
||||
/**
|
||||
* 菜单ID
|
||||
*/
|
||||
@NotNull(message = "菜单ID不能为空")
|
||||
private Long menuId;
|
||||
|
||||
/**
|
||||
* 权限ID
|
||||
*/
|
||||
@NotNull(message = "权限ID不能为空")
|
||||
private Long permissionId;
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.sys.model.dto.menu_permission;
|
||||
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
/**
|
||||
* 删除菜单权限映射DTO
|
||||
*/
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class RemoveMenuPermissionDTO {
|
||||
|
||||
/**
|
||||
* 菜单ID
|
||||
*/
|
||||
@NotNull(message = "菜单ID不能为空")
|
||||
private Long menuId;
|
||||
|
||||
/**
|
||||
* 权限ID
|
||||
*/
|
||||
@NotNull(message = "权限ID不能为空")
|
||||
private Long permissionId;
|
||||
}
|
||||
+3
-3
@@ -7,7 +7,7 @@ import lombok.EqualsAndHashCode;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 菜单与权限关联实体
|
||||
* 菜单权限映射实体
|
||||
*/
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = false)
|
||||
@@ -41,6 +41,6 @@ public class MenuPermissionPO {
|
||||
/**
|
||||
* 创建人ID
|
||||
*/
|
||||
@TableField("create_by")
|
||||
@TableField(value = "create_by", fill = FieldFill.INSERT)
|
||||
private Long createBy;
|
||||
}
|
||||
}
|
||||
+13
-8
@@ -5,13 +5,13 @@ import lombok.Data;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 菜单权限关联VO
|
||||
* 菜单权限映射VO
|
||||
*/
|
||||
@Data
|
||||
public class MenuPermissionVO {
|
||||
|
||||
/**
|
||||
* 关联ID
|
||||
* 主键ID
|
||||
*/
|
||||
private Long id;
|
||||
|
||||
@@ -20,6 +20,11 @@ public class MenuPermissionVO {
|
||||
*/
|
||||
private Long menuId;
|
||||
|
||||
/**
|
||||
* 权限ID
|
||||
*/
|
||||
private Long permissionId;
|
||||
|
||||
/**
|
||||
* 菜单名称
|
||||
*/
|
||||
@@ -30,11 +35,6 @@ public class MenuPermissionVO {
|
||||
*/
|
||||
private String menuTitle;
|
||||
|
||||
/**
|
||||
* 权限ID
|
||||
*/
|
||||
private Long permissionId;
|
||||
|
||||
/**
|
||||
* 权限码
|
||||
*/
|
||||
@@ -54,4 +54,9 @@ public class MenuPermissionVO {
|
||||
* 创建时间
|
||||
*/
|
||||
private LocalDateTime createTime;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建人ID
|
||||
*/
|
||||
private Long createBy;
|
||||
}
|
||||
+6
-1
@@ -99,4 +99,9 @@ public class MenuVO {
|
||||
* 子菜单列表
|
||||
*/
|
||||
private List<MenuVO> children;
|
||||
}
|
||||
|
||||
/**
|
||||
* 权限列表
|
||||
*/
|
||||
private List<PermissionVO> permissions;
|
||||
}
|
||||
+11
-42
@@ -1,60 +1,29 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.sys.service;
|
||||
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.model.dto.menu.BatchAssignMenuPermissionDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.model.dto.menu_permission.AddMenuPermissionDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.model.dto.menu_permission.RemoveMenuPermissionDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.model.vo.MenuPermissionVO;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 菜单权限关联服务接口
|
||||
* 菜单权限映射服务接口
|
||||
*/
|
||||
public interface MenuPermissionService {
|
||||
|
||||
/**
|
||||
* 批量分配菜单权限
|
||||
* 添加菜单权限映射
|
||||
*
|
||||
* @param batchAssignDTO 批量分配DTO
|
||||
* @param addMenuPermissionDTO 添加菜单权限映射DTO
|
||||
* @return 菜单权限映射VO
|
||||
*/
|
||||
void batchAssignMenuPermissions(BatchAssignMenuPermissionDTO batchAssignDTO);
|
||||
MenuPermissionVO addMenuPermission(AddMenuPermissionDTO addMenuPermissionDTO);
|
||||
|
||||
/**
|
||||
* 取消菜单权限
|
||||
* 删除菜单权限映射
|
||||
*
|
||||
* @param menuId 菜单ID
|
||||
* @param permissionId 权限ID
|
||||
* @param removeMenuPermissionDTO 删除菜单权限映射DTO
|
||||
*/
|
||||
void removeMenuPermission(Long menuId, Long permissionId);
|
||||
void removeMenuPermission(RemoveMenuPermissionDTO removeMenuPermissionDTO);
|
||||
|
||||
/**
|
||||
* 根据菜单ID查询权限列表
|
||||
*
|
||||
* @param menuId 菜单ID
|
||||
* @return 权限列表
|
||||
*/
|
||||
List<MenuPermissionVO> getPermissionsByMenuId(Long menuId);
|
||||
|
||||
/**
|
||||
* 根据菜单ID列表查询权限列表
|
||||
*
|
||||
* @param menuIds 菜单ID列表
|
||||
* @return 权限列表
|
||||
*/
|
||||
List<MenuPermissionVO> getPermissionsByMenuIds(List<Long> menuIds);
|
||||
|
||||
/**
|
||||
* 根据权限ID查询菜单列表
|
||||
*
|
||||
* @param permissionId 权限ID
|
||||
* @return 菜单列表
|
||||
*/
|
||||
List<MenuPermissionVO> getMenusByPermissionId(Long permissionId);
|
||||
|
||||
/**
|
||||
* 检查菜单是否有指定权限
|
||||
*
|
||||
* @param menuId 菜单ID
|
||||
* @param permissionId 权限ID
|
||||
* @return 是否有权限
|
||||
*/
|
||||
boolean hasMenuPermission(Long menuId, Long permissionId);
|
||||
}
|
||||
}
|
||||
+4
-4
@@ -1,6 +1,7 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.sys.service;
|
||||
|
||||
import com.baomidou.mybatisplus.extension.service.IService;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.model.dto.menu.BatchSortMenuDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.model.dto.menu.CreateMenuDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.model.dto.menu.UpdateMenuDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.model.po.MenuPO;
|
||||
@@ -59,10 +60,9 @@ public interface MenuService extends IService<MenuPO> {
|
||||
MenuVO getMenuDetail(Long id);
|
||||
|
||||
/**
|
||||
* 根据用户角色获取菜单树
|
||||
* 批量菜单排序
|
||||
*
|
||||
* @param userRole 用户角色
|
||||
* @return 菜单树列表
|
||||
* @param batchSortMenuDTO 批量排序信息
|
||||
*/
|
||||
List<MenuVO> getMenuTreeByRole(String userRole);
|
||||
void batchSortMenu(BatchSortMenuDTO batchSortMenuDTO);
|
||||
}
|
||||
|
||||
+57
-66
@@ -1,96 +1,87 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.sys.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.mapper.MenuPermissionMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.model.dto.menu.BatchAssignMenuPermissionDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.model.dto.menu_permission.AddMenuPermissionDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.model.dto.menu_permission.RemoveMenuPermissionDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.model.po.MenuPermissionPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.model.vo.MenuPermissionVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.service.MenuPermissionService;
|
||||
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 菜单权限关联服务实现类
|
||||
* 菜单权限映射服务实现类
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class MenuPermissionServiceImpl implements MenuPermissionService {
|
||||
|
||||
private final MenuPermissionMapper menuPermissionMapper;
|
||||
private final CurrentUserContext currentUserContext;
|
||||
|
||||
public MenuPermissionServiceImpl(MenuPermissionMapper menuPermissionMapper,
|
||||
CurrentUserContext currentUserContext) {
|
||||
this.menuPermissionMapper = menuPermissionMapper;
|
||||
this.currentUserContext = currentUserContext;
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public MenuPermissionVO addMenuPermission(AddMenuPermissionDTO addMenuPermissionDTO) {
|
||||
log.info("添加菜单权限映射,菜单ID:{},权限ID:{}", addMenuPermissionDTO.getMenuId(), addMenuPermissionDTO.getPermissionId());
|
||||
|
||||
// 检查映射是否已存在
|
||||
LambdaQueryWrapper<MenuPermissionPO> queryWrapper = new LambdaQueryWrapper<>();
|
||||
queryWrapper.eq(MenuPermissionPO::getMenuId, addMenuPermissionDTO.getMenuId())
|
||||
.eq(MenuPermissionPO::getPermissionId, addMenuPermissionDTO.getPermissionId());
|
||||
|
||||
MenuPermissionPO existingMapping = menuPermissionMapper.selectOne(queryWrapper);
|
||||
if (existingMapping != null) {
|
||||
throw new BusinessException("菜单权限映射已存在");
|
||||
}
|
||||
|
||||
// 创建新的映射
|
||||
MenuPermissionPO menuPermissionPO = new MenuPermissionPO();
|
||||
menuPermissionPO.setMenuId(addMenuPermissionDTO.getMenuId());
|
||||
menuPermissionPO.setPermissionId(addMenuPermissionDTO.getPermissionId());
|
||||
|
||||
int result = menuPermissionMapper.insert(menuPermissionPO);
|
||||
if (result <= 0) {
|
||||
throw new BusinessException("添加菜单权限映射失败");
|
||||
}
|
||||
|
||||
log.info("菜单权限映射添加成功,映射ID:{}", menuPermissionPO.getId());
|
||||
|
||||
// 查询并返回完整的映射信息
|
||||
List<MenuPermissionVO> permissions = menuPermissionMapper.selectPermissionsByMenuId(addMenuPermissionDTO.getMenuId());
|
||||
return permissions.stream()
|
||||
.filter(permission -> permission.getPermissionId().equals(addMenuPermissionDTO.getPermissionId()))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new BusinessException("查询菜单权限映射失败"));
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void batchAssignMenuPermissions(BatchAssignMenuPermissionDTO batchAssignDTO) {
|
||||
Long menuId = batchAssignDTO.getMenuId();
|
||||
List<Long> permissionIds = batchAssignDTO.getPermissionIds();
|
||||
public void removeMenuPermission(RemoveMenuPermissionDTO removeMenuPermissionDTO) {
|
||||
log.info("删除菜单权限映射,菜单ID:{},权限ID:{}", removeMenuPermissionDTO.getMenuId(), removeMenuPermissionDTO.getPermissionId());
|
||||
|
||||
// 先删除该菜单的所有权限
|
||||
LambdaQueryWrapper<MenuPermissionPO> deleteWrapper = new LambdaQueryWrapper<>();
|
||||
deleteWrapper.eq(MenuPermissionPO::getMenuId, menuId);
|
||||
menuPermissionMapper.delete(deleteWrapper);
|
||||
|
||||
// 批量插入新的权限
|
||||
List<MenuPermissionPO> menuPermissions = new ArrayList<>();
|
||||
for (Long permissionId : permissionIds) {
|
||||
MenuPermissionPO menuPermission = new MenuPermissionPO();
|
||||
menuPermission.setMenuId(menuId);
|
||||
menuPermission.setPermissionId(permissionId);
|
||||
menuPermission.setCreateBy(currentUserContext.getCurrentUserId());
|
||||
menuPermissions.add(menuPermission);
|
||||
// 查询映射是否存在
|
||||
LambdaQueryWrapper<MenuPermissionPO> queryWrapper = new LambdaQueryWrapper<>();
|
||||
queryWrapper.eq(MenuPermissionPO::getMenuId, removeMenuPermissionDTO.getMenuId())
|
||||
.eq(MenuPermissionPO::getPermissionId, removeMenuPermissionDTO.getPermissionId());
|
||||
|
||||
MenuPermissionPO existingMapping = menuPermissionMapper.selectOne(queryWrapper);
|
||||
if (existingMapping == null) {
|
||||
throw new BusinessException("菜单权限映射不存在");
|
||||
}
|
||||
|
||||
if (!menuPermissions.isEmpty()) {
|
||||
menuPermissions.forEach(menuPermissionMapper::insert);
|
||||
// 删除映射
|
||||
int result = menuPermissionMapper.deleteById(existingMapping.getId());
|
||||
if (result <= 0) {
|
||||
throw new BusinessException("删除菜单权限映射失败");
|
||||
}
|
||||
|
||||
log.info("菜单权限映射删除成功,映射ID:{}", existingMapping.getId());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeMenuPermission(Long menuId, Long permissionId) {
|
||||
LambdaQueryWrapper<MenuPermissionPO> wrapper = new LambdaQueryWrapper<>();
|
||||
wrapper.eq(MenuPermissionPO::getMenuId, menuId)
|
||||
.eq(MenuPermissionPO::getPermissionId, permissionId);
|
||||
|
||||
int result = menuPermissionMapper.delete(wrapper);
|
||||
if (result == 0) {
|
||||
throw new BusinessException("菜单权限关联不存在");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<MenuPermissionVO> getPermissionsByMenuId(Long menuId) {
|
||||
return menuPermissionMapper.selectPermissionsByMenuId(menuId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<MenuPermissionVO> getPermissionsByMenuIds(List<Long> menuIds) {
|
||||
if (menuIds == null || menuIds.isEmpty()) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
return menuPermissionMapper.selectPermissionsByMenuIds(menuIds);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<MenuPermissionVO> getMenusByPermissionId(Long permissionId) {
|
||||
return menuPermissionMapper.selectMenusByPermissionId(permissionId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasMenuPermission(Long menuId, Long permissionId) {
|
||||
LambdaQueryWrapper<MenuPermissionPO> wrapper = new LambdaQueryWrapper<>();
|
||||
wrapper.eq(MenuPermissionPO::getMenuId, menuId)
|
||||
.eq(MenuPermissionPO::getPermissionId, permissionId);
|
||||
|
||||
return menuPermissionMapper.selectCount(wrapper) > 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
+23
-17
@@ -2,14 +2,18 @@ package top.xyquan.ecomdmbbackend.modules.sys.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.BeanUtils;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.mapper.MenuMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.model.dto.menu.BatchSortMenuDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.model.dto.menu.CreateMenuDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.model.dto.menu.UpdateMenuDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.model.po.MenuPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.model.vo.MenuVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.model.vo.PermissionVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.service.MenuService;
|
||||
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
|
||||
|
||||
@@ -21,6 +25,7 @@ import java.util.stream.Collectors;
|
||||
/**
|
||||
* 系统菜单服务实现类
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
public class MenuServiceImpl extends ServiceImpl<MenuMapper, MenuPO> implements MenuService {
|
||||
|
||||
@@ -180,26 +185,22 @@ public class MenuServiceImpl extends ServiceImpl<MenuMapper, MenuPO> implements
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<MenuVO> getMenuTreeByRole(String userRole) {
|
||||
// 查询所有菜单
|
||||
LambdaQueryWrapper<MenuPO> wrapper = new LambdaQueryWrapper<>();
|
||||
wrapper.orderByAsc(MenuPO::getOrder);
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void batchSortMenu(BatchSortMenuDTO batchSortMenuDTO) {
|
||||
log.info("批量菜单排序,排序项数量:{}", batchSortMenuDTO.getSortItems().size());
|
||||
|
||||
// 根据用户角色过滤菜单
|
||||
if (!"super".equals(userRole)) {
|
||||
// 非超级管理员只能看到非超级菜单
|
||||
wrapper.eq(MenuPO::getSuperMenu, 0);
|
||||
// 批量更新菜单排序
|
||||
for (BatchSortMenuDTO.MenuSortItem sortItem : batchSortMenuDTO.getSortItems()) {
|
||||
MenuPO menuPO = this.getById(sortItem.getMenuId());
|
||||
if (menuPO == null) {
|
||||
throw new BusinessException("菜单不存在,ID:" + sortItem.getMenuId());
|
||||
}
|
||||
|
||||
menuPO.setOrder(sortItem.getOrder());
|
||||
this.updateById(menuPO);
|
||||
}
|
||||
|
||||
List<MenuPO> menuList = this.list(wrapper);
|
||||
|
||||
// 转换为VO
|
||||
List<MenuVO> menuVOList = menuList.stream()
|
||||
.map(this::convertToVO)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
// 构建树形结构
|
||||
return buildMenuTree(menuVOList);
|
||||
log.info("批量菜单排序完成");
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -253,6 +254,11 @@ public class MenuServiceImpl extends ServiceImpl<MenuMapper, MenuPO> implements
|
||||
private MenuVO convertToVO(MenuPO menu) {
|
||||
MenuVO menuVO = new MenuVO();
|
||||
BeanUtils.copyProperties(menu, menuVO);
|
||||
|
||||
// 查询菜单关联的权限
|
||||
List<PermissionVO> permissions = baseMapper.selectPermissionsByMenuId(menu.getId());
|
||||
menuVO.setPermissions(permissions);
|
||||
|
||||
return menuVO;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
||||
<mapper namespace="top.xyquan.ecomdmbbackend.modules.sys.mapper.MenuMapper">
|
||||
|
||||
<!-- 权限结果映射 -->
|
||||
<resultMap id="PermissionResultMap" type="top.xyquan.ecomdmbbackend.modules.sys.model.vo.PermissionVO">
|
||||
<id column="id" property="id"/>
|
||||
<result column="code" property="code"/>
|
||||
<result column="name" property="name"/>
|
||||
<result column="type" property="type"/>
|
||||
<result column="status" property="status"/>
|
||||
<result column="remark" property="remark"/>
|
||||
<result column="create_time" property="createTime"/>
|
||||
<result column="update_time" property="updateTime"/>
|
||||
</resultMap>
|
||||
|
||||
<!-- 根据菜单ID查询权限列表 -->
|
||||
<select id="selectPermissionsByMenuId" resultMap="PermissionResultMap">
|
||||
SELECT
|
||||
p.id,
|
||||
p.code,
|
||||
p.name,
|
||||
p.type,
|
||||
p.status,
|
||||
p.remark,
|
||||
p.create_time,
|
||||
p.update_time
|
||||
FROM sys_permission p
|
||||
INNER JOIN sys_menu_permission_map mpm ON p.id = mpm.permission_id
|
||||
WHERE mpm.menu_id = #{menuId}
|
||||
AND p.status = 1
|
||||
ORDER BY p.create_time ASC
|
||||
</select>
|
||||
|
||||
</mapper>
|
||||
@@ -27,7 +27,7 @@
|
||||
p.name as permission_name,
|
||||
p.type as permission_type,
|
||||
rmp.create_time
|
||||
FROM rel_menu_permission rmp
|
||||
FROM sys_menu_permission_map rmp
|
||||
LEFT JOIN sys_menu m ON rmp.menu_id = m.id
|
||||
LEFT JOIN sys_permission p ON rmp.permission_id = p.id
|
||||
WHERE rmp.menu_id = #{menuId}
|
||||
@@ -46,7 +46,7 @@
|
||||
p.name as permission_name,
|
||||
p.type as permission_type,
|
||||
rmp.create_time
|
||||
FROM rel_menu_permission rmp
|
||||
FROM sys_menu_permission_map rmp
|
||||
LEFT JOIN sys_menu m ON rmp.menu_id = m.id
|
||||
LEFT JOIN sys_permission p ON rmp.permission_id = p.id
|
||||
WHERE rmp.menu_id IN
|
||||
@@ -68,7 +68,7 @@
|
||||
p.name as permission_name,
|
||||
p.type as permission_type,
|
||||
rmp.create_time
|
||||
FROM rel_menu_permission rmp
|
||||
FROM sys_menu_permission_map rmp
|
||||
LEFT JOIN sys_menu m ON rmp.menu_id = m.id
|
||||
LEFT JOIN sys_permission p ON rmp.permission_id = p.id
|
||||
WHERE rmp.permission_id = #{permissionId}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
export * from './auth';
|
||||
export * from './menu';
|
||||
export * from './organization';
|
||||
export * from './user';
|
||||
|
||||
@@ -1,100 +0,0 @@
|
||||
import { requestClient } from '#/api/request';
|
||||
|
||||
export namespace MenuApi {
|
||||
/** 菜单信息 */
|
||||
export interface MenuInfo {
|
||||
id: number;
|
||||
parentId?: number;
|
||||
superMenu?: number;
|
||||
name: string;
|
||||
title?: string;
|
||||
path?: string;
|
||||
component?: string;
|
||||
redirect?: string;
|
||||
icon?: string;
|
||||
order?: number;
|
||||
type: string;
|
||||
visible?: number;
|
||||
status?: number;
|
||||
keepAlive?: number;
|
||||
createTime: string;
|
||||
updateTime: string;
|
||||
children?: MenuInfo[];
|
||||
}
|
||||
|
||||
/** 创建菜单参数 */
|
||||
export interface CreateMenuParams {
|
||||
parentId?: number;
|
||||
superMenu?: number;
|
||||
name: string;
|
||||
title?: string;
|
||||
path?: string;
|
||||
component?: string;
|
||||
redirect?: string;
|
||||
icon?: string;
|
||||
order?: number;
|
||||
type: string;
|
||||
visible?: number;
|
||||
status?: number;
|
||||
keepAlive?: number;
|
||||
}
|
||||
|
||||
/** 更新菜单参数 */
|
||||
export interface UpdateMenuParams {
|
||||
parentId?: number;
|
||||
superMenu?: number;
|
||||
name: string;
|
||||
title?: string;
|
||||
path?: string;
|
||||
component?: string;
|
||||
redirect?: string;
|
||||
icon?: string;
|
||||
order?: number;
|
||||
type: string;
|
||||
visible?: number;
|
||||
status?: number;
|
||||
keepAlive?: number;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取菜单树
|
||||
*/
|
||||
export async function getMenuTreeApi() {
|
||||
return requestClient.get<MenuApi.MenuInfo[]>('/menu/tree');
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取所有菜单
|
||||
*/
|
||||
export async function getAllMenusApi() {
|
||||
return requestClient.get<MenuApi.MenuInfo[]>('/menu/list');
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取菜单详情
|
||||
*/
|
||||
export async function getMenuDetailApi(id: number) {
|
||||
return requestClient.get<MenuApi.MenuInfo>(`/menu/detail/${id}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建菜单
|
||||
*/
|
||||
export async function createMenuApi(data: MenuApi.CreateMenuParams) {
|
||||
return requestClient.post<MenuApi.MenuInfo>('/menu/create', data);
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新菜单
|
||||
*/
|
||||
export async function updateMenuApi(id: number, data: MenuApi.UpdateMenuParams) {
|
||||
return requestClient.put<MenuApi.MenuInfo>(`/menu/update/${id}`, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除菜单
|
||||
*/
|
||||
export async function deleteMenuApi(id: number) {
|
||||
return requestClient.delete<void>(`/menu/delete/${id}`);
|
||||
}
|
||||
+12
-5
@@ -10,35 +10,35 @@ import type { MenuDTO, MenuVO } from './types';
|
||||
* 获取菜单树
|
||||
*/
|
||||
export async function getMenuTreeApi() {
|
||||
return requestClient.get<MenuVO.MenuInfoVO[]>('/menu/tree');
|
||||
return requestClient.get<MenuVO.MenuInfo[]>('/menu/tree');
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取所有菜单
|
||||
*/
|
||||
export async function getAllMenusApi() {
|
||||
return requestClient.get<MenuVO.MenuInfoVO[]>('/menu/list');
|
||||
return requestClient.get<MenuVO.MenuInfo[]>('/menu/list');
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取菜单详情
|
||||
*/
|
||||
export async function getMenuDetailApi(id: number) {
|
||||
return requestClient.get<MenuVO.MenuInfoVO>(`/menu/detail/${id}`);
|
||||
return requestClient.get<MenuVO.MenuInfo>(`/menu/detail/${id}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建菜单
|
||||
*/
|
||||
export async function createMenuApi(data: MenuDTO.CreateMenuDTO) {
|
||||
return requestClient.post<MenuVO.MenuInfoVO>('/menu/create', data);
|
||||
return requestClient.post<MenuVO.MenuInfo>('/menu/create', data);
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新菜单
|
||||
*/
|
||||
export async function updateMenuApi(id: number, data: MenuDTO.UpdateMenuDTO) {
|
||||
return requestClient.put<MenuVO.MenuInfoVO>(`/menu/update/${id}`, data);
|
||||
return requestClient.put<MenuVO.MenuInfo>(`/menu/update/${id}`, data);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -47,3 +47,10 @@ export async function updateMenuApi(id: number, data: MenuDTO.UpdateMenuDTO) {
|
||||
export async function deleteMenuApi(id: number) {
|
||||
return requestClient.delete<void>(`/menu/delete/${id}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量菜单排序
|
||||
*/
|
||||
export async function batchSortMenuApi(data: MenuDTO.BatchSortMenuDTO) {
|
||||
return requestClient.post<void>('/menu/batch-sort', data);
|
||||
}
|
||||
@@ -2,5 +2,5 @@
|
||||
* 菜单模块API导出
|
||||
*/
|
||||
|
||||
export * from './menu';
|
||||
export * from './apis';
|
||||
export * from './types';
|
||||
|
||||
@@ -62,4 +62,18 @@ export namespace MenuDTO {
|
||||
/** 是否缓存 */
|
||||
keepAlive?: number;
|
||||
}
|
||||
|
||||
/** 批量菜单排序参数 */
|
||||
export interface BatchSortMenuDTO {
|
||||
/** 菜单排序项列表 */
|
||||
sortItems: MenuSortItem[];
|
||||
}
|
||||
|
||||
/** 菜单排序项 */
|
||||
export interface MenuSortItem {
|
||||
/** 菜单ID */
|
||||
menuId: number;
|
||||
/** 排序值 */
|
||||
order: number;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
/**
|
||||
* 菜单模块VO类型定义
|
||||
*/
|
||||
import type { PermissionVO } from '#/api/system/permission/types';
|
||||
|
||||
export namespace MenuVO {
|
||||
/** 菜单信息 */
|
||||
export interface MenuInfoVO {
|
||||
export interface MenuInfo {
|
||||
/** 主键ID */
|
||||
id: number;
|
||||
/** 父级菜单ID */
|
||||
@@ -38,6 +39,8 @@ export namespace MenuVO {
|
||||
/** 更新时间 */
|
||||
updateTime: string;
|
||||
/** 子菜单列表 */
|
||||
children?: MenuInfoVO[];
|
||||
children?: MenuInfo[];
|
||||
/** 权限列表 */
|
||||
permissions?: PermissionVO.PermissionInfoVO[];
|
||||
}
|
||||
}
|
||||
|
||||
+121
-12
@@ -8,8 +8,15 @@ import {
|
||||
createMenuApi,
|
||||
updateMenuApi,
|
||||
getAllMenusApi,
|
||||
type MenuApi as MenuApiType
|
||||
} from '#/api/core/menu'
|
||||
} from '#/api/system/menu'
|
||||
import type { MenuVO } from '#/api/system/menu/types'
|
||||
import {
|
||||
addMenuPermissionApi,
|
||||
removeMenuPermissionApi
|
||||
} from '#/api/system/menu-permission'
|
||||
import {
|
||||
getAllPermissionsApi
|
||||
} from '#/api/system/permission'
|
||||
|
||||
const emit = defineEmits<{
|
||||
success: [];
|
||||
@@ -26,13 +33,14 @@ const [Modal, modalApi] = useVbenModal({
|
||||
onOpenChange: (isOpen: boolean) => {
|
||||
if (isOpen) {
|
||||
fetchParentMenuOptions();
|
||||
fetchPermissionOptions();
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
// 响应式数据
|
||||
const isEdit = ref(false);
|
||||
const currentRecord = ref<MenuApiType.MenuInfo | null>(null);
|
||||
const currentRecord = ref<MenuVO.MenuInfo | null>(null);
|
||||
const formRef = ref();
|
||||
|
||||
// 内部表单数据类型
|
||||
@@ -71,6 +79,9 @@ const formData = ref<FormData>({
|
||||
|
||||
// 下拉选项数据
|
||||
const parentMenuOptions = ref<{ label: string; value: number }[]>([]);
|
||||
const permissionOptions = ref<{ label: string; value: number }[]>([]);
|
||||
const selectedPermissions = ref<number[]>([]);
|
||||
const originalPermissions = ref<number[]>([]);
|
||||
|
||||
// 创建图标组件
|
||||
const GridIcon = createIconifyIcon('lucide:grid-3x3');
|
||||
@@ -89,7 +100,7 @@ async function fetchParentMenuOptions() {
|
||||
const data = await getAllMenusApi();
|
||||
const options: Array<{ label: string; value: number }> = [];
|
||||
|
||||
const addMenuOptions = (menus: MenuApiType.MenuInfo[], level = 0) => {
|
||||
const addMenuOptions = (menus: MenuVO.MenuInfo[], level = 0) => {
|
||||
menus.forEach(menu => {
|
||||
const prefix = ' '.repeat(level);
|
||||
options.push({
|
||||
@@ -109,8 +120,22 @@ async function fetchParentMenuOptions() {
|
||||
}
|
||||
}
|
||||
|
||||
// 获取权限选项
|
||||
async function fetchPermissionOptions() {
|
||||
try {
|
||||
const data = await getAllPermissionsApi();
|
||||
const options = data.map(permission => ({
|
||||
label: permission.name,
|
||||
value: permission.id,
|
||||
}));
|
||||
permissionOptions.value = options;
|
||||
} catch (error) {
|
||||
console.error('获取权限列表失败:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// 打开模态框
|
||||
function open(edit: boolean, record?: MenuApiType.MenuInfo) {
|
||||
function open(edit: boolean, record?: MenuVO.MenuInfo) {
|
||||
isEdit.value = edit;
|
||||
currentRecord.value = record || null;
|
||||
|
||||
@@ -138,6 +163,15 @@ function open(edit: boolean, record?: MenuApiType.MenuInfo) {
|
||||
status: record.status === 1, // 转换为boolean
|
||||
keepAlive: record.keepAlive === 1, // 转换为boolean
|
||||
};
|
||||
|
||||
// 设置权限数据
|
||||
if ((record as any).permissions && (record as any).permissions.length > 0) {
|
||||
selectedPermissions.value = (record as any).permissions.map((p: any) => p.id);
|
||||
originalPermissions.value = [...selectedPermissions.value];
|
||||
} else {
|
||||
selectedPermissions.value = [];
|
||||
originalPermissions.value = [];
|
||||
}
|
||||
} else if (!edit && record) {
|
||||
// 添加下级菜单模式,自动选中父菜单
|
||||
formData.value = {
|
||||
@@ -172,6 +206,10 @@ function open(edit: boolean, record?: MenuApiType.MenuInfo) {
|
||||
status: true,
|
||||
keepAlive: false,
|
||||
};
|
||||
|
||||
// 重置权限数据
|
||||
selectedPermissions.value = [];
|
||||
originalPermissions.value = [];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -179,9 +217,54 @@ function open(edit: boolean, record?: MenuApiType.MenuInfo) {
|
||||
function close() {
|
||||
modalApi.close();
|
||||
formRef.value?.resetFields();
|
||||
selectedPermissions.value = [];
|
||||
originalPermissions.value = [];
|
||||
emit('cancel');
|
||||
}
|
||||
|
||||
// 处理权限变更
|
||||
async function handlePermissionChange() {
|
||||
if (!currentRecord.value) return;
|
||||
|
||||
const menuId = currentRecord.value.id;
|
||||
const currentPermissions = selectedPermissions.value;
|
||||
const originalPermissionsList = originalPermissions.value;
|
||||
|
||||
// 找出新增的权限
|
||||
const addedPermissions = currentPermissions.filter(id => !originalPermissionsList.includes(id));
|
||||
|
||||
// 找出移除的权限
|
||||
const removedPermissions = originalPermissionsList.filter(id => !currentPermissions.includes(id));
|
||||
|
||||
try {
|
||||
// 添加新权限
|
||||
for (const permissionId of addedPermissions) {
|
||||
await addMenuPermissionApi({
|
||||
menuId,
|
||||
permissionId
|
||||
});
|
||||
}
|
||||
|
||||
// 移除权限
|
||||
for (const permissionId of removedPermissions) {
|
||||
await removeMenuPermissionApi({
|
||||
menuId,
|
||||
permissionId
|
||||
});
|
||||
}
|
||||
|
||||
// 更新原始权限列表
|
||||
originalPermissions.value = [...currentPermissions];
|
||||
|
||||
if (addedPermissions.length > 0 || removedPermissions.length > 0) {
|
||||
message.success('权限更新成功');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('权限更新失败:', error);
|
||||
message.error('权限更新失败');
|
||||
}
|
||||
}
|
||||
|
||||
// 提交表单
|
||||
async function handleSubmit() {
|
||||
try {
|
||||
@@ -203,10 +286,24 @@ async function handleSubmit() {
|
||||
// 更新菜单
|
||||
await updateMenuApi(currentRecord.value.id, submitData);
|
||||
message.success('更新菜单成功');
|
||||
|
||||
// 处理权限变更
|
||||
await handlePermissionChange();
|
||||
} else {
|
||||
// 创建菜单
|
||||
await createMenuApi(submitData);
|
||||
const newMenu = await createMenuApi(submitData);
|
||||
message.success('创建菜单成功');
|
||||
|
||||
// 如果有选择的权限,为新菜单添加权限
|
||||
if (selectedPermissions.value.length > 0 && newMenu?.id) {
|
||||
for (const permissionId of selectedPermissions.value) {
|
||||
await addMenuPermissionApi({
|
||||
menuId: newMenu.id,
|
||||
permissionId
|
||||
});
|
||||
}
|
||||
message.success('权限分配成功');
|
||||
}
|
||||
}
|
||||
|
||||
close();
|
||||
@@ -256,12 +353,15 @@ defineExpose({
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item label="超级菜单" name="superMenu">
|
||||
<Switch
|
||||
v-model:checked="formData.superMenu"
|
||||
checked-children="是"
|
||||
un-checked-children="否"
|
||||
class="w-12"
|
||||
<Form.Item label="权限列表" name="permissions">
|
||||
<Select
|
||||
v-model:value="selectedPermissions"
|
||||
mode="multiple"
|
||||
placeholder="请选择权限"
|
||||
:options="permissionOptions"
|
||||
class="w-full"
|
||||
:max-tag-count="3"
|
||||
:max-tag-text-length="10"
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
@@ -337,6 +437,15 @@ defineExpose({
|
||||
class="w-12"
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item label="超级菜单" name="superMenu">
|
||||
<Switch
|
||||
v-model:checked="formData.superMenu"
|
||||
checked-children="是"
|
||||
un-checked-children="否"
|
||||
class="w-12"
|
||||
/>
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
</template>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script lang="ts" setup>
|
||||
import { ref } from 'vue';
|
||||
import { ref, onMounted } from 'vue';
|
||||
|
||||
import { Page } from '@vben/common-ui';
|
||||
import { Button, message, Space, Tag } from 'ant-design-vue';
|
||||
@@ -10,9 +10,9 @@ import type { VxeGridProps } from '#/adapter/vxe-table';
|
||||
import {
|
||||
deleteMenuApi,
|
||||
getAllMenusApi,
|
||||
type MenuApi as MenuApiType
|
||||
} from '#/api/core/menu';
|
||||
|
||||
batchSortMenuApi,
|
||||
} from '#/api/system/menu';
|
||||
import type { MenuVO } from '#/api/system/menu/types';
|
||||
import MenuFormModal from './components/MenuFormModal.vue';
|
||||
|
||||
// 创建图标组件
|
||||
@@ -45,7 +45,8 @@ const gridOptions: VxeGridProps<any> = {
|
||||
minWidth: 200,
|
||||
showOverflow: 'tooltip' as const,
|
||||
treeNode: true, // 启用树节点显示
|
||||
slots: { default: 'menuName' },
|
||||
dragSort: true, // 启用拖拽排序
|
||||
// 移除自定义插槽,让拖拽控件正常显示
|
||||
},
|
||||
{
|
||||
field: 'title',
|
||||
@@ -65,16 +66,16 @@ const gridOptions: VxeGridProps<any> = {
|
||||
minWidth: 180,
|
||||
showOverflow: 'tooltip' as const,
|
||||
},
|
||||
{
|
||||
title: '权限列表',
|
||||
minWidth: 200,
|
||||
slots: { default: 'permissions' },
|
||||
},
|
||||
{
|
||||
title: '类型',
|
||||
minWidth: 100,
|
||||
slots: { default: 'menuType' },
|
||||
},
|
||||
{
|
||||
field: 'order',
|
||||
title: '排序',
|
||||
minWidth: 80,
|
||||
},
|
||||
{
|
||||
title: '状态',
|
||||
minWidth: 100,
|
||||
@@ -99,7 +100,13 @@ const gridOptions: VxeGridProps<any> = {
|
||||
size: 'small',
|
||||
resizable: true, // 启用列宽调整
|
||||
rowConfig: {
|
||||
isHover: true, // 启用行悬停高亮
|
||||
drag: true, // 启用行拖拽
|
||||
},
|
||||
rowDragConfig: {
|
||||
isPeerDrag: true, // 启用同层级拖拽限制
|
||||
},
|
||||
columnConfig: {
|
||||
// 列配置
|
||||
},
|
||||
toolbarConfig: {
|
||||
custom: true,
|
||||
@@ -109,13 +116,9 @@ const gridOptions: VxeGridProps<any> = {
|
||||
},
|
||||
data: [],
|
||||
treeConfig: {
|
||||
children: 'children',
|
||||
hasChild: 'hasChildren',
|
||||
expandAll: true, // 自动展开所有节点
|
||||
indent: 20, // 树节点缩进距离
|
||||
showIcon: true, // 显示展开/收起图标
|
||||
iconOpen: 'vxe-icon-arrow-down', // 展开图标
|
||||
iconClose: 'vxe-icon-arrow-right', // 收起图标
|
||||
transform: true,
|
||||
rowField: 'id',
|
||||
parentField: 'parentId',
|
||||
},
|
||||
// 配置远程加载
|
||||
proxyConfig: {
|
||||
@@ -124,11 +127,10 @@ const gridOptions: VxeGridProps<any> = {
|
||||
try {
|
||||
loading.value = true;
|
||||
const data = await getAllMenusApi();
|
||||
// 构建树形结构数据
|
||||
const treeData = buildTreeData(data);
|
||||
// 直接返回扁平化数据,让 vxe-table 自动构建树形结构
|
||||
return {
|
||||
items: treeData,
|
||||
total: treeData.length,
|
||||
items: data,
|
||||
total: data.length,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('获取菜单列表失败:', error);
|
||||
@@ -159,17 +161,17 @@ function handleAdd() {
|
||||
}
|
||||
|
||||
// 处理添加下级菜单
|
||||
function handleAddChild(record: MenuApiType.MenuInfo) {
|
||||
function handleAddChild(record: MenuVO.MenuInfo) {
|
||||
menuFormModalRef.value?.open(false, record);
|
||||
}
|
||||
|
||||
// 处理编辑菜单
|
||||
function handleEdit(record: MenuApiType.MenuInfo) {
|
||||
function handleEdit(record: MenuVO.MenuInfo) {
|
||||
menuFormModalRef.value?.open(true, record);
|
||||
}
|
||||
|
||||
// 处理删除菜单
|
||||
async function handleDelete(record: MenuApiType.MenuInfo) {
|
||||
async function handleDelete(record: MenuVO.MenuInfo) {
|
||||
try {
|
||||
await deleteMenuApi(record.id);
|
||||
message.success('删除成功');
|
||||
@@ -185,6 +187,47 @@ function handleModalSuccess() {
|
||||
refreshTable();
|
||||
}
|
||||
|
||||
// 防重复调用标志
|
||||
let isUpdating = false;
|
||||
|
||||
// 处理拖拽排序
|
||||
const handleDragSort = async (_params: any) => {
|
||||
// 防止重复调用
|
||||
if (isUpdating) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
isUpdating = true;
|
||||
|
||||
// 获取当前表格数据
|
||||
const tableDataResult = gridApi.grid.getTableData();
|
||||
const tableData = tableDataResult?.tableData || [];
|
||||
|
||||
// 构建排序数据
|
||||
const sortItems = tableData.map((item: MenuVO.MenuInfo, index: number) => ({
|
||||
menuId: item.id,
|
||||
order: index + 1, // 排序值从1开始
|
||||
}));
|
||||
|
||||
// 调用排序接口
|
||||
await batchSortMenuApi({ sortItems });
|
||||
|
||||
// 排序成功后不需要重新加载数据,因为表格数据已经更新
|
||||
} catch (error: any) {
|
||||
console.error('拖拽排序失败:', error);
|
||||
if (error?.message) {
|
||||
message.error(error.message);
|
||||
} else {
|
||||
message.error('排序更新失败');
|
||||
}
|
||||
// 排序失败时重新加载数据,恢复原始状态
|
||||
gridApi.reload();
|
||||
} finally {
|
||||
isUpdating = false;
|
||||
}
|
||||
};
|
||||
|
||||
// 全部展开树形表格
|
||||
function expandAllTree() {
|
||||
if (gridApi) {
|
||||
@@ -229,35 +272,9 @@ function getMenuTypeColor(type: string) {
|
||||
return colorMap[type] || 'default';
|
||||
}
|
||||
|
||||
// 构建树形结构数据
|
||||
function buildTreeData(menuList: MenuApiType.MenuInfo[]): MenuApiType.MenuInfo[] {
|
||||
const menuMap = new Map<number, MenuApiType.MenuInfo>();
|
||||
const rootMenus: MenuApiType.MenuInfo[] = [];
|
||||
|
||||
// 创建菜单映射
|
||||
menuList.forEach(menu => {
|
||||
menuMap.set(menu.id, { ...menu, children: [] });
|
||||
});
|
||||
|
||||
// 构建树形结构
|
||||
menuList.forEach(menu => {
|
||||
const menuItem = menuMap.get(menu.id)!;
|
||||
if (menu.parentId && menu.parentId !== 0) {
|
||||
const parent = menuMap.get(menu.parentId);
|
||||
if (parent) {
|
||||
parent.children = parent.children || [];
|
||||
parent.children.push(menuItem);
|
||||
}
|
||||
} else {
|
||||
rootMenus.push(menuItem);
|
||||
}
|
||||
});
|
||||
|
||||
return rootMenus;
|
||||
}
|
||||
|
||||
// 获取菜单图标
|
||||
function getMenuIcon(menu: MenuApiType.MenuInfo) {
|
||||
function getMenuIcon(menu: MenuVO.MenuInfo) {
|
||||
if (menu.icon) {
|
||||
return createIconifyIcon(menu.icon);
|
||||
}
|
||||
@@ -278,6 +295,31 @@ const [Grid, gridApi] = useVbenVxeGrid({
|
||||
gridOptions,
|
||||
showSearchForm: false,
|
||||
tableTitle: '菜单管理',
|
||||
gridEvents: {
|
||||
// 拖拽排序事件
|
||||
rowDragend: handleDragSort,
|
||||
} as any,
|
||||
});
|
||||
|
||||
// 添加Grid组件的ref
|
||||
const gridRef = ref();
|
||||
|
||||
// 在组件挂载后绑定拖拽事件
|
||||
onMounted(() => {
|
||||
// 延迟绑定,确保Grid组件完全初始化
|
||||
setTimeout(() => {
|
||||
if (gridRef.value) {
|
||||
// 尝试直接绑定VxeTable的拖拽事件
|
||||
const vxeGrid = gridRef.value;
|
||||
if (vxeGrid && vxeGrid.$refs && vxeGrid.$refs.grid) {
|
||||
const grid = vxeGrid.$refs.grid;
|
||||
// 绑定拖拽事件
|
||||
grid.on('row-drag-end', (params: any) => {
|
||||
handleDragSort(params);
|
||||
});
|
||||
}
|
||||
}
|
||||
}, 1000);
|
||||
});
|
||||
</script>
|
||||
|
||||
@@ -285,6 +327,7 @@ const [Grid, gridApi] = useVbenVxeGrid({
|
||||
<Page title="菜单管理" auto-content-height>
|
||||
<!-- VbenVxeGrid 表格 -->
|
||||
<Grid
|
||||
ref="gridRef"
|
||||
:loading="loading"
|
||||
>
|
||||
<!-- 工具栏工具 -->
|
||||
@@ -302,16 +345,13 @@ const [Grid, gridApi] = useVbenVxeGrid({
|
||||
<CollapseIcon />
|
||||
全部收起
|
||||
</Button>
|
||||
<div class="text-gray-500 text-sm">
|
||||
💡 提示:可直接拖拽菜单名称列进行排序
|
||||
</div>
|
||||
</Space>
|
||||
</template>
|
||||
|
||||
<!-- 菜单名称列 -->
|
||||
<template #menuName="{ row }: { row: any }">
|
||||
<div class="flex items-center space-x-2">
|
||||
<component :is="getMenuIcon(row)" class="w-4 h-4 text-gray-600" />
|
||||
<span>{{ row.name }}</span>
|
||||
</div>
|
||||
</template>
|
||||
<!-- 菜单名称列 - 移除自定义插槽以支持拖拽控件正常显示 -->
|
||||
|
||||
<!-- 图标列 -->
|
||||
<template #icon="{ row }: { row: any }">
|
||||
@@ -335,6 +375,21 @@ const [Grid, gridApi] = useVbenVxeGrid({
|
||||
</Tag>
|
||||
</template>
|
||||
|
||||
<!-- 权限名称列 -->
|
||||
<template #permissions="{ row }: { row: any }">
|
||||
<div v-if="row.permissions && row.permissions.length > 0" class="flex flex-wrap gap-1">
|
||||
<Tag
|
||||
v-for="permission in row.permissions"
|
||||
:key="permission.id"
|
||||
:color="permission.status === 1 ? 'blue' : 'default'"
|
||||
size="small"
|
||||
>
|
||||
{{ permission.name }}
|
||||
</Tag>
|
||||
</div>
|
||||
<span v-else class="text-gray-400">-</span>
|
||||
</template>
|
||||
|
||||
<!-- 操作列 -->
|
||||
<template #action="{ row }: { row: any }">
|
||||
<Space>
|
||||
@@ -361,3 +416,4 @@ const [Grid, gridApi] = useVbenVxeGrid({
|
||||
/>
|
||||
</Page>
|
||||
</template>
|
||||
|
||||
|
||||
Reference in New Issue
Block a user