首页统计
This commit is contained in:
+27
@@ -42,6 +42,19 @@ public class DashboardController {
|
||||
@Parameter(description = "是否包含测试二维码") @RequestParam(required = false, defaultValue = "false") Boolean includeTestQrcodes) {
|
||||
try {
|
||||
Map<String, Object> params = new HashMap<>();
|
||||
// 追加统计粒度(day/month/year),从请求参数读取
|
||||
try {
|
||||
org.springframework.web.context.request.ServletRequestAttributes attrs = (org.springframework.web.context.request.ServletRequestAttributes) org.springframework.web.context.request.RequestContextHolder.getRequestAttributes();
|
||||
jakarta.servlet.http.HttpServletRequest req = attrs != null ? attrs.getRequest() : null;
|
||||
String statType = req != null ? req.getParameter("statType") : null;
|
||||
if (statType != null && !statType.isEmpty()) {
|
||||
params.put("statType", statType);
|
||||
}
|
||||
String incStr = req != null ? req.getParameter("includeChildren") : null;
|
||||
if (incStr != null && !incStr.isEmpty()) {
|
||||
params.put("includeChildren", incStr);
|
||||
}
|
||||
} catch (Exception ignored) {}
|
||||
params.put("tourismId", tourismId);
|
||||
params.put("qrcodeId", qrcodeId);
|
||||
params.put("deviceSn", deviceSn);
|
||||
@@ -64,6 +77,20 @@ public class DashboardController {
|
||||
@Parameter(description = "是否包含测试二维码") @RequestParam(required = false, defaultValue = "false") Boolean includeTestQrcodes) {
|
||||
try {
|
||||
Map<String, Object> params = new HashMap<>();
|
||||
// 追加租户范围(当前租户及其所有子租户)
|
||||
try {
|
||||
String anchor = com.central.common.context.TenantQueryOverrideContext.getTenantId();
|
||||
if (anchor == null || anchor.isEmpty()) {
|
||||
anchor = com.central.common.context.LoginUserContextHolder.getCurrentTenantId();
|
||||
}
|
||||
com.central.common.service.ITenantHierarchyService tenantService = com.central.common.utils.SpringContextHolder.getBean(com.central.common.service.ITenantHierarchyService.class);
|
||||
if (tenantService != null && anchor != null && !anchor.isEmpty()) {
|
||||
java.util.List<String> tenantIds = tenantService.getAllSubTenantIds(anchor);
|
||||
if (tenantIds != null && !tenantIds.isEmpty()) {
|
||||
params.put("tenantIds", tenantIds);
|
||||
}
|
||||
}
|
||||
} catch (Exception ignored) {}
|
||||
params.put("tourismId", tourismId);
|
||||
params.put("includeTestQrcodes", includeTestQrcodes);
|
||||
|
||||
|
||||
+13
@@ -1,11 +1,16 @@
|
||||
package com.central.order.feign;
|
||||
|
||||
import com.central.common.constant.ServiceNameConstants;
|
||||
import com.central.common.model.Result;
|
||||
import com.central.common.model.SysUser;
|
||||
import com.central.order.feign.fallback.UserCenterServiceFallbackFactory;
|
||||
import org.springframework.cloud.openfeign.FeignClient;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* user-center模块远程调用
|
||||
@@ -26,4 +31,12 @@ public interface UserCenterService {
|
||||
*/
|
||||
@GetMapping("/users/{id}")
|
||||
SysUser findUserById(@PathVariable("id") Long id);
|
||||
|
||||
|
||||
/**
|
||||
* 获取指定租户(含自身)及其所有子孙租户ID
|
||||
* @param tenantId 锚点租户ID
|
||||
*/
|
||||
@GetMapping("/tenant/hierarchy/{tenantId}")
|
||||
Result<List<String>> getDescendantTenantIds(@PathVariable("tenantId") String tenantId) throws Exception;
|
||||
}
|
||||
|
||||
+8
@@ -1,11 +1,14 @@
|
||||
package com.central.order.feign.fallback;
|
||||
|
||||
import com.central.common.model.Result;
|
||||
import com.central.common.model.SysUser;
|
||||
import com.central.order.feign.UserCenterService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.cloud.openfeign.FallbackFactory;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 用户中心调用失败回调
|
||||
*
|
||||
@@ -26,6 +29,11 @@ public class UserCenterServiceFallbackFactory implements FallbackFactory<UserCen
|
||||
public SysUser findUserById(Long id) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Result<List<String>> getDescendantTenantIds(String tenantId) {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
+109
-7
@@ -38,6 +38,15 @@ public interface DashboardMapper {
|
||||
"<if test='p.endTime != null and p.endTime != \"\"'>",
|
||||
" AND o.create_time <= #{p.endTime}",
|
||||
"</if>",
|
||||
"<choose>",
|
||||
" <when test='(p.startTime == null or p.startTime == \"\") and p.statType == \"day\"'> AND o.create_time >= DATE_SUB(CURDATE(), INTERVAL 6 DAY) </when>",
|
||||
" <when test='(p.startTime == null or p.startTime == \"\") and p.statType == \"month\"'> AND o.create_time >= DATE_SUB(CURDATE(), INTERVAL 12 MONTH) </when>",
|
||||
" <when test='(p.startTime == null or p.startTime == \"\") and p.statType == \"year\"'> AND o.create_time >= DATE_SUB(CURDATE(), INTERVAL 5 YEAR) </when>",
|
||||
"</choose>",
|
||||
"<if test='p.tourismIds != null and p.tourismIds.size > 0'>",
|
||||
" AND o.tourism_id IN",
|
||||
" <foreach collection='p.tourismIds' item='tid' open='(' separator=',' close=')'>#{tid}</foreach>",
|
||||
"</if>",
|
||||
"</script>"
|
||||
})
|
||||
Long getTotalOrders(@Param("p") Map<String, Object> params);
|
||||
@@ -63,6 +72,10 @@ public interface DashboardMapper {
|
||||
"<if test='p.deviceSn != null and p.deviceSn != \"\"'>",
|
||||
" AND o.device_sn = #{p.deviceSn}",
|
||||
"</if>",
|
||||
"<if test='p.tourismIds != null and p.tourismIds.size > 0'>",
|
||||
" AND o.tourism_id IN",
|
||||
" <foreach collection='p.tourismIds' item='tid' open='(' separator=',' close=')'>#{tid}</foreach>",
|
||||
"</if>",
|
||||
"</script>"
|
||||
})
|
||||
Long getTodayOrders(@Param("p") Map<String, Object> params);
|
||||
@@ -93,6 +106,15 @@ public interface DashboardMapper {
|
||||
"<if test='p.endTime != null and p.endTime != \"\"'>",
|
||||
" AND o.create_time <= #{p.endTime}",
|
||||
"</if>",
|
||||
"<choose>",
|
||||
" <when test='(p.startTime == null or p.startTime == \"\") and p.statType == \"day\"'> AND o.create_time >= DATE_SUB(CURDATE(), INTERVAL 6 DAY) </when>",
|
||||
" <when test='(p.startTime == null or p.startTime == \"\") and p.statType == \"month\"'> AND o.create_time >= DATE_SUB(CURDATE(), INTERVAL 12 MONTH) </when>",
|
||||
" <when test='(p.startTime == null or p.startTime == \"\") and p.statType == \"year\"'> AND o.create_time >= DATE_SUB(CURDATE(), INTERVAL 5 YEAR) </when>",
|
||||
"</choose>",
|
||||
"<if test='p.tourismIds != null and p.tourismIds.size > 0'>",
|
||||
" AND o.tourism_id IN",
|
||||
" <foreach collection='p.tourismIds' item='tid' open='(' separator=',' close=')'>#{tid}</foreach>",
|
||||
"</if>",
|
||||
"</script>"
|
||||
})
|
||||
Long getRefundedOrders(@Param("p") Map<String, Object> params);
|
||||
@@ -117,6 +139,10 @@ public interface DashboardMapper {
|
||||
"<if test='p.deviceSn != null and p.deviceSn != \"\"'>",
|
||||
" AND o.device_sn = #{p.deviceSn}",
|
||||
"</if>",
|
||||
"<if test='p.tourismIds != null and p.tourismIds.size > 0'>",
|
||||
" AND o.tourism_id IN",
|
||||
" <foreach collection='p.tourismIds' item='tid' open='(' separator=',' close=')'>#{tid}</foreach>",
|
||||
"</if>",
|
||||
"</script>"
|
||||
})
|
||||
Long getTodayRefundedOrders(@Param("p") Map<String, Object> params);
|
||||
@@ -147,6 +173,15 @@ public interface DashboardMapper {
|
||||
"<if test='p.endTime != null and p.endTime != \"\"'>",
|
||||
" AND o.create_time <= #{p.endTime}",
|
||||
"</if>",
|
||||
"<choose>",
|
||||
" <when test='(p.startTime == null or p.startTime == \"\") and p.statType == \"day\"'> AND o.create_time >= DATE_SUB(CURDATE(), INTERVAL 6 DAY) </when>",
|
||||
" <when test='(p.startTime == null or p.startTime == \"\") and p.statType == \"month\"'> AND o.create_time >= DATE_SUB(CURDATE(), INTERVAL 12 MONTH) </when>",
|
||||
" <when test='(p.startTime == null or p.startTime == \"\") and p.statType == \"year\"'> AND o.create_time >= DATE_SUB(CURDATE(), INTERVAL 5 YEAR) </when>",
|
||||
"</choose>",
|
||||
"<if test='p.tourismIds != null and p.tourismIds.size > 0'>",
|
||||
" AND o.tourism_id IN",
|
||||
" <foreach collection='p.tourismIds' item='tid' open='(' separator=',' close=')'>#{tid}</foreach>",
|
||||
"</if>",
|
||||
"</script>"
|
||||
})
|
||||
Long getTotalPaidOrders(@Param("p") Map<String, Object> params);
|
||||
@@ -172,6 +207,10 @@ public interface DashboardMapper {
|
||||
"<if test='p.deviceSn != null and p.deviceSn != \"\"'>",
|
||||
" AND o.device_sn = #{p.deviceSn}",
|
||||
"</if>",
|
||||
"<if test='p.tourismIds != null and p.tourismIds.size > 0'>",
|
||||
" AND o.tourism_id IN",
|
||||
" <foreach collection='p.tourismIds' item='tid' open='(' separator=',' close=')'>#{tid}</foreach>",
|
||||
"</if>",
|
||||
"</script>"
|
||||
})
|
||||
Long getTodayPaidOrders(@Param("p") Map<String, Object> params);
|
||||
@@ -241,7 +280,11 @@ public interface DashboardMapper {
|
||||
@Select({
|
||||
"<script>",
|
||||
"SELECT",
|
||||
" DATE_FORMAT(o.create_time, '%Y-%m-%d') as date,",
|
||||
" <choose>",
|
||||
" <when test=\"p.statType == 'year'\"> DATE_FORMAT(o.create_time, '%Y') as date, </when>",
|
||||
" <when test=\"p.statType == 'month'\"> DATE_FORMAT(o.create_time, '%Y-%m') as date, </when>",
|
||||
" <otherwise> DATE_FORMAT(o.create_time, '%Y-%m-%d') as date, </otherwise>",
|
||||
" </choose>",
|
||||
" 'created' as type,",
|
||||
" COUNT(*) as value",
|
||||
"FROM orders o",
|
||||
@@ -267,10 +310,23 @@ public interface DashboardMapper {
|
||||
"<if test='p.deviceSn != null and p.deviceSn != \"\"'>",
|
||||
" AND o.device_sn = #{p.deviceSn}",
|
||||
"</if>",
|
||||
"GROUP BY DATE_FORMAT(o.create_time, '%Y-%m-%d')",
|
||||
"<if test='p.tourismIds != null and p.tourismIds.size > 0'>",
|
||||
" AND o.tourism_id IN",
|
||||
" <foreach collection='p.tourismIds' item='tid' open='(' separator=',' close=')'>#{tid}</foreach>",
|
||||
"</if>",
|
||||
"GROUP BY ",
|
||||
"<choose>",
|
||||
" <when test=\"p.statType == 'year'\"> DATE_FORMAT(o.create_time, '%Y') </when>",
|
||||
" <when test=\"p.statType == 'month'\"> DATE_FORMAT(o.create_time, '%Y-%m') </when>",
|
||||
" <otherwise> DATE_FORMAT(o.create_time, '%Y-%m-%d') </otherwise>",
|
||||
"</choose>",
|
||||
"UNION ALL",
|
||||
"SELECT",
|
||||
" DATE_FORMAT(o.create_time, '%Y-%m-%d') as date,",
|
||||
" <choose>",
|
||||
" <when test=\"p.statType == 'year'\"> DATE_FORMAT(o.create_time, '%Y') as date, </when>",
|
||||
" <when test=\"p.statType == 'month'\"> DATE_FORMAT(o.create_time, '%Y-%m') as date, </when>",
|
||||
" <otherwise> DATE_FORMAT(o.create_time, '%Y-%m-%d') as date, </otherwise>",
|
||||
" </choose>",
|
||||
" 'completed' as type,",
|
||||
" COUNT(*) as value",
|
||||
"FROM orders o",
|
||||
@@ -296,10 +352,23 @@ public interface DashboardMapper {
|
||||
"<if test='p.deviceSn != null and p.deviceSn != \"\"'>",
|
||||
" AND o.device_sn = #{p.deviceSn}",
|
||||
"</if>",
|
||||
"GROUP BY DATE_FORMAT(o.create_time, '%Y-%m-%d')",
|
||||
"<if test='p.tourismIds != null and p.tourismIds.size > 0'>",
|
||||
" AND o.tourism_id IN",
|
||||
" <foreach collection='p.tourismIds' item='tid' open='(' separator=',' close=')'>#{tid}</foreach>",
|
||||
"</if>",
|
||||
"GROUP BY ",
|
||||
"<choose>",
|
||||
" <when test=\"p.statType == 'year'\"> DATE_FORMAT(o.create_time, '%Y') </when>",
|
||||
" <when test=\"p.statType == 'month'\"> DATE_FORMAT(o.create_time, '%Y-%m') </when>",
|
||||
" <otherwise> DATE_FORMAT(o.create_time, '%Y-%m-%d') </otherwise>",
|
||||
"</choose>",
|
||||
"UNION ALL",
|
||||
"SELECT",
|
||||
" DATE_FORMAT(o.create_time, '%Y-%m-%d') as date,",
|
||||
" <choose>",
|
||||
" <when test=\"p.statType == 'year'\"> DATE_FORMAT(o.create_time, '%Y') as date, </when>",
|
||||
" <when test=\"p.statType == 'month'\"> DATE_FORMAT(o.create_time, '%Y-%m') as date, </when>",
|
||||
" <otherwise> DATE_FORMAT(o.create_time, '%Y-%m-%d') as date, </otherwise>",
|
||||
" </choose>",
|
||||
" 'refunded' as type,",
|
||||
" COUNT(*) as value",
|
||||
"FROM orders o",
|
||||
@@ -325,7 +394,16 @@ public interface DashboardMapper {
|
||||
"<if test='p.deviceSn != null and p.deviceSn != \"\"'>",
|
||||
" AND o.device_sn = #{p.deviceSn}",
|
||||
"</if>",
|
||||
"GROUP BY DATE_FORMAT(o.create_time, '%Y-%m-%d')",
|
||||
"<if test='p.tourismIds != null and p.tourismIds.size > 0'>",
|
||||
" AND o.tourism_id IN",
|
||||
" <foreach collection='p.tourismIds' item='tid' open='(' separator=',' close=')'>#{tid}</foreach>",
|
||||
"</if>",
|
||||
"GROUP BY ",
|
||||
"<choose>",
|
||||
" <when test=\"p.statType == 'year'\"> DATE_FORMAT(o.create_time, '%Y') </when>",
|
||||
" <when test=\"p.statType == 'month'\"> DATE_FORMAT(o.create_time, '%Y-%m') </when>",
|
||||
" <otherwise> DATE_FORMAT(o.create_time, '%Y-%m-%d') </otherwise>",
|
||||
"</choose>",
|
||||
"ORDER BY date, type",
|
||||
"</script>"
|
||||
})
|
||||
@@ -346,6 +424,10 @@ public interface DashboardMapper {
|
||||
"<if test='p.tourismId != null'>",
|
||||
" AND q.tourism_id = #{p.tourismId}",
|
||||
"</if>",
|
||||
"<if test='p.tourismIds != null and p.tourismIds.size > 0'>",
|
||||
" AND q.tourism_id IN",
|
||||
" <foreach collection='p.tourismIds' item='tid' open='(' separator=',' close=')'>#{tid}</foreach>",
|
||||
"</if>",
|
||||
"<if test='p.startTime != null and p.startTime != \"\"'>",
|
||||
" AND o.create_time >= #{p.startTime}",
|
||||
"</if>",
|
||||
@@ -454,6 +536,10 @@ public interface DashboardMapper {
|
||||
"<if test='p.endTime != null and p.endTime != \"\"'>",
|
||||
" AND o.create_time <= #{p.endTime}",
|
||||
"</if>",
|
||||
"<if test='p.tourismIds != null and p.tourismIds.size > 0'>",
|
||||
" AND o.tourism_id IN",
|
||||
" <foreach collection='p.tourismIds' item='tid' open='(' separator=',' close=')'>#{tid}</foreach>",
|
||||
"</if>",
|
||||
"GROUP BY o.order_status",
|
||||
"</script>"
|
||||
})
|
||||
@@ -486,6 +572,10 @@ public interface DashboardMapper {
|
||||
"<if test='p.endTime != null and p.endTime != \"\"'>",
|
||||
" AND o.create_time <= #{p.endTime}",
|
||||
"</if>",
|
||||
"<if test='p.tourismIds != null and p.tourismIds.size > 0'>",
|
||||
" AND o.tourism_id IN",
|
||||
" <foreach collection='p.tourismIds' item='tid' open='(' separator=',' close=')'>#{tid}</foreach>",
|
||||
"</if>",
|
||||
"UNION ALL",
|
||||
"SELECT",
|
||||
" '景区分账' as type,",
|
||||
@@ -512,6 +602,10 @@ public interface DashboardMapper {
|
||||
"<if test='p.endTime != null and p.endTime != \"\"'>",
|
||||
" AND o.create_time <= #{p.endTime}",
|
||||
"</if>",
|
||||
"<if test='p.tourismIds != null and p.tourismIds.size > 0'>",
|
||||
" AND o.tourism_id IN",
|
||||
" <foreach collection='p.tourismIds' item='tid' open='(' separator=',' close=')'>#{tid}</foreach>",
|
||||
"</if>",
|
||||
"UNION ALL",
|
||||
"SELECT",
|
||||
" '退款金额' as type,",
|
||||
@@ -538,6 +632,10 @@ public interface DashboardMapper {
|
||||
"<if test='p.endTime != null and p.endTime != \"\"'>",
|
||||
" AND o.create_time <= #{p.endTime}",
|
||||
"</if>",
|
||||
"<if test='p.tourismIds != null and p.tourismIds.size > 0'>",
|
||||
" AND o.tourism_id IN",
|
||||
" <foreach collection='p.tourismIds' item='tid' open='(' separator=',' close=')'>#{tid}</foreach>",
|
||||
"</if>",
|
||||
"</script>"
|
||||
})
|
||||
List<IncomeDataVO> getIncomeBreakdown(@Param("p") Map<String, Object> params);
|
||||
@@ -553,6 +651,10 @@ public interface DashboardMapper {
|
||||
"<if test='p.includeTestQrcodes == null or p.includeTestQrcodes == false'>",
|
||||
" AND is_test = 0",
|
||||
"</if>",
|
||||
"<if test='p.tenantIds != null and p.tenantIds.size > 0'>",
|
||||
" AND tenant_id IN",
|
||||
" <foreach collection='p.tenantIds' item='tid' open='(' separator=',' close=')'>#{tid}</foreach>",
|
||||
"</if>",
|
||||
"<if test='p.tourismId != null'>",
|
||||
" AND tourism_id = #{p.tourismId}",
|
||||
"</if>",
|
||||
@@ -560,4 +662,4 @@ public interface DashboardMapper {
|
||||
"</script>"
|
||||
})
|
||||
List<FilterOptions.OptionItem> getQrcodeOptions(@Param("p") Map<String, Object> params);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -74,4 +74,9 @@ public interface TourismMapper extends SuperMapper<Tourism> {
|
||||
@Param("maxLatitude") BigDecimal maxLatitude
|
||||
);
|
||||
|
||||
/**
|
||||
* 根据租户ID集合查询景区ID集合
|
||||
*/
|
||||
List<Long> findTourismIdsByTenantIds(@Param("tenantIds") List<String> tenantIds);
|
||||
|
||||
}
|
||||
|
||||
+64
@@ -1,7 +1,13 @@
|
||||
package com.central.order.service.impl;
|
||||
|
||||
import com.central.common.context.LoginUserContextHolder;
|
||||
import com.central.common.context.TenantQueryOverrideContext;
|
||||
import com.central.common.datascope.annotation.IgnoreTenantScope;
|
||||
import com.central.common.model.PageResult;
|
||||
import com.central.common.service.ITenantHierarchyService;
|
||||
import com.central.common.utils.SpringContextHolder;
|
||||
import com.central.order.mapper.DashboardMapper;
|
||||
import com.central.order.mapper.TourismMapper;
|
||||
import com.central.order.model.Order;
|
||||
import com.central.order.model.vo.*;
|
||||
import com.central.order.service.IDashboardService;
|
||||
@@ -23,9 +29,32 @@ public class DashboardServiceImpl implements IDashboardService {
|
||||
|
||||
private final DashboardMapper dashboardMapper;
|
||||
private final IOrderService orderService;
|
||||
private final TourismMapper tourismMapper;
|
||||
|
||||
@Override
|
||||
@IgnoreTenantScope
|
||||
public DashboardStatisticsVO getDashboardStatistics(Map<String, Object> params) {
|
||||
// 依据租户层级组装景区ID集合,作为统计范围(支持 includeChildren=false 仅当前租户)
|
||||
try {
|
||||
boolean includeChildren = true;
|
||||
try {
|
||||
Object inc = params != null ? params.get("includeChildren") : null;
|
||||
if (inc != null) {
|
||||
String s = String.valueOf(inc);
|
||||
includeChildren = !("false".equalsIgnoreCase(s) || "0".equals(s));
|
||||
}
|
||||
} catch (Exception ignored) {}
|
||||
|
||||
List<String> tenantIds = resolveTenantIdsFromContext(includeChildren);
|
||||
if (tenantIds != null && !tenantIds.isEmpty()) {
|
||||
List<Long> tourismIds = resolveTourismIdsByTenants(tenantIds);
|
||||
if (tourismIds != null && !tourismIds.isEmpty()) {
|
||||
params.put("tourismIds", tourismIds);
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.warn("解析租户/景区范围失败,使用默认上下文: {}", e.getMessage());
|
||||
}
|
||||
DashboardStatisticsVO statistics = new DashboardStatisticsVO();
|
||||
|
||||
try {
|
||||
@@ -187,4 +216,39 @@ public class DashboardServiceImpl implements IDashboardService {
|
||||
|
||||
return options;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析当前请求上下文的租户集合(包含子租户)
|
||||
*/
|
||||
private List<String> resolveTenantIdsFromContext(boolean includeChildren) {
|
||||
String anchor = TenantQueryOverrideContext.getTenantId();
|
||||
if (anchor == null || anchor.isEmpty()) {
|
||||
anchor = LoginUserContextHolder.getCurrentTenantId();
|
||||
}
|
||||
if (anchor == null || anchor.isEmpty()) {
|
||||
return java.util.Collections.emptyList();
|
||||
}
|
||||
if (!includeChildren) {
|
||||
return java.util.Collections.singletonList(anchor);
|
||||
}
|
||||
try {
|
||||
ITenantHierarchyService tenantService = SpringContextHolder.getBean(ITenantHierarchyService.class);
|
||||
List<String> all = tenantService != null ? tenantService.getAllSubTenantIds(anchor) : null;
|
||||
if (all != null && !all.isEmpty()) return all;
|
||||
} catch (Exception ignored) { }
|
||||
return java.util.Collections.singletonList(anchor);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据租户集合查询景区ID集合
|
||||
*/
|
||||
private List<Long> resolveTourismIdsByTenants(List<String> tenantIds) {
|
||||
try {
|
||||
if (tenantIds == null || tenantIds.isEmpty()) return java.util.Collections.emptyList();
|
||||
return tourismMapper.findTourismIdsByTenantIds(tenantIds);
|
||||
} catch (Exception e) {
|
||||
log.debug("根据租户查询景区失败: {}", e.getMessage());
|
||||
return java.util.Collections.emptyList();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,7 +4,20 @@
|
||||
<mapper namespace="com.central.order.mapper.TourismMapper">
|
||||
|
||||
<select id="findList" resultType="com.central.order.model.Tourism">
|
||||
select * from tourisms t
|
||||
SELECT *
|
||||
FROM tourisms t
|
||||
<where>
|
||||
<if test="p.tenantIds != null and p.tenantIds.size > 0">
|
||||
AND t.tenant_id IN
|
||||
<foreach collection="p.tenantIds" item="tid" open="(" separator="," close=")">
|
||||
#{tid}
|
||||
</foreach>
|
||||
</if>
|
||||
<if test="(p.tenantIds == null or p.tenantIds.size == 0) and p.tenantId != null and p.tenantId != ''">
|
||||
AND t.tenant_id = #{p.tenantId}
|
||||
</if>
|
||||
</where>
|
||||
ORDER BY t.id DESC
|
||||
</select>
|
||||
|
||||
<resultMap id="TourismResultMap" type="com.central.order.model.Tourism">
|
||||
@@ -89,4 +102,17 @@
|
||||
ORDER BY create_time DESC
|
||||
</select>
|
||||
|
||||
<!-- 根据租户ID集合查询景区ID集合 -->
|
||||
<select id="findTourismIdsByTenantIds" resultType="java.lang.Long">
|
||||
SELECT id FROM tourisms
|
||||
WHERE is_del = 0
|
||||
<if test="tenantIds != null and tenantIds.size > 0">
|
||||
AND tenant_id IN
|
||||
<foreach collection="tenantIds" item="tid" open="(" separator="," close=")">
|
||||
#{tid}
|
||||
</foreach>
|
||||
</if>
|
||||
ORDER BY id DESC
|
||||
</select>
|
||||
|
||||
</mapper>
|
||||
|
||||
+19
@@ -152,6 +152,25 @@ public class TenantHierarchyController {
|
||||
return t;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取指定租户(含自身)及其所有子孙租户ID列表
|
||||
* 供其他业务服务(如 order-center)通过 Feign 远程调用
|
||||
*/
|
||||
@GetMapping("/{tenantId}")
|
||||
@Operation(summary = "获取子孙租户ID列表(含自身)")
|
||||
public Result<List<String>> getDescendantTenantIds(@PathVariable("tenantId") String tenantId) {
|
||||
if (!StringUtils.hasText(tenantId)) {
|
||||
return Result.failed("tenantId 不能为空");
|
||||
}
|
||||
try {
|
||||
List<String> ids = tenantHierarchyService.getAllSubTenantIds(tenantId);
|
||||
return Result.succeed(ids);
|
||||
} catch (Exception e) {
|
||||
log.warn("获取子孙租户失败,退化为仅自身: {} -> {}", tenantId, e.getMessage());
|
||||
return Result.succeed(java.util.Collections.singletonList(tenantId), "已退化为仅自身");
|
||||
}
|
||||
}
|
||||
|
||||
private String normalizePathForSave(String rawPath, String parentId, String tenantId) {
|
||||
try {
|
||||
String path = stripPathSafe(rawPath);
|
||||
|
||||
+11
-3
@@ -45,10 +45,18 @@ public class TenantSwitchController {
|
||||
if (user == null) {
|
||||
return Result.failed("用户未登录");
|
||||
}
|
||||
if (!isCanSwitchTenant(user)) {
|
||||
return Result.failed("用户无租户切换权限");
|
||||
// 不再强制校验切换权限:至少返回当前租户 + 子孙租户,便于查询范围选择
|
||||
String userTenantId = getDefaultTenantId(user);
|
||||
List<String> accessibleTenantIds = List.of();
|
||||
if (StringUtils.hasText(userTenantId)) {
|
||||
try {
|
||||
List<String> subIds = tenantHierarchyService != null ? tenantHierarchyService.getAllSubTenantIds(userTenantId) : null;
|
||||
accessibleTenantIds = (subIds != null && !subIds.isEmpty()) ? subIds : List.of(userTenantId);
|
||||
} catch (Exception ex) {
|
||||
log.warn("获取子租户列表失败,降级为仅当前租户: tenantId={}, error={}", userTenantId, ex.getMessage());
|
||||
accessibleTenantIds = List.of(userTenantId);
|
||||
}
|
||||
}
|
||||
List<String> accessibleTenantIds = getAccessibleTenantIds(user);
|
||||
if (accessibleTenantIds.isEmpty()) {
|
||||
return Result.failed("用户无可访问的租户");
|
||||
}
|
||||
|
||||
+12
-1
@@ -5,6 +5,7 @@ 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 org.apache.ibatis.annotations.Update;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@@ -146,4 +147,14 @@ public interface TenantHierarchyMapper extends BaseMapper<Tenant> {
|
||||
long countTenantList(@Param("parentTenantId") String parentTenantId,
|
||||
@Param("tenantName") String tenantName,
|
||||
@Param("status") Integer status);
|
||||
}
|
||||
|
||||
/**
|
||||
* 基于 tenant_id 进行软删除(将 status 置为 0)
|
||||
*
|
||||
* @param tenantId 租户ID
|
||||
* @param status 状态值(0 表示删除/禁用)
|
||||
* @return 影响行数
|
||||
*/
|
||||
@Update("UPDATE sys_tenant SET status = #{status} WHERE tenant_id = #{tenantId}")
|
||||
int updateStatusByTenantId(@Param("tenantId") String tenantId, @Param("status") Integer status);
|
||||
}
|
||||
|
||||
+40
-40
@@ -16,9 +16,9 @@ import com.central.common.model.UserType;
|
||||
import com.central.common.model.SuperEntity;
|
||||
import com.central.common.model.SysMenu;
|
||||
import com.central.common.service.impl.SuperServiceImpl;
|
||||
import com.central.user.feign.DeviceCenterService;
|
||||
import com.central.common.service.ITenantHierarchyService;
|
||||
import com.central.common.context.LoginUserContextHolder;
|
||||
import com.central.user.feign.DeviceCenterService;
|
||||
import com.central.common.service.ITenantHierarchyService;
|
||||
import com.central.common.context.LoginUserContextHolder;
|
||||
import com.central.user.feign.OrderCenterService;
|
||||
import com.central.user.mapper.SysRoleMenuMapper;
|
||||
import com.central.user.mapper.SysUserMapper;
|
||||
@@ -64,11 +64,11 @@ public class SysUserServiceImpl extends SuperServiceImpl<SysUserMapper, SysUser>
|
||||
@Resource
|
||||
private OrderCenterService orderCenterService;
|
||||
|
||||
@Resource
|
||||
private DeviceCenterService deviceCenterService;
|
||||
|
||||
@Resource
|
||||
private ITenantHierarchyService tenantHierarchyService;
|
||||
@Resource
|
||||
private DeviceCenterService deviceCenterService;
|
||||
|
||||
@Resource
|
||||
private ITenantHierarchyService tenantHierarchyService;
|
||||
|
||||
@Override
|
||||
public SysUser findByUsername(String username) {
|
||||
@@ -230,38 +230,38 @@ public class SysUserServiceImpl extends SuperServiceImpl<SysUserMapper, SysUser>
|
||||
return Result.succeed("修改成功");
|
||||
}
|
||||
|
||||
@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);
|
||||
}
|
||||
List<SysUser> list = baseMapper.findList(page, params);
|
||||
@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);
|
||||
}
|
||||
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());
|
||||
|
||||
+126
-235
@@ -23,8 +23,10 @@ import java.util.stream.Collectors;
|
||||
/**
|
||||
* 租户层级管理服务实现
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2024-12-19
|
||||
* 仅修复本文件:
|
||||
* - 处理 status 为空导致的 NPE
|
||||
* - 统一中文文案为 UTF-8
|
||||
* - 保持接口契约不变
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@@ -33,48 +35,31 @@ 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);
|
||||
if (subTenantIds == null) {
|
||||
subTenantIds = new ArrayList<>();
|
||||
}
|
||||
// 确保包含自身
|
||||
if (!subTenantIds.contains(parentTenantId)) {
|
||||
subTenantIds.add(0, parentTenantId);
|
||||
}
|
||||
|
||||
// 如果基于 tenant_path 的查询结果过少,回退为按 parent_tenant_id 递归遍历
|
||||
if (subTenantIds.size() <= 1) {
|
||||
Deque<String> queue = new ArrayDeque<>();
|
||||
queue.add(parentTenantId);
|
||||
while (!queue.isEmpty()) {
|
||||
String pid = queue.poll();
|
||||
List<Tenant> children = tenantHierarchyMapper.selectDirectChildren(pid);
|
||||
if (children != null) {
|
||||
for (Tenant t : children) {
|
||||
String tid = t.getTenantId();
|
||||
if (!subTenantIds.contains(tid)) {
|
||||
subTenantIds.add(tid);
|
||||
queue.add(tid);
|
||||
}
|
||||
}
|
||||
LinkedHashSet<String> all = new LinkedHashSet<>();
|
||||
ArrayDeque<String> queue = new ArrayDeque<>();
|
||||
all.add(parentTenantId);
|
||||
queue.add(parentTenantId);
|
||||
while (!queue.isEmpty()) {
|
||||
String pid = queue.poll();
|
||||
List<Tenant> children = tenantHierarchyMapper.selectDirectChildren(pid);
|
||||
if (children == null) continue;
|
||||
for (Tenant t : children) {
|
||||
String tid = t.getTenantId();
|
||||
if (StringUtils.hasText(tid) && all.add(tid)) {
|
||||
queue.add(tid);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
log.debug("查询租户 {} 的所有子租户,数量: {}", parentTenantId, subTenantIds.size());
|
||||
return subTenantIds;
|
||||
return new ArrayList<>(all);
|
||||
} catch (Exception e) {
|
||||
log.error("查询子租户失败: parentTenantId={}, error={}", parentTenantId, e.getMessage());
|
||||
log.error("查询子孙租户失败: parentTenantId={}, error={}", parentTenantId, e.getMessage());
|
||||
return Collections.singletonList(parentTenantId);
|
||||
}
|
||||
}
|
||||
@@ -84,40 +69,38 @@ public class TenantHierarchyServiceImpl implements ITenantHierarchyService {
|
||||
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<>();
|
||||
List<TenantTreeNode> roots = new ArrayList<>();
|
||||
|
||||
// 创建所有节点
|
||||
for (Tenant tenant : tenants) {
|
||||
for (Tenant t : 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);
|
||||
.tenantId(t.getTenantId())
|
||||
.tenantName(t.getTenantName())
|
||||
.parentTenantId(t.getParentTenantId())
|
||||
.tenantType(t.getTenantType())
|
||||
.tenantLevel(t.getTenantLevel())
|
||||
.status(t.getStatus())
|
||||
.enabled(Objects.equals(t.getStatus(), 1))
|
||||
.description(t.getDescription())
|
||||
.children(new ArrayList<>())
|
||||
.hasChildren(false)
|
||||
.childrenCount(0)
|
||||
.build();
|
||||
nodeMap.put(t.getTenantId(), node);
|
||||
}
|
||||
|
||||
// 构建父子关系
|
||||
for (TenantTreeNode node : nodeMap.values()) {
|
||||
if (!StringUtils.hasText(node.getParentTenantId())) {
|
||||
rootNodes.add(node);
|
||||
String p = node.getParentTenantId();
|
||||
if (!StringUtils.hasText(p)) {
|
||||
roots.add(node);
|
||||
} else {
|
||||
TenantTreeNode parent = nodeMap.get(node.getParentTenantId());
|
||||
if (parent != null) {
|
||||
TenantTreeNode parent = nodeMap.get(p);
|
||||
if (parent == null) {
|
||||
roots.add(node);
|
||||
} else {
|
||||
parent.getChildren().add(node);
|
||||
parent.setHasChildren(true);
|
||||
parent.setChildrenCount(parent.getChildren().size());
|
||||
@@ -125,9 +108,7 @@ public class TenantHierarchyServiceImpl implements ITenantHierarchyService {
|
||||
}
|
||||
}
|
||||
|
||||
log.debug("构建租户树完成,根节点数量: {}", rootNodes.size());
|
||||
return rootNodes;
|
||||
|
||||
return roots;
|
||||
} catch (Exception e) {
|
||||
log.error("构建租户树失败: tenantIds={}, error={}", tenantIds, e.getMessage());
|
||||
return Collections.emptyList();
|
||||
@@ -139,52 +120,44 @@ public class TenantHierarchyServiceImpl implements ITenantHierarchyService {
|
||||
if (!StringUtils.hasText(tenantId)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
Tenant tenant = tenantHierarchyMapper.selectByTenantId(tenantId);
|
||||
if (tenant == null) {
|
||||
return null;
|
||||
}
|
||||
if (tenant == null) return null;
|
||||
|
||||
// 查询子租户数量
|
||||
List<Tenant> children = tenantHierarchyMapper.selectDirectChildren(tenantId);
|
||||
int childrenCount = children != null ? children.size() : 0;
|
||||
int childrenCount = children == null ? 0 : children.size();
|
||||
|
||||
// 查询父租户名称
|
||||
String parentTenantName = null;
|
||||
String parentName = null;
|
||||
if (StringUtils.hasText(tenant.getParentTenantId())) {
|
||||
Tenant parentTenant = tenantHierarchyMapper.selectByTenantId(tenant.getParentTenantId());
|
||||
if (parentTenant != null) {
|
||||
parentTenantName = parentTenant.getTenantName();
|
||||
}
|
||||
Tenant parent = tenantHierarchyMapper.selectByTenantId(tenant.getParentTenantId());
|
||||
if (parent != null) parentName = parent.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();
|
||||
|
||||
.tenantId(tenant.getTenantId())
|
||||
.tenantName(tenant.getTenantName())
|
||||
.parentTenantId(tenant.getParentTenantId())
|
||||
.parentTenantName(parentName)
|
||||
.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(Objects.equals(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());
|
||||
log.error("获取租户信息异常: tenantId={}, error={}", tenantId, e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -194,60 +167,38 @@ public class TenantHierarchyServiceImpl implements ITenantHierarchyService {
|
||||
@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() + "/");
|
||||
Tenant parent = tenantHierarchyMapper.selectByTenantId(tenant.getParentTenantId());
|
||||
if (parent == null) return Result.failed("父租户不存在");
|
||||
tenant.setTenantLevel(parent.getTenantLevel() + 1);
|
||||
tenant.setTenantPath(parent.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 (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("创建租户失败");
|
||||
}
|
||||
|
||||
int r = tenantHierarchyMapper.insert(tenant);
|
||||
if (r > 0) return Result.succeed(tenant);
|
||||
return Result.failed("创建租户失败");
|
||||
} catch (Exception e) {
|
||||
log.error("创建租户异常: tenant={}, error={}", tenant, e.getMessage());
|
||||
return Result.failed("创建租户异常: " + e.getMessage());
|
||||
@@ -262,30 +213,19 @@ public class TenantHierarchyServiceImpl implements ITenantHierarchyService {
|
||||
if (!StringUtils.hasText(tenant.getTenantId())) {
|
||||
return Result.failed("租户ID不能为空");
|
||||
}
|
||||
Tenant exist = tenantHierarchyMapper.selectByTenantId(tenant.getTenantId());
|
||||
if (exist == null) return Result.failed("租户不存在");
|
||||
|
||||
// 检查租户是否存在
|
||||
Tenant existingTenant = tenantHierarchyMapper.selectByTenantId(tenant.getTenantId());
|
||||
if (existingTenant == null) {
|
||||
return Result.failed("租户不存在");
|
||||
}
|
||||
|
||||
// 验证父子关系变更
|
||||
if (!Objects.equals(existingTenant.getParentTenantId(), tenant.getParentTenantId())) {
|
||||
if (!Objects.equals(exist.getParentTenantId(), tenant.getParentTenantId())) {
|
||||
if (!validateTenantRelation(tenant.getTenantId(), tenant.getParentTenantId())) {
|
||||
return Result.failed("无效的父子租户关系");
|
||||
}
|
||||
}
|
||||
|
||||
// 使用主键ID执行更新,避免未传ID导致更新不到
|
||||
tenant.setId(existingTenant.getId());
|
||||
int result = tenantHierarchyMapper.updateById(tenant);
|
||||
if (result > 0) {
|
||||
log.info("更新租户成功: tenantId={}", tenant.getTenantId());
|
||||
return Result.succeed(tenant);
|
||||
} else {
|
||||
return Result.failed("更新租户失败");
|
||||
}
|
||||
|
||||
tenant.setId(exist.getId());
|
||||
int r = tenantHierarchyMapper.updateById(tenant);
|
||||
if (r > 0) return Result.succeed(tenant);
|
||||
return Result.failed("更新租户失败");
|
||||
} catch (Exception e) {
|
||||
log.error("更新租户异常: tenant={}, error={}", tenant, e.getMessage());
|
||||
return Result.failed("更新租户异常: " + e.getMessage());
|
||||
@@ -297,29 +237,12 @@ public class TenantHierarchyServiceImpl implements ITenantHierarchyService {
|
||||
@CacheEvict(value = "tenant:hierarchy", allEntries = true)
|
||||
public Result<Boolean> deleteTenant(String tenantId) {
|
||||
try {
|
||||
if (!StringUtils.hasText(tenantId)) {
|
||||
return Result.failed("租户ID不能为空");
|
||||
}
|
||||
|
||||
// 检查是否有子租户
|
||||
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("删除租户失败");
|
||||
}
|
||||
|
||||
if (children != null && !children.isEmpty()) return Result.failed("存在子租户,无法删除");
|
||||
int r = tenantHierarchyMapper.updateStatusByTenantId(tenantId, 0);
|
||||
if (r > 0) return Result.succeed(true);
|
||||
return Result.failed("删除租户失败");
|
||||
} catch (Exception e) {
|
||||
log.error("删除租户异常: tenantId={}, error={}", tenantId, e.getMessage());
|
||||
return Result.failed("删除租户异常: " + e.getMessage());
|
||||
@@ -331,19 +254,13 @@ public class TenantHierarchyServiceImpl implements ITenantHierarchyService {
|
||||
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);
|
||||
tenants = tenants == null ? Collections.emptyList() : tenants;
|
||||
|
||||
List<TenantInfo> list = tenants.stream().map(this::convertToTenantInfo).collect(Collectors.toList());
|
||||
return Result.succeed(list);
|
||||
} catch (Exception e) {
|
||||
log.error("查询租户列表异常: error={}", e.getMessage());
|
||||
return Result.failed("查询租户列表异常: " + e.getMessage());
|
||||
@@ -352,77 +269,51 @@ public class TenantHierarchyServiceImpl implements ITenantHierarchyService {
|
||||
|
||||
@Override
|
||||
public boolean existsByTenantId(String tenantId) {
|
||||
if (!StringUtils.hasText(tenantId)) {
|
||||
return false;
|
||||
}
|
||||
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(tenantId)) return false;
|
||||
if (!StringUtils.hasText(parentTenantId)) return true;
|
||||
if (tenantId.equals(parentTenantId)) return false;
|
||||
|
||||
// 如果没有父租户,则合法
|
||||
if (!StringUtils.hasText(parentTenantId)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// 不能将自己设置为父租户
|
||||
if (tenantId.equals(parentTenantId)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 检查是否会形成循环引用
|
||||
String currentTenantId = parentTenantId;
|
||||
String current = 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;
|
||||
while (current != null && !visited.contains(current)) {
|
||||
visited.add(current);
|
||||
if (tenantId.equals(current)) return false;
|
||||
Tenant p = tenantHierarchyMapper.selectByTenantId(current);
|
||||
current = p == null ? null : p.getParentTenantId();
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 转换为 TenantInfo
|
||||
*/
|
||||
private TenantInfo convertToTenantInfo(Tenant tenant) {
|
||||
if (tenant == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
private TenantInfo convertToTenantInfo(Tenant t) {
|
||||
if (t == 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();
|
||||
.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())
|
||||
.statusText(Objects.equals(t.getStatus(), 1) ? "启用" : "停用")
|
||||
.hasChildren(t.getHasChildren())
|
||||
.childrenCount(t.getChildrenCount())
|
||||
.createTime(t.getCreateTime() != null ?
|
||||
LocalDateTime.ofInstant(t.getCreateTime().toInstant(), ZoneId.systemDefault()) : null)
|
||||
.updateTime(t.getUpdateTime() != null ?
|
||||
LocalDateTime.ofInstant(t.getUpdateTime().toInstant(), ZoneId.systemDefault()) : null)
|
||||
.creatorId(t.getCreatorId())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user