!38 1:用户管理页面优化 2:角色管理页面优化 3:分配角色权限优化
Merge pull request !38 from 鸭先知/feature_dzc
This commit is contained in:
+106
-23
@@ -18,13 +18,14 @@ import org.springframework.cache.annotation.Cacheable;
|
|||||||
import org.springframework.web.bind.annotation.*;
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
|
import java.util.function.Function;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @author 作者 owen E-mail: 624191343@qq.com
|
* @author 浣滆€?owen E-mail: 624191343@qq.com
|
||||||
*/
|
*/
|
||||||
@RestController
|
@RestController
|
||||||
@Tag(name = "菜单模块api")
|
@Tag(name = "菜单模块API")
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@RequestMapping("/menus")
|
@RequestMapping("/menus")
|
||||||
public class SysMenuController {
|
public class SysMenuController {
|
||||||
@@ -32,12 +33,12 @@ public class SysMenuController {
|
|||||||
private ISysMenuService menuService;
|
private ISysMenuService menuService;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 两层循环实现建树
|
* 涓ゅ眰寰幆瀹炵幇寤烘爲
|
||||||
*
|
*
|
||||||
* @param sysMenus
|
* @param sysMenus
|
||||||
* @return
|
* @return
|
||||||
*/
|
*/
|
||||||
public static List<SysMenu> treeBuilder(List<SysMenu> sysMenus) {
|
/*public static List<SysMenu> treeBuilder(List<SysMenu> sysMenus) {
|
||||||
List<SysMenu> menus = new ArrayList<>();
|
List<SysMenu> menus = new ArrayList<>();
|
||||||
for (SysMenu sysMenu : sysMenus) {
|
for (SysMenu sysMenu : sysMenus) {
|
||||||
if (ObjectUtil.equal(-1L, sysMenu.getParentId())) {
|
if (ObjectUtil.equal(-1L, sysMenu.getParentId())) {
|
||||||
@@ -53,33 +54,114 @@ public class SysMenuController {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
return menus;
|
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
|
* @param id
|
||||||
*/
|
*/
|
||||||
@Operation(summary = "删除菜单")
|
@Operation(summary = "删除菜单")
|
||||||
@DeleteMapping("/{id}")
|
@DeleteMapping("/{id}")
|
||||||
public Result delete(@PathVariable Long id) {
|
public Result delete(@PathVariable Long id) {
|
||||||
try {
|
try {
|
||||||
menuService.removeById(id);
|
menuService.removeById(id);
|
||||||
return Result.succeed("操作成功");
|
return Result.succeed("操作成功");
|
||||||
} catch (Exception ex) {
|
} catch (Exception ex) {
|
||||||
log.error("memu-delete-error", ex);
|
log.error("memu-delete-error", ex);
|
||||||
return Result.failed("操作失败");
|
return Result.failed("操作失败");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "根据roleId获取对应的菜单")
|
@Operation(summary = "根据roleId获取对应的菜单")
|
||||||
@GetMapping("/{roleId}/menus")
|
@GetMapping("/{roleId}/menus")
|
||||||
public List<Map<String, Object>> findMenusByRoleId(@PathVariable Long roleId) {
|
public List<Map<String, Object>> findMenusByRoleId(@PathVariable Long roleId) {
|
||||||
Set<Long> roleIds = new HashSet<>();
|
Set<Long> roleIds = new HashSet<>();
|
||||||
roleIds.add(roleId);
|
roleIds.add(roleId);
|
||||||
//获取该角色对应的菜单
|
//鑾峰彇璇ヨ鑹插搴旂殑鑿滃崟
|
||||||
List<SysMenu> roleMenus = menuService.findByRoles(roleIds);
|
List<SysMenu> roleMenus = menuService.findByRoles(roleIds);
|
||||||
//全部的菜单列表
|
//鍏ㄩ儴鐨勮彍鍗曞垪琛?
|
||||||
List<SysMenu> allMenus = menuService.findAll();
|
List<SysMenu> allMenus = menuService.findAll();
|
||||||
List<Map<String, Object>> authTrees = new ArrayList<>();
|
List<Map<String, Object>> authTrees = new ArrayList<>();
|
||||||
|
|
||||||
@@ -100,7 +182,7 @@ public class SysMenuController {
|
|||||||
return authTrees;
|
return authTrees;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "根据roleCodes获取对应的权限")
|
@Operation(summary = "根据roleCodes获取对应的权限")
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
@Cacheable(value = "menu", key ="#roleCodes")
|
@Cacheable(value = "menu", key ="#roleCodes")
|
||||||
@GetMapping("/{roleCodes}")
|
@GetMapping("/{roleCodes}")
|
||||||
@@ -114,23 +196,23 @@ public class SysMenuController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 给角色分配菜单
|
* 缁欒鑹插垎閰嶈彍鍗?
|
||||||
*/
|
*/
|
||||||
@Operation(summary = "角色分配菜单")
|
@Operation(summary = "角色分配菜单")
|
||||||
@PostMapping("/granted")
|
@PostMapping("/granted")
|
||||||
public Result setMenuToRole(@RequestBody SysMenu sysMenu) {
|
public Result setMenuToRole(@RequestBody SysMenu sysMenu) {
|
||||||
menuService.setMenuToRole(sysMenu.getRoleId(), sysMenu.getMenuIds());
|
menuService.setMenuToRole(sysMenu.getRoleId(), sysMenu.getMenuIds());
|
||||||
return Result.succeed("操作成功");
|
return Result.succeed("操作成功");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "查询所有菜单")
|
@Operation(summary = "查询所有菜单")
|
||||||
@GetMapping("/findAlls")
|
@GetMapping("/findAlls")
|
||||||
public PageResult<SysMenu> findAlls() {
|
public PageResult<SysMenu> findAlls() {
|
||||||
List<SysMenu> list = menuService.findAll();
|
List<SysMenu> list = menuService.findAll();
|
||||||
return PageResult.<SysMenu>builder().data(list).resp_code(0).count((long) list.size()).build();
|
return PageResult.<SysMenu>builder().data(list).resp_code(0).count((long) list.size()).build();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "获取菜单以及顶级菜单")
|
@Operation(summary = "获取菜单以及顶级菜单")
|
||||||
@GetMapping("/findOnes")
|
@GetMapping("/findOnes")
|
||||||
public PageResult<SysMenu> findOnes() {
|
public PageResult<SysMenu> findOnes() {
|
||||||
List<SysMenu> list = menuService.findOnes();
|
List<SysMenu> list = menuService.findOnes();
|
||||||
@@ -138,12 +220,12 @@ public class SysMenuController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 添加菜单 或者 更新
|
* 娣诲姞鑿滃崟 鎴栬€?鏇存柊
|
||||||
*
|
*
|
||||||
* @param menu
|
* @param menu
|
||||||
* @return
|
* @return
|
||||||
*/
|
*/
|
||||||
@Operation(summary = "新增菜单")
|
@Operation(summary = "新增菜单")
|
||||||
@PostMapping("saveOrUpdate")
|
@PostMapping("saveOrUpdate")
|
||||||
public Result saveOrUpdate(@RequestBody SysMenu menu) {
|
public Result saveOrUpdate(@RequestBody SysMenu menu) {
|
||||||
try {
|
try {
|
||||||
@@ -151,22 +233,23 @@ public class SysMenuController {
|
|||||||
menu.setCreatorId(LoginUserContextHolder.getUser().getId());
|
menu.setCreatorId(LoginUserContextHolder.getUser().getId());
|
||||||
}
|
}
|
||||||
menuService.saveOrUpdate(menu);
|
menuService.saveOrUpdate(menu);
|
||||||
return Result.succeed("操作成功");
|
return Result.succeed("操作成功");
|
||||||
} catch (Exception ex) {
|
} catch (Exception ex) {
|
||||||
log.error("memu-saveOrUpdate-error", ex);
|
log.error("memu-saveOrUpdate-error", ex);
|
||||||
return Result.failed("操作失败");
|
return Result.failed("操作失败");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 当前登录用户的菜单
|
* 褰撳墠鐧诲綍鐢ㄦ埛鐨勮彍鍗?
|
||||||
*
|
*
|
||||||
* @return
|
* @return
|
||||||
*/
|
*/
|
||||||
@GetMapping("/current")
|
@GetMapping("/current")
|
||||||
@Operation(summary = "查询当前用户菜单")
|
@Operation(summary = "查询当前用户菜单")
|
||||||
public List<SysMenu> findMyMenu() {
|
public List<SysMenu> findMyMenu() {
|
||||||
LoginAppUser user = LoginUserContextHolder.getUser();
|
LoginAppUser user = LoginUserContextHolder.getUser();
|
||||||
|
log.info("获取到当前登录人的id是:{}", user.getId());
|
||||||
List<SysMenu> menus = menuService.findByUserId(user.getId(), CommonConstant.MENU);
|
List<SysMenu> menus = menuService.findByUserId(user.getId(), CommonConstant.MENU);
|
||||||
return treeBuilder(menus);
|
return treeBuilder(menus);
|
||||||
}
|
}
|
||||||
|
|||||||
+39
-33
@@ -233,42 +233,48 @@ public class SysUserServiceImpl extends SuperServiceImpl<SysUserMapper, SysUser>
|
|||||||
@Override
|
@Override
|
||||||
public PageResult<SysUser> findUsers(Map<String, Object> params) {
|
public PageResult<SysUser> findUsers(Map<String, Object> params) {
|
||||||
Page<SysUser> page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit"));
|
Page<SysUser> page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit"));
|
||||||
// 组装租户过滤:有传tenantId则以其为锚点(可选包含子级);未传则按当前登录用户及其子租户
|
String type = MapUtils.getString(params, "type");
|
||||||
String tenantId = MapUtils.getString(params, "tenantId");
|
if("BACKEND".equals(type)){
|
||||||
Boolean includeChildren = MapUtils.getBoolean(params, "includeChildren", Boolean.TRUE);
|
// 组装租户过滤:有传tenantId则以其为锚点(可选包含子级);未传则按当前登录用户及其子租户
|
||||||
List<String> tenantIds = null;
|
String tenantId = MapUtils.getString(params, "tenantId");
|
||||||
if (StrUtil.isNotBlank(tenantId)) {
|
Boolean includeChildren = MapUtils.getBoolean(params, "includeChildren", Boolean.TRUE);
|
||||||
try {
|
List<String> tenantIds = null;
|
||||||
if (Boolean.TRUE.equals(includeChildren)) {
|
if (StrUtil.isNotBlank(tenantId)) {
|
||||||
tenantIds = tenantHierarchyService.getAllSubTenantIds(tenantId);
|
try {
|
||||||
} else {
|
if (Boolean.TRUE.equals(includeChildren)) {
|
||||||
tenantIds = java.util.Collections.singletonList(tenantId);
|
tenantIds = tenantHierarchyService.getAllSubTenantIds(tenantId);
|
||||||
}
|
} else {
|
||||||
} catch (Exception ignored) { tenantIds = java.util.Collections.singletonList(tenantId); }
|
tenantIds = java.util.Collections.singletonList(tenantId);
|
||||||
} else {
|
}
|
||||||
// 未显式指定,则按当前登录用户所属租户及其子租户
|
} catch (Exception ignored) { tenantIds = java.util.Collections.singletonList(tenantId); }
|
||||||
try {
|
} else {
|
||||||
String anchor = LoginUserContextHolder.getCurrentTenantId();
|
// 未显式指定,则按当前登录用户所属租户及其子租户
|
||||||
if (StringUtils.isNotBlank(anchor)) {
|
try {
|
||||||
try {
|
String anchor = LoginUserContextHolder.getCurrentTenantId();
|
||||||
tenantIds = tenantHierarchyService.getAllSubTenantIds(anchor);
|
if (StringUtils.isNotBlank(anchor)) {
|
||||||
} catch (Exception e) {
|
try {
|
||||||
tenantIds = java.util.Collections.singletonList(anchor);
|
tenantIds = tenantHierarchyService.getAllSubTenantIds(anchor);
|
||||||
}
|
} catch (Exception e) {
|
||||||
}
|
tenantIds = java.util.Collections.singletonList(anchor);
|
||||||
} catch (Exception ignored) { /* no-op */ }
|
}
|
||||||
}
|
}
|
||||||
if (tenantIds != null && !tenantIds.isEmpty()) {
|
} catch (Exception ignored) { /* no-op */ }
|
||||||
params.put("tenantIds", tenantIds);
|
}
|
||||||
}
|
if (tenantIds != null && !tenantIds.isEmpty()) {
|
||||||
|
params.put("tenantIds", tenantIds);
|
||||||
|
}
|
||||||
|
}
|
||||||
List<SysUser> list = baseMapper.findList(page, params);
|
List<SysUser> list = baseMapper.findList(page, params);
|
||||||
long total = page.getTotal();
|
long total = page.getTotal();
|
||||||
if (total > 0) {
|
|
||||||
List<Long> userIds = list.stream().map(SysUser::getId).collect(Collectors.toList());
|
|
||||||
|
|
||||||
List<SysRole> sysRoles = roleUserService.findRolesByUserIds(userIds);
|
if ("BACKEND".equals(type) && list != null && !list.isEmpty()) {
|
||||||
list.forEach(u -> u.setRoles(sysRoles.stream().filter(r -> !Objects.equals(u.getId(), r.getUserId()))
|
for (SysUser u : list) {
|
||||||
.collect(Collectors.toList())));
|
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();
|
return PageResult.<SysUser>builder().data(list).resp_code(0).count(total).build();
|
||||||
}
|
}
|
||||||
|
|||||||
+35
-2
@@ -184,7 +184,12 @@ public class TenantHierarchyServiceImpl implements ITenantHierarchyService {
|
|||||||
Tenant parent = tenantHierarchyMapper.selectByTenantId(tenant.getParentTenantId());
|
Tenant parent = tenantHierarchyMapper.selectByTenantId(tenant.getParentTenantId());
|
||||||
if (parent == null) return Result.failed("父租户不存在");
|
if (parent == null) return Result.failed("父租户不存在");
|
||||||
tenant.setTenantLevel(parent.getTenantLevel() + 1);
|
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 {
|
} else {
|
||||||
tenant.setTenantLevel(1);
|
tenant.setTenantLevel(1);
|
||||||
tenant.setTenantPath("/" + tenant.getTenantId() + "/");
|
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
|
@Override
|
||||||
@Transactional
|
@Transactional
|
||||||
@CacheEvict(value = "tenant:hierarchy", allEntries = true)
|
@CacheEvict(value = "tenant:hierarchy", allEntries = true)
|
||||||
@@ -316,4 +350,3 @@ public class TenantHierarchyServiceImpl implements ITenantHierarchyService {
|
|||||||
.build();
|
.build();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,21 +2,24 @@
|
|||||||
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||||
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
||||||
<mapper namespace="com.central.user.mapper.SysUserMapper">
|
<mapper namespace="com.central.user.mapper.SysUserMapper">
|
||||||
<sql id="where">
|
<sql id="where">
|
||||||
<where>
|
<where>
|
||||||
t.is_del=0
|
t.is_del=0
|
||||||
<if test="u.tenantIds != null and u.tenantIds.size > 0">
|
<if test="u.tenantIds != null and u.tenantIds.size > 0">
|
||||||
and t.company in
|
and t.company in
|
||||||
<foreach collection="u.tenantIds" item="tid" open="(" separator="," close=")">
|
<foreach collection="u.tenantIds" item="tid" open="(" separator="," close=")">
|
||||||
#{tid}
|
#{tid}
|
||||||
</foreach>
|
</foreach>
|
||||||
</if>
|
</if>
|
||||||
<if test="u.id != null and u.id != ''">
|
<if test="u.id != null and u.id != ''">
|
||||||
and t.id like concat('%', #{u.id}, '%')
|
and t.id like concat('%', #{u.id}, '%')
|
||||||
</if>
|
</if>
|
||||||
<if test="u.username != null and u.username != ''">
|
<if test="u.username != null and u.username != ''">
|
||||||
and t.username like concat('%', #{u.username}, '%')
|
and t.username like concat('%', #{u.username}, '%')
|
||||||
</if>
|
</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 != ''">
|
<if test="u.nickname != null and u.nickname != ''">
|
||||||
and t.nickname like concat('%', #{u.nickname}, '%')
|
and t.nickname like concat('%', #{u.nickname}, '%')
|
||||||
</if>
|
</if>
|
||||||
@@ -26,18 +29,6 @@
|
|||||||
<if test="u.type != null and u.type != ''">
|
<if test="u.type != null and u.type != ''">
|
||||||
and t.type = #{u.type}
|
and t.type = #{u.type}
|
||||||
</if>
|
</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>
|
</where>
|
||||||
</sql>
|
</sql>
|
||||||
|
|
||||||
@@ -46,4 +37,4 @@
|
|||||||
<include refid="where" />
|
<include refid="where" />
|
||||||
order by t.id desc
|
order by t.id desc
|
||||||
</select>
|
</select>
|
||||||
</mapper>
|
</mapper>
|
||||||
|
|||||||
@@ -1,17 +1,21 @@
|
|||||||
import React, { useEffect, useState } from 'react';
|
import React, { useEffect, useState } from 'react';
|
||||||
import { Form, TreeSelect, Checkbox, message } from 'antd';
|
import { Form, TreeSelect, Checkbox, message } from 'antd';
|
||||||
import { tenantApi, TenantTreeNode } from '@/services/tenant';
|
import { tenantApi, TenantTreeNode } from '@/services/tenant';
|
||||||
import { getTenantTreeCache, setTenantTreeCache, getTenantChildrenCache, setTenantChildrenCache, getTenantDetailCache, setTenantDetailCache } from '@/utils/tenantCache';
|
import { getTenantTreeCache, setTenantTreeCache } from '@/utils/tenantCache';
|
||||||
|
|
||||||
export interface TenantSelectorProps {
|
export interface TenantSelectorProps {
|
||||||
nameTenant?: string;
|
nameTenant?: string;
|
||||||
nameIncludeChildren?: string;
|
nameIncludeChildren?: string;
|
||||||
labelTenant?: React.ReactNode;
|
labelTenant?: React.ReactNode;
|
||||||
labelIncludeChildren?: React.ReactNode;
|
labelIncludeChildren?: React.ReactNode;
|
||||||
// 是否隐藏“包含下级”复选框(用于仅需要选择租户的场景,如用户表单)
|
// 是否隐藏“包含子租户”复选框(用于仅需要选择租户的场景,如用户表单)
|
||||||
hideIncludeChildren?: boolean;
|
hideIncludeChildren?: boolean;
|
||||||
// 透传给租户选择项的校验规则(用于必填等)
|
// 透传给租户选择项的校验规则(用于必填等)
|
||||||
rulesTenant?: any[];
|
rulesTenant?: any[];
|
||||||
|
// 抑制默认选中当前租户(不自动回填),并避免无必要的当前租户接口调用
|
||||||
|
suppressAutoSelect?: boolean;
|
||||||
|
// 禁止在挂载时请求“当前租户”接口(通常在编辑态已知租户时使用)
|
||||||
|
disableFetchCurrentTenant?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
const toTreeData = (nodes?: TenantTreeNode[] | any): any[] => {
|
const toTreeData = (nodes?: TenantTreeNode[] | any): any[] => {
|
||||||
@@ -19,7 +23,7 @@ const toTreeData = (nodes?: TenantTreeNode[] | any): any[] => {
|
|||||||
return arr.map((n) => {
|
return arr.map((n) => {
|
||||||
const id = (n as any)?.tenantId as string | undefined;
|
const id = (n as any)?.tenantId as string | undefined;
|
||||||
const name = (n as any)?.tenantName as string | undefined;
|
const name = (n as any)?.tenantName as string | undefined;
|
||||||
const title = name && id ? `${name} (${id})` : (name || id || '-');
|
const title = name && id ? `${name} (${id})` : (name || id || '-')
|
||||||
return {
|
return {
|
||||||
title,
|
title,
|
||||||
value: id,
|
value: id,
|
||||||
@@ -33,9 +37,11 @@ const TenantSelector: React.FC<TenantSelectorProps> = ({
|
|||||||
nameTenant = 'tenantId',
|
nameTenant = 'tenantId',
|
||||||
nameIncludeChildren = 'includeChildren',
|
nameIncludeChildren = 'includeChildren',
|
||||||
labelTenant = '租户',
|
labelTenant = '租户',
|
||||||
labelIncludeChildren = '包含下级',
|
labelIncludeChildren = '包含子租户',
|
||||||
hideIncludeChildren = false,
|
hideIncludeChildren = false,
|
||||||
rulesTenant,
|
rulesTenant,
|
||||||
|
suppressAutoSelect = false,
|
||||||
|
disableFetchCurrentTenant = false,
|
||||||
}) => {
|
}) => {
|
||||||
const form = Form.useFormInstance?.();
|
const form = Form.useFormInstance?.();
|
||||||
const [tree, setTree] = useState<TenantTreeNode[]>([]);
|
const [tree, setTree] = useState<TenantTreeNode[]>([]);
|
||||||
@@ -45,7 +51,7 @@ const TenantSelector: React.FC<TenantSelectorProps> = ({
|
|||||||
(async () => {
|
(async () => {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
try {
|
try {
|
||||||
// 优先从缓存读取可访问租户树
|
// 使用“可访问租户树”
|
||||||
let list: TenantTreeNode[] = (getTenantTreeCache() as any) || [];
|
let list: TenantTreeNode[] = (getTenantTreeCache() as any) || [];
|
||||||
if (!list || list.length === 0) {
|
if (!list || list.length === 0) {
|
||||||
const treeRes: any = await tenantApi.getAccessibleTenants();
|
const treeRes: any = await tenantApi.getAccessibleTenants();
|
||||||
@@ -53,111 +59,31 @@ const TenantSelector: React.FC<TenantSelectorProps> = ({
|
|||||||
list = treeRes.success ? (treeRes.data || []) : [];
|
list = treeRes.success ? (treeRes.data || []) : [];
|
||||||
} else if (Array.isArray(treeRes)) {
|
} else if (Array.isArray(treeRes)) {
|
||||||
list = treeRes as TenantTreeNode[];
|
list = treeRes as TenantTreeNode[];
|
||||||
|
} else if (Array.isArray(treeRes?.data)) {
|
||||||
|
list = treeRes.data as TenantTreeNode[];
|
||||||
}
|
}
|
||||||
if (list && list.length) setTenantTreeCache(list as any);
|
if (list && list.length) setTenantTreeCache(list as any);
|
||||||
}
|
}
|
||||||
if (!list || list.length === 0) {
|
setTree(Array.isArray(list) ? list : []);
|
||||||
// 回退:仅当前租户
|
|
||||||
const cur: any = await tenantApi.getCurrentTenant();
|
// 默认选中当前租户(可被抑制)
|
||||||
if (cur?.success && cur?.data?.tenantId) {
|
if (!suppressAutoSelect) {
|
||||||
list = [{ tenantId: cur.data.tenantId, tenantName: cur.data.tenantName } as any];
|
try {
|
||||||
try { form?.setFieldsValue?.({ [nameTenant]: cur.data.tenantId, [nameIncludeChildren]: true }); } catch {}
|
if (!disableFetchCurrentTenant) {
|
||||||
} else {
|
const cur: any = await tenantApi.getCurrentTenant();
|
||||||
const stats: any = await tenantApi.getScopeStats();
|
const curId = cur?.data?.tenantId ?? cur?.tenantId;
|
||||||
const id = stats?.data?.currentTenantId;
|
if (curId && !form?.getFieldValue?.(nameTenant)) {
|
||||||
if (id) list = [{ tenantId: id, tenantName: id } as any];
|
form?.setFieldsValue?.({ [nameTenant]: curId, [nameIncludeChildren]: true });
|
||||||
try { form?.setFieldsValue?.({ [nameTenant]: id, [nameIncludeChildren]: true }); } catch {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (list && list.length && !form?.getFieldValue?.(nameTenant)) {
|
|
||||||
try { form?.setFieldsValue?.({ [nameTenant]: list[0].tenantId, [nameIncludeChildren]: true }); } catch {}
|
|
||||||
}
|
|
||||||
// 递进补齐:根 -> 二级 -> 三级,确保三级部门可见
|
|
||||||
const loadChildrenFor = async (nodes?: any[]): Promise<any[]> => {
|
|
||||||
const resultChildren: any[] = [];
|
|
||||||
if (!Array.isArray(nodes)) return resultChildren;
|
|
||||||
await Promise.all((nodes || []).map(async (node: any) => {
|
|
||||||
if (!node) return;
|
|
||||||
const pid = node.tenantId;
|
|
||||||
if (!pid) return;
|
|
||||||
// 若已有子节点,直接使用;否则尝试缓存;再不行才请求接口
|
|
||||||
if (Array.isArray(node.children) && node.children.length) {
|
|
||||||
// 已有
|
|
||||||
} else {
|
|
||||||
const cached = getTenantChildrenCache(pid);
|
|
||||||
if (cached) {
|
|
||||||
node.children = cached as any;
|
|
||||||
} else {
|
|
||||||
try {
|
|
||||||
const res: any = await tenantApi.getTenantList({ parentTenantId: pid, status: 1 as any, current: 1, pageSize: 1000 } as any);
|
|
||||||
const children = res?.data?.data || [];
|
|
||||||
if (children && children.length) {
|
|
||||||
node.children = children.map((c: any) => ({ tenantId: c.tenantId, tenantName: c.tenantName, status: c.status }));
|
|
||||||
} else {
|
|
||||||
node.children = undefined;
|
|
||||||
}
|
|
||||||
setTenantChildrenCache(pid, node.children as any);
|
|
||||||
} catch {}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (Array.isArray(node.children)) resultChildren.push(...node.children);
|
} catch {}
|
||||||
}));
|
// 回退为列表第一个(不覆盖已有值)
|
||||||
return resultChildren;
|
try {
|
||||||
};
|
if (Array.isArray(list) && list.length && !form?.getFieldValue?.(nameTenant)) {
|
||||||
try {
|
form?.setFieldsValue?.({ [nameTenant]: list[0].tenantId, [nameIncludeChildren]: true });
|
||||||
const level2 = await loadChildrenFor(list);
|
|
||||||
await loadChildrenFor(level2);
|
|
||||||
} catch {}
|
|
||||||
// 补齐根节点状态,随后过滤仅显示启用(status=1)
|
|
||||||
try {
|
|
||||||
await Promise.all((list || []).map(async (node: any) => {
|
|
||||||
if (node?.status == null && node?.tenantId) {
|
|
||||||
// 先看缓存,无则请求
|
|
||||||
const cached = getTenantDetailCache(node.tenantId);
|
|
||||||
if (typeof (cached as any)?.status !== 'undefined') {
|
|
||||||
node.status = (cached as any).status as any;
|
|
||||||
} else {
|
|
||||||
try {
|
|
||||||
const d: any = await tenantApi.getTenantDetail(node.tenantId);
|
|
||||||
node.status = (d?.data?.status ?? node.status);
|
|
||||||
setTenantDetailCache(node.tenantId, { status: node.status } as any);
|
|
||||||
} catch {}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}));
|
} catch {}
|
||||||
} catch {}
|
}
|
||||||
const filterEnabled = (nodes?: any[]): any[] => {
|
|
||||||
if (!Array.isArray(nodes)) return [];
|
|
||||||
const out: any[] = [];
|
|
||||||
for (const n of nodes) {
|
|
||||||
const v = (typeof (n as any)?.status === 'boolean') ? ((n as any).status ? 1 : 0) : (n as any)?.status;
|
|
||||||
if (v === 1) {
|
|
||||||
const item: any = { ...n };
|
|
||||||
if (Array.isArray((n as any).children)) item.children = filterEnabled((n as any).children);
|
|
||||||
out.push(item);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return out;
|
|
||||||
};
|
|
||||||
const filtered = filterEnabled(list || []);
|
|
||||||
setTree(filtered);
|
|
||||||
// 若当前选择的租户已被过滤(禁用),回退到第一个可用租户
|
|
||||||
try {
|
|
||||||
const selected = form?.getFieldValue?.(nameTenant);
|
|
||||||
const collectIds = (nodes?: any[]): string[] => {
|
|
||||||
const out: string[] = [];
|
|
||||||
if (!Array.isArray(nodes)) return out;
|
|
||||||
for (const n of nodes) {
|
|
||||||
if ((n as any)?.tenantId) out.push((n as any).tenantId);
|
|
||||||
if (Array.isArray((n as any).children)) out.push(...collectIds((n as any).children));
|
|
||||||
}
|
|
||||||
return out;
|
|
||||||
};
|
|
||||||
const ids = collectIds(filtered);
|
|
||||||
if (!selected || (ids.length && !ids.includes(selected))) {
|
|
||||||
form?.setFieldsValue?.({ [nameTenant]: ids[0], [nameIncludeChildren]: true });
|
|
||||||
}
|
|
||||||
} catch {}
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
message.warn('获取租户列表失败');
|
message.warn('获取租户列表失败');
|
||||||
} finally {
|
} finally {
|
||||||
@@ -166,8 +92,6 @@ const TenantSelector: React.FC<TenantSelectorProps> = ({
|
|||||||
})();
|
})();
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
// 不启用懒加载,依赖后端返回的完整树;仅在“仅单根无子”时补一层直系子级(见上方 useEffect)
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<Form.Item name={nameTenant} label={labelTenant} rules={rulesTenant as any}>
|
<Form.Item name={nameTenant} label={labelTenant} rules={rulesTenant as any}>
|
||||||
@@ -177,14 +101,14 @@ const TenantSelector: React.FC<TenantSelectorProps> = ({
|
|||||||
treeNodeFilterProp='title'
|
treeNodeFilterProp='title'
|
||||||
loading={loading}
|
loading={loading}
|
||||||
dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
|
dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
|
||||||
placeholder='选择租户(默认当前租户)'
|
placeholder='选择租户(含子租户)'
|
||||||
treeData={toTreeData(tree)}
|
treeData={toTreeData(tree)}
|
||||||
allowClear
|
allowClear
|
||||||
/>
|
/>
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
{hideIncludeChildren ? null : (
|
{hideIncludeChildren ? null : (
|
||||||
<Form.Item name={nameIncludeChildren} label={labelIncludeChildren} valuePropName='checked' initialValue={true}>
|
<Form.Item name={nameIncludeChildren} label={labelIncludeChildren} valuePropName='checked' initialValue={true}>
|
||||||
<Checkbox>包含下级租户</Checkbox>
|
<Checkbox>包含子租户</Checkbox>
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
)}
|
)}
|
||||||
</>
|
</>
|
||||||
@@ -192,3 +116,4 @@ const TenantSelector: React.FC<TenantSelectorProps> = ({
|
|||||||
};
|
};
|
||||||
|
|
||||||
export default TenantSelector;
|
export default TenantSelector;
|
||||||
|
|
||||||
|
|||||||
@@ -116,7 +116,7 @@ const BasicLayout: React.FC = (props: any) => {
|
|||||||
|
|
||||||
const rightContentRender = () => (
|
const rightContentRender = () => (
|
||||||
<Space size="middle">
|
<Space size="middle">
|
||||||
<Link to="/welcome" style={{ color: 'var(--text-primary)' }}>首页</Link>
|
{/*<Link to="/welcome" style={{ color: 'var(--text-primary)' }}>首页</Link>*/}
|
||||||
<ThemeSwitch mode={mode} onToggle={toggle} />
|
<ThemeSwitch mode={mode} onToggle={toggle} />
|
||||||
<Dropdown
|
<Dropdown
|
||||||
menu={{
|
menu={{
|
||||||
|
|||||||
@@ -281,16 +281,16 @@ const Welcome: React.FC = () => {
|
|||||||
// 订单状态:1. 待支付 2. 已取消 3. 支付成功 4. 设备执行中 5. 素材上传中 6. 素材上传完成 7. 用户已下载完成 8. 退款中 9. 退款成功 10. 退款失败
|
// 订单状态:1. 待支付 2. 已取消 3. 支付成功 4. 设备执行中 5. 素材上传中 6. 素材上传完成 7. 用户已下载完成 8. 退款中 9. 退款成功 10. 退款失败
|
||||||
// Tag 颜色使用 antd v4 预设色
|
// Tag 颜色使用 antd v4 预设色
|
||||||
const STATUS_OPTIONS: { value: number; label: string; color?: string }[] = [
|
const STATUS_OPTIONS: { value: number; label: string; color?: string }[] = [
|
||||||
{ value: 1, label: '待支付', color: 'gold' },
|
{ value: 0, label: '待支付' },
|
||||||
{ value: 2, label: '已取消' },
|
{ value: 1, label: '排队中', color: 'gold' },
|
||||||
{ value: 3, label: '支付成功', color: 'green' },
|
{ value: 2, label: '已取消', color: 'red'},
|
||||||
{ value: 4, label: '设备执行中', color: 'blue' },
|
{ value: 3, label: '设备执行完成', color: 'green' },
|
||||||
|
{ value: 4, label: '正在服务中', color: 'blue' },
|
||||||
{ value: 5, label: '素材上传中', color: 'geekblue' },
|
{ value: 5, label: '素材上传中', color: 'geekblue' },
|
||||||
{ value: 6, label: '素材上传完成', color: 'cyan' },
|
{ value: 6, label: '任务完成', color: 'purple' },
|
||||||
{ value: 7, label: '用户已下载完成', color: 'purple' },
|
{ value: 7, label: '退款中', color: 'orange' },
|
||||||
{ value: 8, label: '退款中', color: 'orange' },
|
{ value: 8, label: '退款成功', color: 'lime' },
|
||||||
{ value: 9, label: '退款成功', color: 'lime' },
|
{ value: 9, label: '退款失败', color: 'red' },
|
||||||
{ value: 10, label: '退款失败', color: 'red' },
|
|
||||||
];
|
];
|
||||||
|
|
||||||
const PAY_TYPE_OPTIONS: { value: number; label: string; color?: string }[] = [
|
const PAY_TYPE_OPTIONS: { value: number; label: string; color?: string }[] = [
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import React, { useEffect, useState } from 'react';
|
import React, { useEffect, useState } from 'react';
|
||||||
import { Modal, Tree, message } from 'antd';
|
import { Modal, Tree, message } from 'antd';
|
||||||
import { roleApi } from '@/services/role';
|
import { roleApi } from '@/services/role';
|
||||||
import { buildTree } from '@/utils/tree';
|
import { buildTree } from '@/utils/tree';
|
||||||
@@ -29,20 +29,20 @@ const AssignAuth: React.FC<AssignAuthProps> = ({ roleId, tenantId, open, onClose
|
|||||||
|
|
||||||
const handleOk = async () => {
|
const handleOk = async () => {
|
||||||
if (!roleId) return;
|
if (!roleId) return;
|
||||||
const hide = message.loading('淇濆瓨涓?..');
|
const hide = message.loading('保存中...');
|
||||||
try {
|
try {
|
||||||
await roleApi.assignMenu({ roleId, menuIds: checkedKeys });
|
await roleApi.assignMenu({ roleId, menuIds: checkedKeys });
|
||||||
message.success('鏉冮檺鍒嗛厤鎴愬姛');
|
message.success('权限分配成功');
|
||||||
onClose();
|
onClose();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
message.error('鏉冮檺鍒嗛厤澶辫触');
|
message.error('权限分配失败');
|
||||||
} finally {
|
} finally {
|
||||||
hide();
|
hide();
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Modal title="鏉冮檺鍒嗛厤" open={open} destroyOnClose onOk={handleOk} onCancel={onClose}>
|
<Modal title="权限分配" open={open} destroyOnClose onOk={handleOk} onCancel={onClose}>
|
||||||
<Tree
|
<Tree
|
||||||
defaultExpandAll
|
defaultExpandAll
|
||||||
checkable
|
checkable
|
||||||
@@ -56,4 +56,3 @@ const AssignAuth: React.FC<AssignAuthProps> = ({ roleId, tenantId, open, onClose
|
|||||||
|
|
||||||
export default AssignAuth;
|
export default AssignAuth;
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -16,7 +16,6 @@ const RolePage: React.FC = () => {
|
|||||||
const [current, setCurrent] = useState<RoleItem | undefined>(undefined);
|
const [current, setCurrent] = useState<RoleItem | undefined>(undefined);
|
||||||
|
|
||||||
// 以租户为主:通过 SearchBarPlus 内置租户选择器
|
// 以租户为主:通过 SearchBarPlus 内置租户选择器
|
||||||
|
|
||||||
const columns = [
|
const columns = [
|
||||||
{ dataIndex: 'index', valueType: 'indexBorder', width: 48 },
|
{ dataIndex: 'index', valueType: 'indexBorder', width: 48 },
|
||||||
{ title: '租户', dataIndex: 'tenantId', width: 160, search: false, render: (_: any, r: RoleItem) => (r as any)?.tenantName || (r as any)?.tenantId || '-' },
|
{ title: '租户', dataIndex: 'tenantId', width: 160, search: false, render: (_: any, r: RoleItem) => (r as any)?.tenantName || (r as any)?.tenantId || '-' },
|
||||||
@@ -148,3 +147,4 @@ const RolePage: React.FC = () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export default RolePage;
|
export default RolePage;
|
||||||
|
|
||||||
|
|||||||
@@ -80,10 +80,12 @@ const TenantTreeTable: React.FC<TenantTreeTableProps> = ({ data, loading, onAddC
|
|||||||
render: (_: any, rec: TenantTreeNode | undefined) => {
|
render: (_: any, rec: TenantTreeNode | undefined) => {
|
||||||
const record = (rec || ({} as TenantTreeNode));
|
const record = (rec || ({} as TenantTreeNode));
|
||||||
const hasId = !!(record as any)?.tenantId;
|
const hasId = !!(record as any)?.tenantId;
|
||||||
|
const typeVal = (record as any)?.tenantType;
|
||||||
|
const isDepartment = String(typeVal || '').toUpperCase() === 'DEPARTMENT';
|
||||||
return (
|
return (
|
||||||
<Space>
|
<Space>
|
||||||
<a onClick={() => hasId && onEdit?.(record)}>编辑</a>
|
<a onClick={() => hasId && onEdit?.(record)}>编辑</a>
|
||||||
{onAddChild ? <a onClick={() => hasId && onAddChild?.(record)}>新增下级</a> : null}
|
{onAddChild && !isDepartment ? <a onClick={() => hasId && onAddChild?.(record)}>新增下级</a> : null}
|
||||||
<Popconfirm title={`确认删除租户[${record?.tenantName ?? ''}]?`} onConfirm={() => hasId && onDelete?.(record)}>
|
<Popconfirm title={`确认删除租户[${record?.tenantName ?? ''}]?`} onConfirm={() => hasId && onDelete?.(record)}>
|
||||||
<a style={{ color: '#1677ff' }}>删除</a>
|
<a style={{ color: '#1677ff' }}>删除</a>
|
||||||
</Popconfirm>
|
</Popconfirm>
|
||||||
|
|||||||
@@ -36,131 +36,101 @@ const TenantManage: React.FC = () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const fetchTree = useCallback(async () => {
|
const fetchTree = useCallback(async () => {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
|
try {
|
||||||
|
// 1) 获取可访问租户树(作为根集合);无则回退当前租户
|
||||||
|
const res: any = await tenantApi.getAccessibleTenants();
|
||||||
|
let list: TenantTreeNode[] = [];
|
||||||
|
if (typeof res?.success !== "undefined") list = res.success ? (res.data || []) : [];
|
||||||
|
else if (Array.isArray(res)) list = res as TenantTreeNode[];
|
||||||
|
if (!list || list.length === 0) {
|
||||||
|
const cur: any = await tenantApi.getCurrentTenant();
|
||||||
|
if (cur?.success && cur?.data?.tenantId) {
|
||||||
|
list = [{ tenantId: cur.data.tenantId, tenantName: cur.data.tenantName } as any];
|
||||||
|
} else {
|
||||||
|
const stats: any = await tenantApi.getScopeStats();
|
||||||
|
const id = stats?.data?.currentTenantId;
|
||||||
|
if (id) list = [{ tenantId: id, tenantName: id } as any];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2) 补齐根节点缺失的必要字段
|
||||||
try {
|
try {
|
||||||
const res: any = await tenantApi.getAccessibleTenants();
|
await Promise.all((list || []).map(async (node: any) => {
|
||||||
let list: TenantTreeNode[] = [];
|
if (!node) return;
|
||||||
if (typeof res?.success !== "undefined") {
|
|
||||||
list = res.success ? (res.data || []) : [];
|
|
||||||
} else if (Array.isArray(res)) {
|
|
||||||
list = res as TenantTreeNode[];
|
|
||||||
}
|
|
||||||
if (!list || list.length === 0) {
|
|
||||||
// 回退:至少返回当前租户
|
|
||||||
const cur: any = await tenantApi.getCurrentTenant();
|
|
||||||
if (cur?.success && cur?.data?.tenantId) {
|
|
||||||
list = [{ tenantId: cur.data.tenantId, tenantName: cur.data.tenantName } as any];
|
|
||||||
} else {
|
|
||||||
const stats: any = await tenantApi.getScopeStats();
|
|
||||||
const id = stats?.data?.currentTenantId;
|
|
||||||
if (id) list = [{ tenantId: id, tenantName: id } as any];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// 若只有根节点且无子节点,尝试加载一层子租户以展示层级
|
|
||||||
if (list && list.length === 1 && !Array.isArray((list[0] as any).children)) {
|
|
||||||
try {
|
try {
|
||||||
const parentId = (list[0] as any).tenantId;
|
if (node.tenantType == null || node.status == null || node.contactPerson == null || node.contactPhone == null) {
|
||||||
const resPage: any = await tenantApi.getTenantList({ parentTenantId: parentId, status: (statusFilter === 'all' ? undefined : statusFilter) as any, current: 1, pageSize: 1000 } as any);
|
const detail: any = await tenantApi.getTenantDetail(node.tenantId);
|
||||||
const children = resPage?.data?.data || [];
|
const d = detail?.data || {};
|
||||||
if (children && children.length) {
|
if (node.tenantType == null) node.tenantType = d.tenantType;
|
||||||
(list[0] as any).children = children.map((c: any) => ({ tenantId: c.tenantId, tenantName: c.tenantName, tenantType: c.tenantType, status: c.status, contactPerson: c.contactPerson, contactPhone: c.contactPhone }));
|
if (node.status == null) node.status = d.status;
|
||||||
|
if (node.contactPerson == null) node.contactPerson = d.contactPerson;
|
||||||
|
if (node.contactPhone == null) node.contactPhone = d.contactPhone;
|
||||||
}
|
}
|
||||||
} catch {}
|
} catch {}
|
||||||
}
|
}));
|
||||||
// 补充每个根的一层直接子租户,便于默认展开时可见
|
} catch {}
|
||||||
try {
|
|
||||||
await Promise.all(
|
// 3) 以 BFS 方式递归加载所有层级子租户(直到叶子)
|
||||||
(list || []).map(async (node: any) => {
|
const loadChildren = async (pid: string): Promise<TenantTreeNode[]> => {
|
||||||
if (!node) return;
|
const resp: any = await tenantApi.getTenantList({ parentTenantId: pid, status: (statusFilter === 'all' ? undefined : statusFilter) as any, current: 1, pageSize: 1000 } as any);
|
||||||
// 顶层节点缺失类型/状态/联系人信息时,补充详情
|
const items = resp?.data?.data || [];
|
||||||
try {
|
return (items || []).map((c: any) => ({
|
||||||
if (node.tenantType == null || node.status == null || node.contactPerson == null || node.contactPhone == null) {
|
tenantId: c.tenantId,
|
||||||
const detail: any = await tenantApi.getTenantDetail(node.tenantId);
|
tenantName: c.tenantName,
|
||||||
const d = detail?.data || {};
|
tenantType: c.tenantType,
|
||||||
if (node.tenantType == null) node.tenantType = d.tenantType;
|
status: c.status,
|
||||||
if (node.status == null) node.status = d.status;
|
contactPerson: c.contactPerson,
|
||||||
if (node.contactPerson == null) node.contactPerson = d.contactPerson;
|
contactPhone: c.contactPhone,
|
||||||
if (node.contactPhone == null) node.contactPhone = d.contactPhone;
|
} as any));
|
||||||
}
|
};
|
||||||
} catch {}
|
|
||||||
// 确保至少补一层孩子,方便默认展开后可见
|
let current: any[] = list as any[];
|
||||||
if (!Array.isArray(node.children) || node.children.length === 0) {
|
while (Array.isArray(current) && current.length) {
|
||||||
const resp: any = await tenantApi.getTenantList({ parentTenantId: node.tenantId, status: (statusFilter === 'all' ? undefined : statusFilter) as any, current: 1, pageSize: 1000 } as any);
|
const next: any[] = [];
|
||||||
const children = resp?.data?.data || [];
|
await Promise.all(current.map(async (node: any) => {
|
||||||
if (children && children.length) {
|
if (!node?.tenantId) return;
|
||||||
node.children = children.map((c: any) => ({ tenantId: c.tenantId, tenantName: c.tenantName, tenantType: c.tenantType, status: c.status, contactPerson: c.contactPerson, contactPhone: c.contactPhone }));
|
if (!Array.isArray(node.children) || node.children.length === 0) {
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
);
|
|
||||||
} catch {}
|
|
||||||
// 递进加载至第三级,保证三级部门可见
|
|
||||||
const loadChildrenFor = async (nodes?: any[]): Promise<any[]> => {
|
|
||||||
const resultChildren: any[] = [];
|
|
||||||
if (!Array.isArray(nodes)) return resultChildren;
|
|
||||||
await Promise.all(nodes.map(async (node: any) => {
|
|
||||||
if (!node) return;
|
|
||||||
// 再次兜底补全基础信息
|
|
||||||
try {
|
try {
|
||||||
if (node.tenantType == null || node.status == null || node.contactPerson == null || node.contactPhone == null) {
|
const children = await loadChildren(node.tenantId);
|
||||||
const detail: any = await tenantApi.getTenantDetail(node.tenantId);
|
if (children && children.length) node.children = children as any;
|
||||||
const d = detail?.data || {};
|
|
||||||
if (node.tenantType == null) node.tenantType = d.tenantType;
|
|
||||||
if (node.status == null) node.status = d.status;
|
|
||||||
if (node.contactPerson == null) node.contactPerson = d.contactPerson;
|
|
||||||
if (node.contactPhone == null) node.contactPhone = d.contactPhone;
|
|
||||||
}
|
|
||||||
} catch {}
|
} catch {}
|
||||||
const needLoad = !Array.isArray(node.children) || node.children.length === 0;
|
}
|
||||||
if (needLoad) {
|
if (Array.isArray(node.children) && node.children.length) next.push(...node.children);
|
||||||
try {
|
}));
|
||||||
const resp: any = await tenantApi.getTenantList({ parentTenantId: node.tenantId, status: (statusFilter === 'all' ? undefined : statusFilter) as any, current: 1, pageSize: 1000 } as any);
|
current = next;
|
||||||
const children = resp?.data?.data || [];
|
}
|
||||||
if (children && children.length) {
|
|
||||||
node.children = children.map((c: any) => ({ tenantId: c.tenantId, tenantName: c.tenantName, tenantType: c.tenantType, status: c.status, contactPerson: c.contactPerson, contactPhone: c.contactPhone }));
|
// 4) 按状态筛选(全部/启用/停用)
|
||||||
}
|
const filterTreeByStatus = (nodes?: any[]): any[] => {
|
||||||
} catch {}
|
if (statusFilter === 'all') return Array.isArray(nodes) ? nodes : [];
|
||||||
|
const want = statusFilter;
|
||||||
|
const walk = (arr?: any[]): any[] => {
|
||||||
|
if (!Array.isArray(arr)) return [];
|
||||||
|
const res: any[] = [];
|
||||||
|
for (const n of arr) {
|
||||||
|
const v = (typeof (n as any)?.status === 'boolean') ? ((n as any).status ? 1 : 0) : (n as any)?.status;
|
||||||
|
if (v === want) {
|
||||||
|
const item: any = { ...n };
|
||||||
|
if (Array.isArray((n as any).children)) item.children = walk((n as any).children);
|
||||||
|
res.push(item);
|
||||||
|
} else if (Array.isArray((n as any).children)) {
|
||||||
|
const sub = walk((n as any).children);
|
||||||
|
if (sub.length) res.push(...sub);
|
||||||
}
|
}
|
||||||
if (Array.isArray(node.children)) resultChildren.push(...node.children);
|
}
|
||||||
}));
|
return res;
|
||||||
return resultChildren;
|
|
||||||
};
|
};
|
||||||
|
return walk(nodes);
|
||||||
|
};
|
||||||
|
|
||||||
try {
|
const finalList = filterTreeByStatus(list);
|
||||||
const level2 = await loadChildrenFor(list);
|
setTreeCache(list);
|
||||||
await loadChildrenFor(level2);
|
setData(finalList);
|
||||||
} catch {}
|
} catch (e) {
|
||||||
|
message.error("获取租户数据失败");
|
||||||
// 按状态筛选(仅当选择启用或停用时)
|
} finally { setLoading(false); }
|
||||||
const filterTreeByStatus = (nodes?: any[]): any[] => {
|
}, [statusFilter]);
|
||||||
if (statusFilter === 'all') return Array.isArray(nodes) ? nodes : [];
|
|
||||||
const want = statusFilter;
|
|
||||||
const walk = (arr?: any[]): any[] => {
|
|
||||||
if (!Array.isArray(arr)) return [];
|
|
||||||
const res: any[] = [];
|
|
||||||
for (const n of arr) {
|
|
||||||
const v = (typeof (n as any)?.status === 'boolean') ? ((n as any).status ? 1 : 0) : (n as any)?.status;
|
|
||||||
if (v === want) {
|
|
||||||
const item: any = { ...n };
|
|
||||||
if (Array.isArray((n as any).children)) item.children = walk((n as any).children);
|
|
||||||
res.push(item);
|
|
||||||
} else if (Array.isArray((n as any).children)) {
|
|
||||||
const sub = walk((n as any).children);
|
|
||||||
if (sub.length) res.push(...sub);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return res;
|
|
||||||
};
|
|
||||||
return walk(nodes);
|
|
||||||
};
|
|
||||||
|
|
||||||
const finalList = filterTreeByStatus(list);
|
|
||||||
setTreeCache(list);
|
|
||||||
setData(finalList);
|
|
||||||
} catch (e) {
|
|
||||||
message.error("获取租户数据失败");
|
|
||||||
} finally { setLoading(false); }
|
|
||||||
}, [statusFilter]);
|
|
||||||
|
|
||||||
|
|
||||||
useEffect(() => { fetchTree(); }, [fetchTree]);
|
useEffect(() => { fetchTree(); }, [fetchTree]);
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import React from 'react';
|
import React from 'react';
|
||||||
import { ModalForm, ProForm, ProFormRadio, ProFormSelect, ProFormText, ProFormTextArea } from '@ant-design/pro-components';
|
import { ModalForm, ProForm, ProFormRadio, ProFormSelect, ProFormText, ProFormTextArea, ProFormDependency } from '@ant-design/pro-components';
|
||||||
import { systemApi, UserItem } from '@/services/system';
|
import { systemApi, UserItem } from '@/services/system';
|
||||||
import TenantSelector from '@/components/ui/TenantSelector';
|
import TenantSelector from '@/components/ui/TenantSelector';
|
||||||
|
|
||||||
@@ -14,13 +14,26 @@ export interface UserFormProps {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const UserForm: React.FC<UserFormProps> = ({ visible, title, initialValues, onVisibleChange, onFinish, showCompany = true }) => {
|
const UserForm: React.FC<UserFormProps> = ({ visible, title, initialValues, onVisibleChange, onFinish, showCompany = true }) => {
|
||||||
|
// 统一初始值:补充 type 默认值;将 roles/roleId 映射为 roleIds(字符串数组)
|
||||||
|
const mergedInitial = React.useMemo(() => {
|
||||||
|
const base: any = { type: 'BACKEND', ...(initialValues || {}) };
|
||||||
|
// 兼容后端仅返回 tenantId 的场景:用于初始化“所属租户”和角色下拉
|
||||||
|
if (!base.company && base.tenantId) base.company = base.tenantId;
|
||||||
|
if (!base.roleIds) {
|
||||||
|
if (Array.isArray(base.roles)) base.roleIds = base.roles.map((r: any) => String(r.id));
|
||||||
|
else if (typeof base.roleId === 'string') base.roleIds = String(base.roleId).split(',').map((s) => String(s).trim()).filter(Boolean);
|
||||||
|
}
|
||||||
|
if (base.roleIds) base.roleIds = (Array.isArray(base.roleIds) ? base.roleIds : [base.roleIds]).map((v: any) => String(v));
|
||||||
|
return base;
|
||||||
|
}, [initialValues]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ModalForm<UserItem & { company?: string; type?: string }>
|
<ModalForm<UserItem & { company?: string; type?: string }>
|
||||||
title={title}
|
title={title}
|
||||||
visible={visible}
|
visible={visible}
|
||||||
onVisibleChange={onVisibleChange}
|
onVisibleChange={onVisibleChange}
|
||||||
onFinish={onFinish}
|
onFinish={onFinish}
|
||||||
initialValues={{ type: 'BACKEND', ...(initialValues || {}) }}
|
initialValues={mergedInitial}
|
||||||
modalProps={{ destroyOnClose: true }}
|
modalProps={{ destroyOnClose: true }}
|
||||||
>
|
>
|
||||||
<ProForm.Group>
|
<ProForm.Group>
|
||||||
@@ -28,15 +41,39 @@ const UserForm: React.FC<UserFormProps> = ({ visible, title, initialValues, onVi
|
|||||||
<ProFormText name="nickname" label="用户昵称" rules={[{ required: true, message: '用户昵称不能为空' }]} />
|
<ProFormText name="nickname" label="用户昵称" rules={[{ required: true, message: '用户昵称不能为空' }]} />
|
||||||
<ProFormText name="mobile" label="手机号" rules={[{ required: true, message: '手机号不能为空' }]} />
|
<ProFormText name="mobile" label="手机号" rules={[{ required: true, message: '手机号不能为空' }]} />
|
||||||
</ProForm.Group>
|
</ProForm.Group>
|
||||||
<ProFormRadio.Group name="sex" label="性别" options={[{ label: '男', value: 0 }, { label: '女', value: 1 }]} />
|
<ProFormRadio.Group name="sex" label="性别" options={[{ label: '女', value: 0 }, { label: '男', value: 1 }]} />
|
||||||
<ProFormSelect name="roleIds" label="角色" mode="multiple" request={systemApi.roles} placeholder="选择角色" />
|
|
||||||
|
|
||||||
|
{/* 先选择租户,再选择角色 */}
|
||||||
{showCompany ? (
|
{showCompany ? (
|
||||||
<TenantSelector nameTenant="company" labelTenant="所属租户" hideIncludeChildren />
|
<TenantSelector
|
||||||
|
nameTenant="company"
|
||||||
|
labelTenant="所属租户"
|
||||||
|
hideIncludeChildren
|
||||||
|
rulesTenant={[{ required: true, message: '请选择所属租户' }]}
|
||||||
|
suppressAutoSelect
|
||||||
|
disableFetchCurrentTenant
|
||||||
|
/>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
|
<ProFormDependency name={["company"]}>
|
||||||
|
{({ company }) => (
|
||||||
|
<ProFormSelect
|
||||||
|
key={company || 'none'}
|
||||||
|
params={{ tenantId: company || (initialValues as any)?.company || (initialValues as any)?.tenantId }}
|
||||||
|
name="roleIds"
|
||||||
|
label="角色"
|
||||||
|
mode="multiple"
|
||||||
|
request={async (p: any) => systemApi.roles(p?.tenantId)}
|
||||||
|
placeholder={company ? '选择角色' : '请先选择所属租户'}
|
||||||
|
disabled={!company}
|
||||||
|
rules={[{ required: true, message: '请选择角色(如无可选项,请先到角色管理创建该租户的角色)' }]}
|
||||||
|
fieldProps={{ showSearch: true, optionFilterProp: 'label' }}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</ProFormDependency>
|
||||||
|
|
||||||
<ProFormTextArea name="remark" label="备注" />
|
<ProFormTextArea name="remark" label="备注" />
|
||||||
{/* 类型固定为系统用户,默认也会按 BACKEND 新建 */}
|
{/* 类型固定为系统用户,默认也会以 BACKEND 新建 */}
|
||||||
<ProFormText name="type" label="用户类型" initialValue="BACKEND" disabled hidden />
|
<ProFormText name="type" label="用户类型" initialValue="BACKEND" disabled hidden />
|
||||||
</ModalForm>
|
</ModalForm>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -88,9 +88,10 @@ export const systemApi = {
|
|||||||
},
|
},
|
||||||
|
|
||||||
// 角色列表(下拉)
|
// 角色列表(下拉)
|
||||||
roles: async () => {
|
// 角色列表(可按租户筛选)
|
||||||
const res = await request('/api-user/roles', { method: 'GET' });
|
roles: async (tenantId?: string) => {
|
||||||
|
const res = await request('/api-user/roles', { method: 'GET', params: tenantId ? { tenantId } : {} });
|
||||||
const list = (res as any).data || [];
|
const list = (res as any).data || [];
|
||||||
return list.map((r: any) => ({ label: r.name, value: r.id }));
|
return Array.isArray(list) ? list.map((r: any) => ({ label: r.name, value: String(r.id) })) : [];
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
Reference in New Issue
Block a user