feat(react-web-next): 新增.editorconfig和.prettierrc配置文件,添加public/.gitkeep占位文件

This commit is contained in:
2025-09-23 10:32:35 +08:00
parent 10ddfd6f75
commit 408b500b6a
199 changed files with 16850 additions and 34874 deletions
@@ -0,0 +1,166 @@
package com.central.user.controller;
import com.central.common.model.CodeEnum;
import com.central.common.model.Result;
import com.central.common.model.Tenant;
import com.central.common.model.TenantInfo;
import com.central.common.service.ITenantHierarchyService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 租户层级管理接口
* 对应前端 /tenant/hierarchy/* 约定
*/
@Slf4j
@RestController
@RequestMapping("/tenant/hierarchy")
@Tag(name = "租户层级管理")
public class TenantHierarchyController {
@Autowired
private ITenantHierarchyService tenantHierarchyService;
/**
* 创建租户
*/
@PostMapping("/create")
@Operation(summary = "创建租户")
public Result<TenantInfo> createTenant(@RequestBody TenantInfo body) {
if (body == null || !StringUtils.hasText(body.getTenantId())) {
return Result.failed("租户ID不能为空");
}
if (!tenantHierarchyService.validateTenantRelation(body.getTenantId(), body.getParentTenantId())) {
return Result.failed("租户关系不合法,检测到可能的循环引用");
}
Tenant tenant = toTenant(body);
Result<Tenant> created = tenantHierarchyService.createTenant(tenant);
if (created.getResp_code() != null && created.getResp_code().equals(CodeEnum.SUCCESS.getCode())) {
return Result.succeed(toTenantInfo(created.getData()), "创建成功");
}
return Result.failed(created.getResp_msg() != null ? created.getResp_msg() : "创建失败");
}
/**
* 更新租户
*/
@PutMapping("/update")
@Operation(summary = "更新租户")
public Result<TenantInfo> updateTenant(@RequestBody TenantInfo body) {
if (body == null || !StringUtils.hasText(body.getTenantId())) {
return Result.failed("租户ID不能为空");
}
if (!tenantHierarchyService.validateTenantRelation(body.getTenantId(), body.getParentTenantId())) {
return Result.failed("租户关系不合法,检测到可能的循环引用");
}
Tenant tenant = toTenant(body);
Result<Tenant> updated = tenantHierarchyService.updateTenant(tenant);
if (updated.getResp_code() != null && updated.getResp_code().equals(CodeEnum.SUCCESS.getCode())) {
return Result.succeed(toTenantInfo(updated.getData()), "更新成功");
}
return Result.failed(updated.getResp_msg() != null ? updated.getResp_msg() : "更新失败");
}
/**
* 删除租户(软删除)
*/
@DeleteMapping("/delete")
@Operation(summary = "删除租户(软删除)")
public Result<Boolean> deleteTenant(
@Parameter(description = "租户ID", required = true)
@RequestParam String tenantId) {
return tenantHierarchyService.deleteTenant(tenantId);
}
/**
* 获取租户列表(分页)
* 前端已将 current/pageSize 转换为 page/size
*/
@GetMapping("/list")
@Operation(summary = "获取租户列表(分页)")
public Result<Map<String, Object>> listTenants(
@RequestParam(required = false) String parentTenantId,
@RequestParam(required = false) String tenantName,
@RequestParam(required = false) Integer status,
@RequestParam(required = false) Integer page,
@RequestParam(required = false) Integer size) {
Result<List<TenantInfo>> res = tenantHierarchyService.getTenantList(parentTenantId, tenantName, status, page, size);
Map<String, Object> payload = new HashMap<>();
List<TenantInfo> list = res.getData();
payload.put("data", list);
// 由于服务层暂未返回 total,这里先以当前页条目数代替;后续可在服务层补充总数返回
payload.put("total", list != null ? list.size() : 0);
payload.put("success", res.getResp_code() != null && res.getResp_code().equals(CodeEnum.SUCCESS.getCode()));
if (payload.get("success").equals(Boolean.TRUE)) {
return Result.succeed(payload);
}
return Result.failed(payload, res.getResp_msg());
}
/**
* 获取租户详情
*/
@GetMapping("/detail/{tenantId}")
@Operation(summary = "获取租户详情")
public Result<TenantInfo> getTenantDetail(
@Parameter(description = "租户ID", required = true)
@PathVariable("tenantId") String tenantId) {
TenantInfo info = tenantHierarchyService.getTenantInfo(tenantId);
if (info == null) {
return Result.failed("租户不存在");
}
return Result.succeed(info);
}
// ===== 私有方法:对象转换 =====
private Tenant toTenant(TenantInfo info) {
if (info == null) return null;
Tenant t = new Tenant();
t.setTenantId(info.getTenantId());
t.setTenantName(info.getTenantName());
t.setParentTenantId(info.getParentTenantId());
t.setTenantLevel(info.getTenantLevel());
t.setTenantPath(info.getTenantPath());
t.setTenantType(info.getTenantType());
t.setTenantCode(info.getTenantCode());
t.setContactPerson(info.getContactPerson());
t.setContactPhone(info.getContactPhone());
t.setAddress(info.getAddress());
t.setDescription(info.getDescription());
t.setStatus(info.getStatus());
t.setCreatorId(info.getCreatorId());
return t;
}
private TenantInfo toTenantInfo(Tenant t) {
if (t == null) return null;
return TenantInfo.builder()
.tenantId(t.getTenantId())
.tenantName(t.getTenantName())
.parentTenantId(t.getParentTenantId())
.tenantLevel(t.getTenantLevel())
.tenantPath(t.getTenantPath())
.tenantType(t.getTenantType())
.tenantCode(t.getTenantCode())
.contactPerson(t.getContactPerson())
.contactPhone(t.getContactPhone())
.address(t.getAddress())
.description(t.getDescription())
.status(t.getStatus())
.creatorId(t.getCreatorId())
.build();
}
}
@@ -0,0 +1,183 @@
package com.central.user.controller;
import com.central.common.context.LoginUserContextHolder;
import com.central.common.model.LoginAppUser;
import com.central.common.model.Result;
import com.central.common.model.TenantInfo;
import com.central.common.model.TenantTreeNode;
import com.central.common.service.ITenantHierarchyService;
import com.central.common.service.UserTenantSelectionService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 租户切换管理控制器
*/
@RestController
@RequestMapping("/tenant")
@Tag(name = "租户管理")
@Slf4j
public class TenantSwitchController {
@Autowired
private ITenantHierarchyService tenantHierarchyService;
@Autowired(required = false)
private UserTenantSelectionService userTenantSelectionService;
/**
* 获取用户可访问的租户树
*/
@GetMapping("/accessible")
@Operation(summary = "获取可访问租户列表")
public Result<List<TenantTreeNode>> getAccessibleTenants() {
try {
LoginAppUser user = LoginUserContextHolder.getUser();
if (user == null) {
return Result.failed("用户未登录");
}
if (!isCanSwitchTenant(user)) {
return Result.failed("用户无租户切换权限");
}
List<String> accessibleTenantIds = getAccessibleTenantIds(user);
if (accessibleTenantIds.isEmpty()) {
return Result.failed("用户无可访问的租户");
}
List<TenantTreeNode> tenantTree = tenantHierarchyService.buildTenantTree(accessibleTenantIds);
return Result.succeed(tenantTree);
} catch (Exception e) {
log.error("获取可访问租户列表失败: {}", e.getMessage());
return Result.failed("获取可访问租户列表失败: " + e.getMessage());
}
}
/**
* 切换当前查询租户
*/
@PostMapping("/switch-query")
@Operation(summary = "切换当前查询租户")
public Result<String> switchTenant(
@Parameter(description = "目标租户ID", required = true)
@RequestParam String tenantId) {
try {
// 设置当前租户
LoginUserContextHolder.setCurrentTenant(tenantId);
// 持久化选择(避免依赖请求头),后续请求基于Authorization恢复
LoginAppUser user = LoginUserContextHolder.getUser();
if (userTenantSelectionService != null && user != null) {
userTenantSelectionService.setCurrentTenant(user.getId(), tenantId);
}
log.info("用户 {} 切换到租户 {}", user != null ? user.getUsername() : "-", tenantId);
return Result.succeed("成功");
} catch (SecurityException e) {
log.warn("租户切换失败: {}", e.getMessage());
return Result.failed(e.getMessage());
} catch (Exception e) {
log.error("租户切换异常: {}", e.getMessage());
return Result.failed("租户切换异常: " + e.getMessage());
}
}
/**
* 获取当前租户信息
*/
@GetMapping("/current/info")
@Operation(summary = "获取当前租户信息")
public Result<TenantInfo> getCurrentTenant() {
try {
String currentTenantId = LoginUserContextHolder.getCurrentTenantId();
if (!StringUtils.hasText(currentTenantId)) {
return Result.failed("未获取到当前租户信息");
}
TenantInfo tenantInfo = tenantHierarchyService.getTenantInfo(currentTenantId);
if (tenantInfo == null) {
return Result.failed("租户信息不存在");
}
return Result.succeed(tenantInfo);
} catch (Exception e) {
log.error("获取当前租户信息失败: {}", e.getMessage());
return Result.failed("获取当前租户信息失败: " + e.getMessage());
}
}
/**
* 获取当前查询范围统计
*/
@GetMapping("/scope/stats")
@Operation(summary = "获取当前查询范围统计")
public Result<Map<String, Object>> getCurrentScopeStats() {
try {
LoginAppUser user = LoginUserContextHolder.getUser();
if (user == null) {
return Result.failed("用户未登录");
}
String currentTenantId = LoginUserContextHolder.getCurrentTenantId();
List<String> queryTenantIds = LoginUserContextHolder.getCurrentQueryTenantIds();
Map<String, Object> stats = new HashMap<>();
stats.put("currentTenantId", currentTenantId);
stats.put("queryTenantCount", queryTenantIds.size());
stats.put("queryTenantIds", queryTenantIds);
stats.put("canSwitchTenant", LoginUserContextHolder.isManagementUser());
stats.put("userType", LoginUserContextHolder.getUserType());
stats.put("timestamp", System.currentTimeMillis());
return Result.succeed(stats);
} catch (Exception e) {
log.error("获取查询范围统计失败: {}", e.getMessage());
return Result.failed("获取查询范围统计失败: " + e.getMessage());
}
}
/**
* 重置当前租户为用户默认租户
*/
@PostMapping("/reset")
@Operation(summary = "重置为默认租户")
public Result<String> resetToDefaultTenant() {
try {
LoginUserContextHolder.resetToDefaultTenant();
LoginAppUser user = LoginUserContextHolder.getUser();
if (userTenantSelectionService != null && user != null) {
userTenantSelectionService.clearCurrentTenant(user.getId());
}
log.info("用户 {} 重置为默认租户", user != null ? user.getUsername() : "-");
return Result.succeed("成功");
} catch (Exception e) {
log.error("重置默认租户失败: {}", e.getMessage());
return Result.failed("重置默认租户失败: " + e.getMessage());
}
}
// ===== 私有方法 =====
private boolean isCanSwitchTenant(LoginAppUser user) {
return user.isCanSwitchTenant();
}
private List<String> getAccessibleTenantIds(LoginAppUser user) {
String userTenantId = getDefaultTenantId(user);
if (StringUtils.hasText(userTenantId)) {
if (isCanSwitchTenant(user)) {
return tenantHierarchyService.getAllSubTenantIds(userTenantId);
} else {
return List.of(userTenantId);
}
}
return List.of();
}
private String getDefaultTenantId(LoginAppUser user) {
Object company = user.getAttributes().get("company");
return company != null ? company.toString() : null;
}
}
@@ -1,6 +1,7 @@
package com.central.user.feign;
import com.central.common.model.Result;
import com.central.user.feign.fallback.DeviceCenterServiceFallback;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
@@ -1,6 +1,7 @@
package com.central.user.feign;
import com.central.common.model.Result;
import com.central.user.feign.fallback.OrderCenterServiceFallback;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
@@ -1,6 +1,7 @@
package com.central.user.feign;
import com.central.common.model.Result;
import com.central.user.feign.fallback.TenantServiceFallback;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.*;
@@ -1,6 +1,7 @@
package com.central.user.feign;
package com.central.user.feign.fallback;
import com.central.common.model.Result;
import com.central.user.feign.DeviceCenterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
@@ -1,6 +1,7 @@
package com.central.user.feign;
package com.central.user.feign.fallback;
import com.central.common.model.Result;
import com.central.user.feign.OrderCenterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
@@ -1,10 +1,10 @@
package com.central.user.feign;
package com.central.user.feign.fallback;
import com.central.common.model.Result;
import com.central.user.feign.TenantService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
/**
@@ -0,0 +1,149 @@
package com.central.user.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.central.common.model.Tenant;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.List;
/**
* 租户层级管理Mapper
*
* @author zlt
* @date 2024-12-19
*/
@Mapper
public interface TenantHierarchyMapper extends BaseMapper<Tenant> {
/**
* 根据租户ID查询租户信息
*
* @param tenantId 租户ID
* @return 租户信息
*/
@Select("SELECT * FROM sys_tenant WHERE tenant_id = #{tenantId} AND status = 1")
Tenant selectByTenantId(@Param("tenantId") String tenantId);
/**
* 根据租户ID列表查询租户信息
*
* @param tenantIds 租户ID列表
* @return 租户信息列表
*/
@Select("<script>" +
"SELECT * FROM sys_tenant " +
"WHERE tenant_id IN " +
"<foreach collection='tenantIds' item='tenantId' open='(' separator=',' close=')'>" +
"#{tenantId}" +
"</foreach> " +
"AND status = 1 " +
"ORDER BY tenant_level, tenant_id" +
"</script>")
List<Tenant> selectByTenantIds(@Param("tenantIds") List<String> tenantIds);
/**
* 查询指定租户的所有子租户ID(递归)
*
* @param parentTenantId 父租户ID
* @return 子租户ID列表
*/
@Select("SELECT tenant_id FROM sys_tenant " +
"WHERE tenant_path LIKE CONCAT(" +
" (SELECT tenant_path FROM sys_tenant WHERE tenant_id = #{parentTenantId}), " +
" '%'" +
") " +
"AND status = 1 " +
"ORDER BY tenant_level, tenant_id")
List<String> selectSubTenantIds(@Param("parentTenantId") String parentTenantId);
/**
* 查询指定租户的直接子租户
*
* @param parentTenantId 父租户ID
* @return 直接子租户列表
*/
@Select("SELECT * FROM sys_tenant " +
"WHERE parent_tenant_id = #{parentTenantId} " +
"AND status = 1 " +
"ORDER BY tenant_id")
List<Tenant> selectDirectChildren(@Param("parentTenantId") String parentTenantId);
/**
* 检查租户ID是否存在
*
* @param tenantId 租户ID
* @return 存在数量
*/
@Select("SELECT COUNT(*) FROM sys_tenant WHERE tenant_id = #{tenantId}")
int existsByTenantId(@Param("tenantId") String tenantId);
/**
* 查询租户路径
*
* @param tenantId 租户ID
* @return 租户路径
*/
@Select("SELECT tenant_path FROM sys_tenant WHERE tenant_id = #{tenantId} AND status = 1")
String selectTenantPath(@Param("tenantId") String tenantId);
/**
* 分页查询租户列表
*
* @param parentTenantId 父租户ID(可选)
* @param tenantName 租户名称(模糊查询,可选)
* @param status 状态(可选)
* @param offset 偏移量
* @param limit 限制数量
* @return 租户列表
*/
@Select("<script>" +
"SELECT t.*, " +
" (SELECT COUNT(*) FROM sys_tenant c WHERE c.parent_tenant_id = t.tenant_id AND c.status = 1) as children_count, " +
" (SELECT tenant_name FROM sys_tenant p WHERE p.tenant_id = t.parent_tenant_id) as parent_tenant_name " +
"FROM sys_tenant t " +
"WHERE 1=1 " +
"<if test='parentTenantId != null and parentTenantId != \"\"'>" +
" AND t.parent_tenant_id = #{parentTenantId} " +
"</if>" +
"<if test='tenantName != null and tenantName != \"\"'>" +
" AND t.tenant_name LIKE CONCAT('%', #{tenantName}, '%') " +
"</if>" +
"<if test='status != null'>" +
" AND t.status = #{status} " +
"</if>" +
"ORDER BY t.tenant_level, t.tenant_id " +
"LIMIT #{offset}, #{limit}" +
"</script>")
List<Tenant> selectTenantList(@Param("parentTenantId") String parentTenantId,
@Param("tenantName") String tenantName,
@Param("status") Integer status,
@Param("offset") Integer offset,
@Param("limit") Integer limit);
/**
* 查询租户总数
*
* @param parentTenantId 父租户ID(可选)
* @param tenantName 租户名称(模糊查询,可选)
* @param status 状态(可选)
* @return 总数
*/
@Select("<script>" +
"SELECT COUNT(*) FROM sys_tenant t " +
"WHERE 1=1 " +
"<if test='parentTenantId != null and parentTenantId != \"\"'>" +
" AND t.parent_tenant_id = #{parentTenantId} " +
"</if>" +
"<if test='tenantName != null and tenantName != \"\"'>" +
" AND t.tenant_name LIKE CONCAT('%', #{tenantName}, '%') " +
"</if>" +
"<if test='status != null'>" +
" AND t.status = #{status} " +
"</if>" +
"</script>")
long countTenantList(@Param("parentTenantId") String parentTenantId,
@Param("tenantName") String tenantName,
@Param("status") Integer status);
}
@@ -20,7 +20,7 @@ public interface ISysRoleUserService extends ISuperService<SysRoleUser> {
* @param userId
* @return
*/
List<SysRole> findRolesByUserId(Long userId);
List<SysRole> findRolesByUserId(Long userId);
/**
* 根据用户ids 获取
@@ -16,7 +16,7 @@ import java.util.List;
*/
@Slf4j
@Service
public class SysRoleUserServiceImpl extends SuperServiceImpl<SysUserRoleMapper, SysRoleUser> implements ISysRoleUserService {
public class SysRoleUserServiceImpl extends SuperServiceImpl<SysUserRoleMapper, SysRoleUser> implements ISysRoleUserService {
@Resource
private SysUserRoleMapper sysUserRoleMapper;
@@ -6,6 +6,7 @@ import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.central.common.constant.CommonConstant;
import com.central.common.context.LoginUserContextHolder;
import com.central.common.datascope.annotation.IgnoreTenantScope;
import com.central.common.lock.DistributedLock;
import com.central.common.model.PageResult;
import com.central.common.model.Result;
@@ -240,6 +241,7 @@ public class SysUserServiceImpl extends SuperServiceImpl<SysUserMapper, SysUser>
}
@Override
@IgnoreTenantScope
public List<SysRole> findRolesByUserId(Long userId) {
return roleUserService.findRolesByUserId(userId);
}
@@ -0,0 +1,399 @@
package com.central.user.service.impl;
import com.central.common.context.LoginUserContextHolder;
import com.central.common.model.Result;
import com.central.common.model.Tenant;
import com.central.common.model.TenantInfo;
import com.central.common.model.TenantTreeNode;
import com.central.common.service.ITenantHierarchyService;
import com.central.user.mapper.TenantHierarchyMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;
/**
* 租户层级管理服务实现
*
* @author zlt
* @date 2024-12-19
*/
@Slf4j
@Service
public class TenantHierarchyServiceImpl implements ITenantHierarchyService {
@Autowired
private TenantHierarchyMapper tenantHierarchyMapper;
private static final String CACHE_KEY_PREFIX = "tenant:hierarchy:";
@Override
@Cacheable(value = "tenant:hierarchy", key = "#parentTenantId")
public List<String> getAllSubTenantIds(String parentTenantId) {
if (!StringUtils.hasText(parentTenantId)) {
return Collections.emptyList();
}
try {
List<String> subTenantIds = tenantHierarchyMapper.selectSubTenantIds(parentTenantId);
log.debug("查询租户 {} 的所有子租户,数量: {}", parentTenantId, subTenantIds.size());
return subTenantIds;
} catch (Exception e) {
log.error("查询子租户失败: parentTenantId={}, error={}", parentTenantId, e.getMessage());
return Collections.singletonList(parentTenantId);
}
}
@Override
public List<TenantTreeNode> buildTenantTree(List<String> tenantIds) {
if (tenantIds == null || tenantIds.isEmpty()) {
return Collections.emptyList();
}
try {
// 获取租户详细信息
List<Tenant> tenants = tenantHierarchyMapper.selectByTenantIds(tenantIds);
// 转换为树形节点
Map<String, TenantTreeNode> nodeMap = new HashMap<>();
List<TenantTreeNode> rootNodes = new ArrayList<>();
// 创建所有节点
for (Tenant tenant : tenants) {
TenantTreeNode node = TenantTreeNode.builder()
.tenantId(tenant.getTenantId())
.tenantName(tenant.getTenantName())
.parentTenantId(tenant.getParentTenantId())
.tenantType(tenant.getTenantType())
.tenantLevel(tenant.getTenantLevel())
.status(tenant.getStatus())
.enabled(tenant.getStatus() == 1)
.description(tenant.getDescription())
.children(new ArrayList<>())
.hasChildren(false)
.childrenCount(0)
.build();
nodeMap.put(tenant.getTenantId(), node);
}
// 构建父子关系
for (TenantTreeNode node : nodeMap.values()) {
if (!StringUtils.hasText(node.getParentTenantId())) {
rootNodes.add(node);
} else {
TenantTreeNode parent = nodeMap.get(node.getParentTenantId());
if (parent != null) {
parent.getChildren().add(node);
parent.setHasChildren(true);
parent.setChildrenCount(parent.getChildren().size());
}
}
}
log.debug("构建租户树完成,根节点数量: {}", rootNodes.size());
return rootNodes;
} catch (Exception e) {
log.error("构建租户树失败: tenantIds={}, error={}", tenantIds, e.getMessage());
return Collections.emptyList();
}
}
@Override
public TenantInfo getTenantInfo(String tenantId) {
if (!StringUtils.hasText(tenantId)) {
return null;
}
try {
Tenant tenant = tenantHierarchyMapper.selectByTenantId(tenantId);
if (tenant == null) {
return null;
}
// 查询子租户数量
List<Tenant> children = tenantHierarchyMapper.selectDirectChildren(tenantId);
int childrenCount = children != null ? children.size() : 0;
// 查询父租户名称
String parentTenantName = null;
if (StringUtils.hasText(tenant.getParentTenantId())) {
Tenant parentTenant = tenantHierarchyMapper.selectByTenantId(tenant.getParentTenantId());
if (parentTenant != null) {
parentTenantName = parentTenant.getTenantName();
}
}
return TenantInfo.builder()
.tenantId(tenant.getTenantId())
.tenantName(tenant.getTenantName())
.parentTenantId(tenant.getParentTenantId())
.parentTenantName(parentTenantName)
.tenantLevel(tenant.getTenantLevel())
.tenantPath(tenant.getTenantPath())
.tenantType(tenant.getTenantType())
.tenantCode(tenant.getTenantCode())
.contactPerson(tenant.getContactPerson())
.contactPhone(tenant.getContactPhone())
.address(tenant.getAddress())
.description(tenant.getDescription())
.status(tenant.getStatus())
.statusText(tenant.getStatus() == 1 ? "启用" : "停用")
.hasChildren(childrenCount > 0)
.childrenCount(childrenCount)
.createTime(tenant.getCreateTime() != null ?
LocalDateTime.ofInstant(tenant.getCreateTime().toInstant(), ZoneId.systemDefault()) : null)
.updateTime(tenant.getUpdateTime() != null ?
LocalDateTime.ofInstant(tenant.getUpdateTime().toInstant(), ZoneId.systemDefault()) : null)
.creatorId(tenant.getCreatorId())
.build();
} catch (Exception e) {
log.error("获取租户信息失败: tenantId={}, error={}", tenantId, e.getMessage());
return null;
}
}
@Override
@Transactional
@CacheEvict(value = "tenant:hierarchy", allEntries = true)
public Result<Tenant> createTenant(Tenant tenant) {
try {
// 验证必填字段
if (!StringUtils.hasText(tenant.getTenantId())) {
return Result.failed("租户ID不能为空");
}
if (!StringUtils.hasText(tenant.getTenantName())) {
return Result.failed("租户名称不能为空");
}
// 检查租户ID是否已存在
if (existsByTenantId(tenant.getTenantId())) {
return Result.failed("租户ID已存在");
}
// 验证父租户关系
if (StringUtils.hasText(tenant.getParentTenantId())) {
if (!validateTenantRelation(tenant.getTenantId(), tenant.getParentTenantId())) {
return Result.failed("无效的父子租户关系");
}
// 获取父租户信息,设置层级和路径
Tenant parentTenant = tenantHierarchyMapper.selectByTenantId(tenant.getParentTenantId());
if (parentTenant == null) {
return Result.failed("父租户不存在");
}
tenant.setTenantLevel(parentTenant.getTenantLevel() + 1);
tenant.setTenantPath(parentTenant.getTenantPath() + tenant.getTenantId() + "/");
} else {
// 根租户
tenant.setTenantLevel(1);
tenant.setTenantPath("/" + tenant.getTenantId() + "/");
}
// 设置默认值
if (tenant.getStatus() == null) {
tenant.setStatus(1);
}
if (!StringUtils.hasText(tenant.getTenantType())) {
tenant.setTenantType("COMPANY");
}
// 设置创建人
if (LoginUserContextHolder.getUser() != null) {
tenant.setCreatorId(LoginUserContextHolder.getUser().getId());
}
// 保存租户
int result = tenantHierarchyMapper.insert(tenant);
if (result > 0) {
log.info("创建租户成功: tenantId={}, tenantName={}", tenant.getTenantId(), tenant.getTenantName());
return Result.succeed(tenant);
} else {
return Result.failed("创建租户失败");
}
} catch (Exception e) {
log.error("创建租户异常: tenant={}, error={}", tenant, e.getMessage());
return Result.failed("创建租户异常: " + e.getMessage());
}
}
@Override
@Transactional
@CacheEvict(value = "tenant:hierarchy", allEntries = true)
public Result<Tenant> updateTenant(Tenant tenant) {
try {
if (!StringUtils.hasText(tenant.getTenantId())) {
return Result.failed("租户ID不能为空");
}
// 检查租户是否存在
Tenant existingTenant = tenantHierarchyMapper.selectByTenantId(tenant.getTenantId());
if (existingTenant == null) {
return Result.failed("租户不存在");
}
// 验证父租户关系变更
if (!Objects.equals(existingTenant.getParentTenantId(), tenant.getParentTenantId())) {
if (!validateTenantRelation(tenant.getTenantId(), tenant.getParentTenantId())) {
return Result.failed("无效的父子租户关系");
}
}
// 更新租户
int result = tenantHierarchyMapper.updateById(tenant);
if (result > 0) {
log.info("更新租户成功: tenantId={}", tenant.getTenantId());
return Result.succeed(tenant);
} else {
return Result.failed("更新租户失败");
}
} catch (Exception e) {
log.error("更新租户异常: tenant={}, error={}", tenant, e.getMessage());
return Result.failed("更新租户异常: " + e.getMessage());
}
}
@Override
@Transactional
@CacheEvict(value = "tenant:hierarchy", allEntries = true)
public Result<Boolean> deleteTenant(String tenantId) {
try {
if (!StringUtils.hasText(tenantId)) {
return Result.failed("租户ID不能为空");
}
// 检查是否有子租户
List<Tenant> children = tenantHierarchyMapper.selectDirectChildren(tenantId);
if (children != null && !children.isEmpty()) {
return Result.failed("存在子租户,无法删除");
}
// 软删除(更新状态为0)
Tenant tenant = new Tenant();
tenant.setTenantId(tenantId);
tenant.setStatus(0);
int result = tenantHierarchyMapper.updateById(tenant);
if (result > 0) {
log.info("删除租户成功: tenantId={}", tenantId);
return Result.succeed(true);
} else {
return Result.failed("删除租户失败");
}
} catch (Exception e) {
log.error("删除租户异常: tenantId={}, error={}", tenantId, e.getMessage());
return Result.failed("删除租户异常: " + e.getMessage());
}
}
@Override
public Result<List<TenantInfo>> getTenantList(String parentTenantId, String tenantName, Integer status, Integer page, Integer size) {
try {
if (page == null || page < 1) page = 1;
if (size == null || size < 1) size = 10;
int offset = (page - 1) * size;
List<Tenant> tenants = tenantHierarchyMapper.selectTenantList(parentTenantId, tenantName, status, offset, size);
long total = tenantHierarchyMapper.countTenantList(parentTenantId, tenantName, status);
List<TenantInfo> tenantInfos = tenants.stream()
.map(this::convertToTenantInfo)
.collect(Collectors.toList());
log.debug("查询租户列表完成,总数: {}, 当前页: {}", total, tenantInfos.size());
return Result.succeed(tenantInfos);
} catch (Exception e) {
log.error("查询租户列表异常: error={}", e.getMessage());
return Result.failed("查询租户列表异常: " + e.getMessage());
}
}
@Override
public boolean existsByTenantId(String tenantId) {
if (!StringUtils.hasText(tenantId)) {
return false;
}
return tenantHierarchyMapper.existsByTenantId(tenantId) > 0;
}
@Override
public boolean validateTenantRelation(String tenantId, String parentTenantId) {
if (!StringUtils.hasText(tenantId)) {
return false;
}
// 如果没有父租户,则合法
if (!StringUtils.hasText(parentTenantId)) {
return true;
}
// 不能将自己设置为父租户
if (tenantId.equals(parentTenantId)) {
return false;
}
// 检查是否会形成循环引用
String currentTenantId = parentTenantId;
Set<String> visited = new HashSet<>();
while (currentTenantId != null && !visited.contains(currentTenantId)) {
visited.add(currentTenantId);
if (currentTenantId.equals(tenantId)) {
// 形成循环引用
return false;
}
Tenant currentTenant = tenantHierarchyMapper.selectByTenantId(currentTenantId);
currentTenantId = currentTenant != null ? currentTenant.getParentTenantId() : null;
}
return true;
}
/**
* 转换为TenantInfo
*/
private TenantInfo convertToTenantInfo(Tenant tenant) {
if (tenant == null) {
return null;
}
return TenantInfo.builder()
.tenantId(tenant.getTenantId())
.tenantName(tenant.getTenantName())
.parentTenantId(tenant.getParentTenantId())
.tenantLevel(tenant.getTenantLevel())
.tenantPath(tenant.getTenantPath())
.tenantType(tenant.getTenantType())
.tenantCode(tenant.getTenantCode())
.contactPerson(tenant.getContactPerson())
.contactPhone(tenant.getContactPhone())
.address(tenant.getAddress())
.description(tenant.getDescription())
.status(tenant.getStatus())
.statusText(tenant.getStatus() == 1 ? "启用" : "停用")
.hasChildren(tenant.getHasChildren())
.childrenCount(tenant.getChildrenCount())
.createTime(tenant.getCreateTime() != null ?
LocalDateTime.ofInstant(tenant.getCreateTime().toInstant(), ZoneId.systemDefault()) : null)
.updateTime(tenant.getUpdateTime() != null ?
LocalDateTime.ofInstant(tenant.getUpdateTime().toInstant(), ZoneId.systemDefault()) : null)
.creatorId(tenant.getCreatorId())
.build();
}
}
@@ -1,75 +1,75 @@
spring:
datasource:
# url: jdbc:mysql://${zlt.datasource.ip}:3306/user-center?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai
url: jdbc:mysql://${zlt.datasource.ip}/user-center?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai
username: ${zlt.datasource.username}
password: ${zlt.datasource.password}
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis-plus:
mapper-locations: classpath:/mapper/*Mapper.xml
#实体扫描,多个package用逗号或者分号分隔
typeAliasesPackage: com.central.common.model
global-config:
db-config:
id-type: auto
springdoc:
group-configs:
- group: 'default'
paths-to-match: '/**'
packages-to-scan: com.central.user.controller
knife4j:
enable: true
setting:
swagger-model-name: 用户中心接口文档
zlt:
cache-manager:
configs:
- key: menu
second: 300
- key: user
second: 1800
#多租户配置
tenant:
enable: true
ignoreTables:
- sys_user
- sys_role_user
- sys_role_menu
- wechat_config
ignoreSqls:
# 用户关联角色时,显示所有角色
- com.central.user.mapper.SysRoleMapper.findAll
# 用户列表显示用户所关联的所有角色
- com.central.user.mapper.SysUserRoleMapper.findRolesByUserIds
# 数据权限
datascope:
enabled: false
ignoreTables:
- sys_role_user
- sys_role_menu
includeSqls:
# 用户列表
- com.central.user.mapper.SysUserMapper.findList
# 角色列表
- com.central.user.mapper.SysRoleMapper.findList
# 菜单列表
- com.central.user.mapper.SysMenuMapper.selectList
tencent:
app-id: ${zlt.security.tencent.app-id}
app-secret: ${zlt.security.tencent.app-secret}
access-token-url: https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=
get-phonenumber-url: https://api.weixin.qq.com/cgi-bin/token
#审计日志
# audit-log:
# enabled: true
# log-type: db
# datasource:
# driver-class-name: com.mysql.cj.jdbc.Driver
# jdbc-url: jdbc:mysql://${zlt.datasource.ip}:3306/logger-center?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai
# username: ${zlt.datasource.username}
# password: ${zlt.datasource.password}
#spring:
# datasource:
## url: jdbc:mysql://${zlt.datasource.ip}:3306/user-center?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai
# url: jdbc:mysql://${zlt.datasource.ip}/user-center?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai
# username: ${zlt.datasource.username}
# password: ${zlt.datasource.password}
# driver-class-name: com.mysql.cj.jdbc.Driver
#
#mybatis-plus:
# mapper-locations: classpath:/mapper/*Mapper.xml
# #实体扫描,多个package用逗号或者分号分隔
# typeAliasesPackage: com.central.common.model
# global-config:
# db-config:
# id-type: auto
#
#springdoc:
# group-configs:
# - group: 'default'
# paths-to-match: '/**'
# packages-to-scan: com.central.user.controller
#
#knife4j:
# enable: true
# setting:
# swagger-model-name: 用户中心接口文档
#
#zlt:
# cache-manager:
# configs:
# - key: menu
# second: 300
# - key: user
# second: 1800
# #多租户配置
# tenant:
# enable: true
# ignoreTables:
# - sys_user
# - sys_role_user
# - sys_role_menu
# - wechat_config
# ignoreSqls:
# # 用户关联角色时,显示所有角色
# - com.central.user.mapper.SysRoleMapper.findAll
# # 用户列表显示用户所关联的所有角色
# - com.central.user.mapper.SysUserRoleMapper.findRolesByUserIds
# # 数据权限
# datascope:
# enabled: false
# ignoreTables:
# - sys_role_user
# - sys_role_menu
# includeSqls:
# # 用户列表
# - com.central.user.mapper.SysUserMapper.findList
# # 角色列表
# - com.central.user.mapper.SysRoleMapper.findList
# # 菜单列表
# - com.central.user.mapper.SysMenuMapper.selectList
#
# tencent:
# app-id: ${zlt.security.tencent.app-id}
# app-secret: ${zlt.security.tencent.app-secret}
# access-token-url: https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=
# get-phonenumber-url: https://api.weixin.qq.com/cgi-bin/token
##审计日志
## audit-log:
## enabled: true
## log-type: db
## datasource:
## driver-class-name: com.mysql.cj.jdbc.Driver
## jdbc-url: jdbc:mysql://${zlt.datasource.ip}:3306/logger-center?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai
## username: ${zlt.datasource.username}
## password: ${zlt.datasource.password}
@@ -4,10 +4,10 @@ server:
spring:
application:
name: user-center
cloud:
nacos:
discovery:
ip: 124.222.128.40
# cloud:
# nacos:
# discovery:
# ip: 124.222.128.40
# cloud:
# nacos:
# discovery: