1:用户管理页面优化 2:角色管理页面优化 3:分配角色权限优化

This commit is contained in:
2025-10-11 12:19:34 +08:00
parent 65e2d4b92f
commit 96da469bef
13 changed files with 382 additions and 335 deletions
@@ -18,13 +18,14 @@ import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* @author 作者 owen E-mail: 624191343@qq.com
* @author 浣滆€?owen E-mail: 624191343@qq.com
*/
@RestController
@Tag(name = "菜单模块api")
@Tag(name = "菜单模块API")
@Slf4j
@RequestMapping("/menus")
public class SysMenuController {
@@ -32,12 +33,12 @@ public class SysMenuController {
private ISysMenuService menuService;
/**
* 两层循环实现建树
* 涓ゅ眰寰幆瀹炵幇寤烘爲
*
* @param sysMenus
* @return
*/
public static List<SysMenu> treeBuilder(List<SysMenu> sysMenus) {
/*public static List<SysMenu> treeBuilder(List<SysMenu> sysMenus) {
List<SysMenu> menus = new ArrayList<>();
for (SysMenu sysMenu : sysMenus) {
if (ObjectUtil.equal(-1L, sysMenu.getParentId())) {
@@ -53,33 +54,114 @@ public class SysMenuController {
}
}
return menus;
}*/
/**
* 构建菜单树:当仅有子菜单时,自动批量补齐父菜单后再组装树
*/
private List<SysMenu> treeBuilder(List<SysMenu> sysMenus) {
if (sysMenus == null || sysMenus.isEmpty()) {
return Collections.emptyList();
}
// 1) 去重映射:id -> SysMenu
Map<Long, SysMenu> idMap = sysMenus.stream()
.filter(Objects::nonNull)
.filter(m -> m.getId() != null)
.collect(Collectors.toMap(SysMenu::getId, Function.identity(), (a, b) -> a));
Set<Long> knownIds = new HashSet<>(idMap.keySet());
// 2) 迭代补齐缺失的父菜单(根判定:null/0/-1)
Set<Long> missing = sysMenus.stream()
.map(SysMenu::getParentId)
.filter(Objects::nonNull)
.filter(pid -> !Objects.equals(pid, 0L) && !Objects.equals(pid, -1L))
.filter(pid -> !knownIds.contains(pid))
.collect(Collectors.toSet());
int guard = 0;
final int maxIterations = 50;
while (!missing.isEmpty() && guard++ < maxIterations) {
List<SysMenu> parents = menuService.listByIds(new ArrayList<>(missing));
if (parents == null || parents.isEmpty()) break;
boolean progressed = false;
for (SysMenu p : parents) {
if (p != null && p.getId() != null && knownIds.add(p.getId())) {
idMap.put(p.getId(), p);
progressed = true;
}
}
if (!progressed) break;
missing = parents.stream()
.map(SysMenu::getParentId)
.filter(Objects::nonNull)
.filter(pid -> !Objects.equals(pid, 0L) && !Objects.equals(pid, -1L))
.filter(pid -> !knownIds.contains(pid))
.collect(Collectors.toSet());
}
// 合并全集
List<SysMenu> all = new ArrayList<>(idMap.values());
// 3) parentId -> children
Map<Long, List<SysMenu>> childrenMap = all.stream()
.filter(m -> m.getParentId() != null)
.collect(Collectors.groupingBy(SysMenu::getParentId));
Comparator<SysMenu> bySort = Comparator.comparing(
SysMenu::getSort,
Comparator.nullsLast(Integer::compareTo)
);
// 4) 挂载子节点(无子设为 null)
for (SysMenu node : all) {
List<SysMenu> children = childrenMap.get(node.getId());
if (children != null && !children.isEmpty()) {
children.sort(bySort);
node.setSubMenus(children);
} else {
node.setSubMenus(null);
}
}
// 5) 根节点:parentId 为 null/0/-1,或 parentId 不在已知 id 集合中
List<SysMenu> roots = all.stream()
.filter(m -> {
Long pid = m.getParentId();
return pid == null || Objects.equals(pid, 0L) || Objects.equals(pid, -1L) || !knownIds.contains(pid);
})
.distinct()
.sorted(bySort)
.collect(Collectors.toList());
return roots;
}
/**
* 删除菜单
* 鍒犻櫎鑿滃崟
*
* @param id
*/
@Operation(summary = "删除菜单")
@Operation(summary = "删除菜单")
@DeleteMapping("/{id}")
public Result delete(@PathVariable Long id) {
try {
menuService.removeById(id);
return Result.succeed("操作成功");
return Result.succeed("操作成功");
} catch (Exception ex) {
log.error("memu-delete-error", ex);
return Result.failed("操作失败");
return Result.failed("操作失败");
}
}
@Operation(summary = "根据roleId获取对应的菜单")
@Operation(summary = "根据roleId获取对应的菜单")
@GetMapping("/{roleId}/menus")
public List<Map<String, Object>> findMenusByRoleId(@PathVariable Long roleId) {
Set<Long> roleIds = new HashSet<>();
roleIds.add(roleId);
//获取该角色对应的菜单
//鑾峰彇璇ヨ鑹插搴旂殑鑿滃崟
List<SysMenu> roleMenus = menuService.findByRoles(roleIds);
//全部的菜单列表
//鍏ㄩ儴鐨勮彍鍗曞垪琛?
List<SysMenu> allMenus = menuService.findAll();
List<Map<String, Object>> authTrees = new ArrayList<>();
@@ -100,7 +182,7 @@ public class SysMenuController {
return authTrees;
}
@Operation(summary = "根据roleCodes获取对应的权限")
@Operation(summary = "根据roleCodes获取对应的权限")
@SuppressWarnings("unchecked")
@Cacheable(value = "menu", key ="#roleCodes")
@GetMapping("/{roleCodes}")
@@ -114,23 +196,23 @@ public class SysMenuController {
}
/**
* 给角色分配菜单
* 缁欒鑹插垎閰嶈彍鍗?
*/
@Operation(summary = "角色分配菜单")
@Operation(summary = "角色分配菜单")
@PostMapping("/granted")
public Result setMenuToRole(@RequestBody SysMenu sysMenu) {
menuService.setMenuToRole(sysMenu.getRoleId(), sysMenu.getMenuIds());
return Result.succeed("操作成功");
return Result.succeed("操作成功");
}
@Operation(summary = "查询所有菜单")
@Operation(summary = "查询所有菜单")
@GetMapping("/findAlls")
public PageResult<SysMenu> findAlls() {
List<SysMenu> list = menuService.findAll();
return PageResult.<SysMenu>builder().data(list).resp_code(0).count((long) list.size()).build();
}
@Operation(summary = "获取菜单以及顶级菜单")
@Operation(summary = "获取菜单以及顶级菜单")
@GetMapping("/findOnes")
public PageResult<SysMenu> findOnes() {
List<SysMenu> list = menuService.findOnes();
@@ -138,12 +220,12 @@ public class SysMenuController {
}
/**
* 添加菜单 或者 更新
* 娣诲姞鑿滃崟 鎴栬€?鏇存柊
*
* @param menu
* @return
*/
@Operation(summary = "新增菜单")
@Operation(summary = "新增菜单")
@PostMapping("saveOrUpdate")
public Result saveOrUpdate(@RequestBody SysMenu menu) {
try {
@@ -151,22 +233,23 @@ public class SysMenuController {
menu.setCreatorId(LoginUserContextHolder.getUser().getId());
}
menuService.saveOrUpdate(menu);
return Result.succeed("操作成功");
return Result.succeed("操作成功");
} catch (Exception ex) {
log.error("memu-saveOrUpdate-error", ex);
return Result.failed("操作失败");
return Result.failed("操作失败");
}
}
/**
* 当前登录用户的菜单
* 褰撳墠鐧诲綍鐢ㄦ埛鐨勮彍鍗?
*
* @return
*/
@GetMapping("/current")
@Operation(summary = "查询当前用户菜单")
@Operation(summary = "查询当前用户菜单")
public List<SysMenu> findMyMenu() {
LoginAppUser user = LoginUserContextHolder.getUser();
log.info("获取到当前登录人的id是:{}", user.getId());
List<SysMenu> menus = menuService.findByUserId(user.getId(), CommonConstant.MENU);
return treeBuilder(menus);
}
@@ -233,42 +233,48 @@ public class SysUserServiceImpl extends SuperServiceImpl<SysUserMapper, SysUser>
@Override
public PageResult<SysUser> findUsers(Map<String, Object> params) {
Page<SysUser> page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit"));
// 组装租户过滤:有传tenantId则以其为锚点(可选包含子级);未传则按当前登录用户及其子租户
String tenantId = MapUtils.getString(params, "tenantId");
Boolean includeChildren = MapUtils.getBoolean(params, "includeChildren", Boolean.TRUE);
List<String> tenantIds = null;
if (StrUtil.isNotBlank(tenantId)) {
try {
if (Boolean.TRUE.equals(includeChildren)) {
tenantIds = tenantHierarchyService.getAllSubTenantIds(tenantId);
} else {
tenantIds = java.util.Collections.singletonList(tenantId);
}
} catch (Exception ignored) { tenantIds = java.util.Collections.singletonList(tenantId); }
} else {
// 未显式指定,则按当前登录用户所属租户及其子租户
try {
String anchor = LoginUserContextHolder.getCurrentTenantId();
if (StringUtils.isNotBlank(anchor)) {
try {
tenantIds = tenantHierarchyService.getAllSubTenantIds(anchor);
} catch (Exception e) {
tenantIds = java.util.Collections.singletonList(anchor);
}
}
} catch (Exception ignored) { /* no-op */ }
}
if (tenantIds != null && !tenantIds.isEmpty()) {
params.put("tenantIds", tenantIds);
}
String type = MapUtils.getString(params, "type");
if("BACKEND".equals(type)){
// 组装租户过滤:有传tenantId则以其为锚点(可选包含子级);未传则按当前登录用户及其子租户
String tenantId = MapUtils.getString(params, "tenantId");
Boolean includeChildren = MapUtils.getBoolean(params, "includeChildren", Boolean.TRUE);
List<String> tenantIds = null;
if (StrUtil.isNotBlank(tenantId)) {
try {
if (Boolean.TRUE.equals(includeChildren)) {
tenantIds = tenantHierarchyService.getAllSubTenantIds(tenantId);
} else {
tenantIds = java.util.Collections.singletonList(tenantId);
}
} catch (Exception ignored) { tenantIds = java.util.Collections.singletonList(tenantId); }
} else {
// 未显式指定,则按当前登录用户所属租户及其子租户
try {
String anchor = LoginUserContextHolder.getCurrentTenantId();
if (StringUtils.isNotBlank(anchor)) {
try {
tenantIds = tenantHierarchyService.getAllSubTenantIds(anchor);
} catch (Exception e) {
tenantIds = java.util.Collections.singletonList(anchor);
}
}
} catch (Exception ignored) { /* no-op */ }
}
if (tenantIds != null && !tenantIds.isEmpty()) {
params.put("tenantIds", tenantIds);
}
}
List<SysUser> list = baseMapper.findList(page, params);
long total = page.getTotal();
if (total > 0) {
List<Long> userIds = list.stream().map(SysUser::getId).collect(Collectors.toList());
List<SysRole> sysRoles = roleUserService.findRolesByUserIds(userIds);
list.forEach(u -> u.setRoles(sysRoles.stream().filter(r -> !Objects.equals(u.getId(), r.getUserId()))
.collect(Collectors.toList())));
if ("BACKEND".equals(type) && list != null && !list.isEmpty()) {
for (SysUser u : list) {
if (u == null || u.getId() == null) {
continue;
}
List<SysRole> roles = roleUserService.findRolesByUserId(u.getId());
u.setRoles(roles == null ? Collections.emptyList() : roles);
}
}
return PageResult.<SysUser>builder().data(list).resp_code(0).count(total).build();
}
@@ -184,7 +184,12 @@ public class TenantHierarchyServiceImpl implements ITenantHierarchyService {
Tenant parent = tenantHierarchyMapper.selectByTenantId(tenant.getParentTenantId());
if (parent == null) return Result.failed("父租户不存在");
tenant.setTenantLevel(parent.getTenantLevel() + 1);
tenant.setTenantPath(parent.getTenantPath() + tenant.getTenantId() + "/");
// 规范化父路径与当前租户ID的拼接,确保只存在一个分隔符“/”
// 兼容历史数据:父路径可能不存在结尾斜杠,或带有多余斜杠
String base = normalizeBasePath(parent.getTenantPath());
String cur = stripSlashes(tenant.getTenantId());
String path = (base.isEmpty() ? "" : ("/" + base)) + "/" + cur + "/";
tenant.setTenantPath(path);
} else {
tenant.setTenantLevel(1);
tenant.setTenantPath("/" + tenant.getTenantId() + "/");
@@ -205,6 +210,35 @@ public class TenantHierarchyServiceImpl implements ITenantHierarchyService {
}
}
/**
* 规范化基础路径:
* - 去除前后多余斜杠
* - 去除前缀的 "null"(防御历史脏数据)
* 返回不带首尾斜杠的路径片段,例如:"webApp/xcApp"
*/
private String normalizeBasePath(String raw) {
if (raw == null) return "";
String s = raw.trim();
if (s.toLowerCase().startsWith("null")) {
s = s.substring(4);
}
// 去除前后所有斜杠
while (s.startsWith("/")) s = s.substring(1);
while (s.endsWith("/")) s = s.substring(0, s.length() - 1);
return s;
}
/**
* 去除参数前后斜杠,返回中间片段
*/
private String stripSlashes(String raw) {
if (raw == null) return "";
String s = raw.trim();
while (s.startsWith("/")) s = s.substring(1);
while (s.endsWith("/")) s = s.substring(0, s.length() - 1);
return s;
}
@Override
@Transactional
@CacheEvict(value = "tenant:hierarchy", allEntries = true)
@@ -316,4 +350,3 @@ public class TenantHierarchyServiceImpl implements ITenantHierarchyService {
.build();
}
}
@@ -2,21 +2,24 @@
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.central.user.mapper.SysUserMapper">
<sql id="where">
<where>
t.is_del=0
<if test="u.tenantIds != null and u.tenantIds.size > 0">
and t.company in
<foreach collection="u.tenantIds" item="tid" open="(" separator="," close=")">
#{tid}
</foreach>
</if>
<if test="u.id != null and u.id != ''">
and t.id like concat('%', #{u.id}, '%')
</if>
<sql id="where">
<where>
t.is_del=0
<if test="u.tenantIds != null and u.tenantIds.size > 0">
and t.company in
<foreach collection="u.tenantIds" item="tid" open="(" separator="," close=")">
#{tid}
</foreach>
</if>
<if test="u.id != null and u.id != ''">
and t.id like concat('%', #{u.id}, '%')
</if>
<if test="u.username != null and u.username != ''">
and t.username like concat('%', #{u.username}, '%')
</if>
<if test="u.mobile != null and u.mobile != ''">
and t.mobile like concat('%', #{u.mobile}, '%')
</if>
<if test="u.nickname != null and u.nickname != ''">
and t.nickname like concat('%', #{u.nickname}, '%')
</if>
@@ -26,18 +29,6 @@
<if test="u.type != null and u.type != ''">
and t.type = #{u.type}
</if>
<if test="u.searchKey != null and u.searchKey != '' and u.searchKey=='user_id'">
and t.id like concat('%', #{u.searchValue}, '%')
</if>
<if test="u.searchKey != null and u.searchKey != '' and u.searchKey=='username'">
and t.username like concat('%', #{u.searchValue}, '%')
</if>
<if test="u.searchKey != null and u.searchKey != '' and u.searchKey=='nick_name'">
and t.nickname like concat('%', #{u.searchValue}, '%')
</if>
<if test="u.searchKey != null and u.searchKey != '' and u.searchKey=='mobile'">
and t.mobile like concat('%', #{u.searchValue}, '%')
</if>
</where>
</sql>
@@ -46,4 +37,4 @@
<include refid="where" />
order by t.id desc
</select>
</mapper>
</mapper>