首页统计

This commit is contained in:
2025-10-01 03:51:53 +08:00
parent dbd4d4d198
commit 66d09ef19c
32 changed files with 1293 additions and 499 deletions
-1
View File
@@ -1 +0,0 @@
/* Go-Fly Admin 鐜颁唬绉戞妧鎰熶富棰?*//* CSS鍙橀噺瀹氫箟 */:root { /* 涓昏壊璋?*/ --primary-color: #1677ff; --primary-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%); --tech-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%); /* 鑳屾櫙鑹?*/ --bg-primary: #0f1419; --bg-secondary: #1a1d23; --bg-tertiary: #21252b; --bg-card: rgba(255, 255, 255, 0.05); --bg-glass: rgba(255, 255, 255, 0.08); /* 鏂囧瓧棰滆壊 */ --text-primary: #ffffff; --text-secondary: #a0a6b8; --text-tertiary: #6c7293; /* 杈规鍜屽垎鍓茬嚎 */ --border-color: rgba(255, 255, 255, 0.1); --divider-color: rgba(255, 255, 255, 0.08); /* 闃村奖 */ --shadow-card: 0 8px 32px rgba(0, 0, 0, 0.3); --shadow-hover: 0 12px 48px rgba(0, 0, 0, 0.4); --shadow-glow: 0 0 20px rgba(102, 126, 234, 0.3); /* 鍔ㄧ敾鏇茬嚎 */ --ease-out-quart: cubic-bezier(0.25, 1, 0.5, 1); --ease-in-out-back: cubic-bezier(0.68, -0.55, 0.265, 1.55);}/* 鍏ㄥ眬鏍峰紡閲嶇疆 */body { background: var(--bg-primary); color: var(--text-primary); font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Helvetica Neue', Helvetica, Arial, sans-serif;}/* 鐜荤拑璐ㄦ劅鏁堟灉 */.glass-effect { background: var(--bg-glass); backdrop-filter: blur(10px); border: 1px solid var(--border-color); border-radius: 12px;}/* 鍗$墖鎮仠鏁堟灉 */.modern-card { background: var(--bg-card); border-radius: 16px; padding: 24px; box-shadow: var(--shadow-card); border: 1px solid var(--border-color); transition: all 0.3s var(--ease-out-quart); &:hover { transform: translateY(-4px); box-shadow: var(--shadow-hover); border-color: var(--primary-color); }}/* 绉戞妧鎰熸寜閽?*/.tech-button { background: var(--tech-gradient); border: none; border-radius: 8px; color: white; font-weight: 500; transition: all 0.3s var(--ease-out-quart); position: relative; overflow: hidden; &::before { content: ''; position: absolute;
@@ -42,6 +42,19 @@ public class DashboardController {
@Parameter(description = "是否包含测试二维码") @RequestParam(required = false, defaultValue = "false") Boolean includeTestQrcodes) { @Parameter(description = "是否包含测试二维码") @RequestParam(required = false, defaultValue = "false") Boolean includeTestQrcodes) {
try { try {
Map<String, Object> params = new HashMap<>(); 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("tourismId", tourismId);
params.put("qrcodeId", qrcodeId); params.put("qrcodeId", qrcodeId);
params.put("deviceSn", deviceSn); params.put("deviceSn", deviceSn);
@@ -64,6 +77,20 @@ public class DashboardController {
@Parameter(description = "是否包含测试二维码") @RequestParam(required = false, defaultValue = "false") Boolean includeTestQrcodes) { @Parameter(description = "是否包含测试二维码") @RequestParam(required = false, defaultValue = "false") Boolean includeTestQrcodes) {
try { try {
Map<String, Object> params = new HashMap<>(); 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("tourismId", tourismId);
params.put("includeTestQrcodes", includeTestQrcodes); params.put("includeTestQrcodes", includeTestQrcodes);
@@ -1,11 +1,16 @@
package com.central.order.feign; package com.central.order.feign;
import com.central.common.constant.ServiceNameConstants; import com.central.common.constant.ServiceNameConstants;
import com.central.common.model.Result;
import com.central.common.model.SysUser; import com.central.common.model.SysUser;
import com.central.order.feign.fallback.UserCenterServiceFallbackFactory; import com.central.order.feign.fallback.UserCenterServiceFallbackFactory;
import org.springframework.cloud.openfeign.FeignClient; import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
import java.util.Map;
/** /**
* user-center模块远程调用 * user-center模块远程调用
@@ -26,4 +31,12 @@ public interface UserCenterService {
*/ */
@GetMapping("/users/{id}") @GetMapping("/users/{id}")
SysUser findUserById(@PathVariable("id") Long 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;
} }
@@ -1,11 +1,14 @@
package com.central.order.feign.fallback; package com.central.order.feign.fallback;
import com.central.common.model.Result;
import com.central.common.model.SysUser; import com.central.common.model.SysUser;
import com.central.order.feign.UserCenterService; import com.central.order.feign.UserCenterService;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.openfeign.FallbackFactory; import org.springframework.cloud.openfeign.FallbackFactory;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.util.List;
/** /**
* 用户中心调用失败回调 * 用户中心调用失败回调
* *
@@ -26,6 +29,11 @@ public class UserCenterServiceFallbackFactory implements FallbackFactory<UserCen
public SysUser findUserById(Long id) { public SysUser findUserById(Long id) {
return null; return null;
} }
@Override
public Result<List<String>> getDescendantTenantIds(String tenantId) {
return null;
}
}; };
} }
} }
@@ -38,6 +38,15 @@ public interface DashboardMapper {
"<if test='p.endTime != null and p.endTime != \"\"'>", "<if test='p.endTime != null and p.endTime != \"\"'>",
" AND o.create_time &lt;= #{p.endTime}", " AND o.create_time &lt;= #{p.endTime}",
"</if>", "</if>",
"<choose>",
" <when test='(p.startTime == null or p.startTime == \"\") and p.statType == \"day\"'> AND o.create_time &gt;= DATE_SUB(CURDATE(), INTERVAL 6 DAY) </when>",
" <when test='(p.startTime == null or p.startTime == \"\") and p.statType == \"month\"'> AND o.create_time &gt;= DATE_SUB(CURDATE(), INTERVAL 12 MONTH) </when>",
" <when test='(p.startTime == null or p.startTime == \"\") and p.statType == \"year\"'> AND o.create_time &gt;= 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>" "</script>"
}) })
Long getTotalOrders(@Param("p") Map<String, Object> params); Long getTotalOrders(@Param("p") Map<String, Object> params);
@@ -63,6 +72,10 @@ public interface DashboardMapper {
"<if test='p.deviceSn != null and p.deviceSn != \"\"'>", "<if test='p.deviceSn != null and p.deviceSn != \"\"'>",
" AND o.device_sn = #{p.deviceSn}", " AND o.device_sn = #{p.deviceSn}",
"</if>", "</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>" "</script>"
}) })
Long getTodayOrders(@Param("p") Map<String, Object> params); Long getTodayOrders(@Param("p") Map<String, Object> params);
@@ -93,6 +106,15 @@ public interface DashboardMapper {
"<if test='p.endTime != null and p.endTime != \"\"'>", "<if test='p.endTime != null and p.endTime != \"\"'>",
" AND o.create_time &lt;= #{p.endTime}", " AND o.create_time &lt;= #{p.endTime}",
"</if>", "</if>",
"<choose>",
" <when test='(p.startTime == null or p.startTime == \"\") and p.statType == \"day\"'> AND o.create_time &gt;= DATE_SUB(CURDATE(), INTERVAL 6 DAY) </when>",
" <when test='(p.startTime == null or p.startTime == \"\") and p.statType == \"month\"'> AND o.create_time &gt;= DATE_SUB(CURDATE(), INTERVAL 12 MONTH) </when>",
" <when test='(p.startTime == null or p.startTime == \"\") and p.statType == \"year\"'> AND o.create_time &gt;= 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>" "</script>"
}) })
Long getRefundedOrders(@Param("p") Map<String, Object> params); Long getRefundedOrders(@Param("p") Map<String, Object> params);
@@ -117,6 +139,10 @@ public interface DashboardMapper {
"<if test='p.deviceSn != null and p.deviceSn != \"\"'>", "<if test='p.deviceSn != null and p.deviceSn != \"\"'>",
" AND o.device_sn = #{p.deviceSn}", " AND o.device_sn = #{p.deviceSn}",
"</if>", "</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>" "</script>"
}) })
Long getTodayRefundedOrders(@Param("p") Map<String, Object> params); Long getTodayRefundedOrders(@Param("p") Map<String, Object> params);
@@ -147,6 +173,15 @@ public interface DashboardMapper {
"<if test='p.endTime != null and p.endTime != \"\"'>", "<if test='p.endTime != null and p.endTime != \"\"'>",
" AND o.create_time &lt;= #{p.endTime}", " AND o.create_time &lt;= #{p.endTime}",
"</if>", "</if>",
"<choose>",
" <when test='(p.startTime == null or p.startTime == \"\") and p.statType == \"day\"'> AND o.create_time &gt;= DATE_SUB(CURDATE(), INTERVAL 6 DAY) </when>",
" <when test='(p.startTime == null or p.startTime == \"\") and p.statType == \"month\"'> AND o.create_time &gt;= DATE_SUB(CURDATE(), INTERVAL 12 MONTH) </when>",
" <when test='(p.startTime == null or p.startTime == \"\") and p.statType == \"year\"'> AND o.create_time &gt;= 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>" "</script>"
}) })
Long getTotalPaidOrders(@Param("p") Map<String, Object> params); Long getTotalPaidOrders(@Param("p") Map<String, Object> params);
@@ -172,6 +207,10 @@ public interface DashboardMapper {
"<if test='p.deviceSn != null and p.deviceSn != \"\"'>", "<if test='p.deviceSn != null and p.deviceSn != \"\"'>",
" AND o.device_sn = #{p.deviceSn}", " AND o.device_sn = #{p.deviceSn}",
"</if>", "</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>" "</script>"
}) })
Long getTodayPaidOrders(@Param("p") Map<String, Object> params); Long getTodayPaidOrders(@Param("p") Map<String, Object> params);
@@ -241,7 +280,11 @@ public interface DashboardMapper {
@Select({ @Select({
"<script>", "<script>",
"SELECT", "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,", " 'created' as type,",
" COUNT(*) as value", " COUNT(*) as value",
"FROM orders o", "FROM orders o",
@@ -267,10 +310,23 @@ public interface DashboardMapper {
"<if test='p.deviceSn != null and p.deviceSn != \"\"'>", "<if test='p.deviceSn != null and p.deviceSn != \"\"'>",
" AND o.device_sn = #{p.deviceSn}", " AND o.device_sn = #{p.deviceSn}",
"</if>", "</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", "UNION ALL",
"SELECT", "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,", " 'completed' as type,",
" COUNT(*) as value", " COUNT(*) as value",
"FROM orders o", "FROM orders o",
@@ -296,10 +352,23 @@ public interface DashboardMapper {
"<if test='p.deviceSn != null and p.deviceSn != \"\"'>", "<if test='p.deviceSn != null and p.deviceSn != \"\"'>",
" AND o.device_sn = #{p.deviceSn}", " AND o.device_sn = #{p.deviceSn}",
"</if>", "</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", "UNION ALL",
"SELECT", "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,", " 'refunded' as type,",
" COUNT(*) as value", " COUNT(*) as value",
"FROM orders o", "FROM orders o",
@@ -325,7 +394,16 @@ public interface DashboardMapper {
"<if test='p.deviceSn != null and p.deviceSn != \"\"'>", "<if test='p.deviceSn != null and p.deviceSn != \"\"'>",
" AND o.device_sn = #{p.deviceSn}", " AND o.device_sn = #{p.deviceSn}",
"</if>", "</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", "ORDER BY date, type",
"</script>" "</script>"
}) })
@@ -346,6 +424,10 @@ public interface DashboardMapper {
"<if test='p.tourismId != null'>", "<if test='p.tourismId != null'>",
" AND q.tourism_id = #{p.tourismId}", " AND q.tourism_id = #{p.tourismId}",
"</if>", "</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 != \"\"'>", "<if test='p.startTime != null and p.startTime != \"\"'>",
" AND o.create_time >= #{p.startTime}", " AND o.create_time >= #{p.startTime}",
"</if>", "</if>",
@@ -454,6 +536,10 @@ public interface DashboardMapper {
"<if test='p.endTime != null and p.endTime != \"\"'>", "<if test='p.endTime != null and p.endTime != \"\"'>",
" AND o.create_time &lt;= #{p.endTime}", " AND o.create_time &lt;= #{p.endTime}",
"</if>", "</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", "GROUP BY o.order_status",
"</script>" "</script>"
}) })
@@ -486,6 +572,10 @@ public interface DashboardMapper {
"<if test='p.endTime != null and p.endTime != \"\"'>", "<if test='p.endTime != null and p.endTime != \"\"'>",
" AND o.create_time &lt;= #{p.endTime}", " AND o.create_time &lt;= #{p.endTime}",
"</if>", "</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", "UNION ALL",
"SELECT", "SELECT",
" '景区分账' as type,", " '景区分账' as type,",
@@ -512,6 +602,10 @@ public interface DashboardMapper {
"<if test='p.endTime != null and p.endTime != \"\"'>", "<if test='p.endTime != null and p.endTime != \"\"'>",
" AND o.create_time &lt;= #{p.endTime}", " AND o.create_time &lt;= #{p.endTime}",
"</if>", "</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", "UNION ALL",
"SELECT", "SELECT",
" '退款金额' as type,", " '退款金额' as type,",
@@ -538,6 +632,10 @@ public interface DashboardMapper {
"<if test='p.endTime != null and p.endTime != \"\"'>", "<if test='p.endTime != null and p.endTime != \"\"'>",
" AND o.create_time &lt;= #{p.endTime}", " AND o.create_time &lt;= #{p.endTime}",
"</if>", "</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>" "</script>"
}) })
List<IncomeDataVO> getIncomeBreakdown(@Param("p") Map<String, Object> params); 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'>", "<if test='p.includeTestQrcodes == null or p.includeTestQrcodes == false'>",
" AND is_test = 0", " AND is_test = 0",
"</if>", "</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'>", "<if test='p.tourismId != null'>",
" AND tourism_id = #{p.tourismId}", " AND tourism_id = #{p.tourismId}",
"</if>", "</if>",
@@ -74,4 +74,9 @@ public interface TourismMapper extends SuperMapper<Tourism> {
@Param("maxLatitude") BigDecimal maxLatitude @Param("maxLatitude") BigDecimal maxLatitude
); );
/**
* 根据租户ID集合查询景区ID集合
*/
List<Long> findTourismIdsByTenantIds(@Param("tenantIds") List<String> tenantIds);
} }
@@ -1,7 +1,13 @@
package com.central.order.service.impl; 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.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.DashboardMapper;
import com.central.order.mapper.TourismMapper;
import com.central.order.model.Order; import com.central.order.model.Order;
import com.central.order.model.vo.*; import com.central.order.model.vo.*;
import com.central.order.service.IDashboardService; import com.central.order.service.IDashboardService;
@@ -23,9 +29,32 @@ public class DashboardServiceImpl implements IDashboardService {
private final DashboardMapper dashboardMapper; private final DashboardMapper dashboardMapper;
private final IOrderService orderService; private final IOrderService orderService;
private final TourismMapper tourismMapper;
@Override @Override
@IgnoreTenantScope
public DashboardStatisticsVO getDashboardStatistics(Map<String, Object> params) { 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(); DashboardStatisticsVO statistics = new DashboardStatisticsVO();
try { try {
@@ -187,4 +216,39 @@ public class DashboardServiceImpl implements IDashboardService {
return options; 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"> <mapper namespace="com.central.order.mapper.TourismMapper">
<select id="findList" resultType="com.central.order.model.Tourism"> <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> </select>
<resultMap id="TourismResultMap" type="com.central.order.model.Tourism"> <resultMap id="TourismResultMap" type="com.central.order.model.Tourism">
@@ -89,4 +102,17 @@
ORDER BY create_time DESC ORDER BY create_time DESC
</select> </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> </mapper>
@@ -152,6 +152,25 @@ public class TenantHierarchyController {
return t; 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) { private String normalizePathForSave(String rawPath, String parentId, String tenantId) {
try { try {
String path = stripPathSafe(rawPath); String path = stripPathSafe(rawPath);
@@ -45,10 +45,18 @@ public class TenantSwitchController {
if (user == null) { if (user == null) {
return Result.failed("用户未登录"); 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()) { if (accessibleTenantIds.isEmpty()) {
return Result.failed("用户无可访问的租户"); return Result.failed("用户无可访问的租户");
} }
@@ -5,6 +5,7 @@ import com.central.common.model.Tenant;
import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import java.util.List; import java.util.List;
@@ -146,4 +147,14 @@ public interface TenantHierarchyMapper extends BaseMapper<Tenant> {
long countTenantList(@Param("parentTenantId") String parentTenantId, long countTenantList(@Param("parentTenantId") String parentTenantId,
@Param("tenantName") String tenantName, @Param("tenantName") String tenantName,
@Param("status") Integer status); @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);
} }
@@ -23,8 +23,10 @@ import java.util.stream.Collectors;
/** /**
* 租户层级管理服务实现 * 租户层级管理服务实现
* *
* @author zlt * 仅修复本文件:
* @date 2024-12-19 * - 处理 status 为空导致的 NPE
* - 统一中文文案为 UTF-8
* - 保持接口契约不变
*/ */
@Slf4j @Slf4j
@Service @Service
@@ -33,48 +35,31 @@ public class TenantHierarchyServiceImpl implements ITenantHierarchyService {
@Autowired @Autowired
private TenantHierarchyMapper tenantHierarchyMapper; private TenantHierarchyMapper tenantHierarchyMapper;
private static final String CACHE_KEY_PREFIX = "tenant:hierarchy:";
@Override @Override
@Cacheable(value = "tenant:hierarchy", key = "#parentTenantId") @Cacheable(value = "tenant:hierarchy", key = "#parentTenantId")
public List<String> getAllSubTenantIds(String parentTenantId) { public List<String> getAllSubTenantIds(String parentTenantId) {
if (!StringUtils.hasText(parentTenantId)) { if (!StringUtils.hasText(parentTenantId)) {
return Collections.emptyList(); return Collections.emptyList();
} }
try { try {
List<String> subTenantIds = tenantHierarchyMapper.selectSubTenantIds(parentTenantId); LinkedHashSet<String> all = new LinkedHashSet<>();
if (subTenantIds == null) { ArrayDeque<String> queue = new ArrayDeque<>();
subTenantIds = new ArrayList<>(); all.add(parentTenantId);
} queue.add(parentTenantId);
// 确保包含自身 while (!queue.isEmpty()) {
if (!subTenantIds.contains(parentTenantId)) { String pid = queue.poll();
subTenantIds.add(0, parentTenantId); List<Tenant> children = tenantHierarchyMapper.selectDirectChildren(pid);
} if (children == null) continue;
for (Tenant t : children) {
// 如果基于 tenant_path 的查询结果过少,回退为按 parent_tenant_id 递归遍历 String tid = t.getTenantId();
if (subTenantIds.size() <= 1) { if (StringUtils.hasText(tid) && all.add(tid)) {
Deque<String> queue = new ArrayDeque<>(); queue.add(tid);
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);
}
}
} }
} }
} }
return new ArrayList<>(all);
log.debug("查询租户 {} 的所有子租户,数量: {}", parentTenantId, subTenantIds.size());
return subTenantIds;
} catch (Exception e) { } catch (Exception e) {
log.error("查询子租户失败: parentTenantId={}, error={}", parentTenantId, e.getMessage()); log.error("查询子孙租户失败: parentTenantId={}, error={}", parentTenantId, e.getMessage());
return Collections.singletonList(parentTenantId); return Collections.singletonList(parentTenantId);
} }
} }
@@ -84,40 +69,38 @@ public class TenantHierarchyServiceImpl implements ITenantHierarchyService {
if (tenantIds == null || tenantIds.isEmpty()) { if (tenantIds == null || tenantIds.isEmpty()) {
return Collections.emptyList(); return Collections.emptyList();
} }
try { try {
// 获取租户详细信息
List<Tenant> tenants = tenantHierarchyMapper.selectByTenantIds(tenantIds); List<Tenant> tenants = tenantHierarchyMapper.selectByTenantIds(tenantIds);
// 转换为树形节点
Map<String, TenantTreeNode> nodeMap = new HashMap<>(); Map<String, TenantTreeNode> nodeMap = new HashMap<>();
List<TenantTreeNode> rootNodes = new ArrayList<>(); List<TenantTreeNode> roots = new ArrayList<>();
// 创建所有节点 for (Tenant t : tenants) {
for (Tenant tenant : tenants) {
TenantTreeNode node = TenantTreeNode.builder() TenantTreeNode node = TenantTreeNode.builder()
.tenantId(tenant.getTenantId()) .tenantId(t.getTenantId())
.tenantName(tenant.getTenantName()) .tenantName(t.getTenantName())
.parentTenantId(tenant.getParentTenantId()) .parentTenantId(t.getParentTenantId())
.tenantType(tenant.getTenantType()) .tenantType(t.getTenantType())
.tenantLevel(tenant.getTenantLevel()) .tenantLevel(t.getTenantLevel())
.status(tenant.getStatus()) .status(t.getStatus())
.enabled(tenant.getStatus() == 1) .enabled(Objects.equals(t.getStatus(), 1))
.description(tenant.getDescription()) .description(t.getDescription())
.children(new ArrayList<>()) .children(new ArrayList<>())
.hasChildren(false) .hasChildren(false)
.childrenCount(0) .childrenCount(0)
.build(); .build();
nodeMap.put(tenant.getTenantId(), node); nodeMap.put(t.getTenantId(), node);
} }
// 构建父子关系
for (TenantTreeNode node : nodeMap.values()) { for (TenantTreeNode node : nodeMap.values()) {
if (!StringUtils.hasText(node.getParentTenantId())) { String p = node.getParentTenantId();
rootNodes.add(node); if (!StringUtils.hasText(p)) {
roots.add(node);
} else { } else {
TenantTreeNode parent = nodeMap.get(node.getParentTenantId()); TenantTreeNode parent = nodeMap.get(p);
if (parent != null) { if (parent == null) {
roots.add(node);
} else {
parent.getChildren().add(node); parent.getChildren().add(node);
parent.setHasChildren(true); parent.setHasChildren(true);
parent.setChildrenCount(parent.getChildren().size()); parent.setChildrenCount(parent.getChildren().size());
@@ -125,9 +108,7 @@ public class TenantHierarchyServiceImpl implements ITenantHierarchyService {
} }
} }
log.debug("构建租户树完成,根节点数量: {}", rootNodes.size()); return roots;
return rootNodes;
} catch (Exception e) { } catch (Exception e) {
log.error("构建租户树失败: tenantIds={}, error={}", tenantIds, e.getMessage()); log.error("构建租户树失败: tenantIds={}, error={}", tenantIds, e.getMessage());
return Collections.emptyList(); return Collections.emptyList();
@@ -139,52 +120,44 @@ public class TenantHierarchyServiceImpl implements ITenantHierarchyService {
if (!StringUtils.hasText(tenantId)) { if (!StringUtils.hasText(tenantId)) {
return null; return null;
} }
try { try {
Tenant tenant = tenantHierarchyMapper.selectByTenantId(tenantId); Tenant tenant = tenantHierarchyMapper.selectByTenantId(tenantId);
if (tenant == null) { if (tenant == null) return null;
return null;
}
// 查询子租户数量
List<Tenant> children = tenantHierarchyMapper.selectDirectChildren(tenantId); List<Tenant> children = tenantHierarchyMapper.selectDirectChildren(tenantId);
int childrenCount = children != null ? children.size() : 0; int childrenCount = children == null ? 0 : children.size();
// 查询父租户名称 String parentName = null;
String parentTenantName = null;
if (StringUtils.hasText(tenant.getParentTenantId())) { if (StringUtils.hasText(tenant.getParentTenantId())) {
Tenant parentTenant = tenantHierarchyMapper.selectByTenantId(tenant.getParentTenantId()); Tenant parent = tenantHierarchyMapper.selectByTenantId(tenant.getParentTenantId());
if (parentTenant != null) { if (parent != null) parentName = parent.getTenantName();
parentTenantName = parentTenant.getTenantName();
}
} }
return TenantInfo.builder() return TenantInfo.builder()
.tenantId(tenant.getTenantId()) .tenantId(tenant.getTenantId())
.tenantName(tenant.getTenantName()) .tenantName(tenant.getTenantName())
.parentTenantId(tenant.getParentTenantId()) .parentTenantId(tenant.getParentTenantId())
.parentTenantName(parentTenantName) .parentTenantName(parentName)
.tenantLevel(tenant.getTenantLevel()) .tenantLevel(tenant.getTenantLevel())
.tenantPath(tenant.getTenantPath()) .tenantPath(tenant.getTenantPath())
.tenantType(tenant.getTenantType()) .tenantType(tenant.getTenantType())
.tenantCode(tenant.getTenantCode()) .tenantCode(tenant.getTenantCode())
.contactPerson(tenant.getContactPerson()) .contactPerson(tenant.getContactPerson())
.contactPhone(tenant.getContactPhone()) .contactPhone(tenant.getContactPhone())
.address(tenant.getAddress()) .address(tenant.getAddress())
.description(tenant.getDescription()) .description(tenant.getDescription())
.status(tenant.getStatus()) .status(tenant.getStatus())
.statusText(tenant.getStatus() == 1 ? "启用" : "停用") .statusText(Objects.equals(tenant.getStatus(), 1) ? "启用" : "停用")
.hasChildren(childrenCount > 0) .hasChildren(childrenCount > 0)
.childrenCount(childrenCount) .childrenCount(childrenCount)
.createTime(tenant.getCreateTime() != null ? .createTime(tenant.getCreateTime() != null ?
LocalDateTime.ofInstant(tenant.getCreateTime().toInstant(), ZoneId.systemDefault()) : null) LocalDateTime.ofInstant(tenant.getCreateTime().toInstant(), ZoneId.systemDefault()) : null)
.updateTime(tenant.getUpdateTime() != null ? .updateTime(tenant.getUpdateTime() != null ?
LocalDateTime.ofInstant(tenant.getUpdateTime().toInstant(), ZoneId.systemDefault()) : null) LocalDateTime.ofInstant(tenant.getUpdateTime().toInstant(), ZoneId.systemDefault()) : null)
.creatorId(tenant.getCreatorId()) .creatorId(tenant.getCreatorId())
.build(); .build();
} catch (Exception e) { } catch (Exception e) {
log.error("获取租户信息失败: tenantId={}, error={}", tenantId, e.getMessage()); log.error("获取租户信息异常: tenantId={}, error={}", tenantId, e.getMessage());
return null; return null;
} }
} }
@@ -194,60 +167,38 @@ public class TenantHierarchyServiceImpl implements ITenantHierarchyService {
@CacheEvict(value = "tenant:hierarchy", allEntries = true) @CacheEvict(value = "tenant:hierarchy", allEntries = true)
public Result<Tenant> createTenant(Tenant tenant) { public Result<Tenant> createTenant(Tenant tenant) {
try { try {
// 校验必填字段
if (!StringUtils.hasText(tenant.getTenantId())) { if (!StringUtils.hasText(tenant.getTenantId())) {
return Result.failed("租户ID不能为空"); return Result.failed("租户ID不能为空");
} }
if (!StringUtils.hasText(tenant.getTenantName())) { if (!StringUtils.hasText(tenant.getTenantName())) {
return Result.failed("租户名称不能为空"); return Result.failed("租户名称不能为空");
} }
// 检查租户ID是否已存在
if (existsByTenantId(tenant.getTenantId())) { if (existsByTenantId(tenant.getTenantId())) {
return Result.failed("租户ID已存在"); return Result.failed("租户ID已存在");
} }
// 验证父子租户关系
if (StringUtils.hasText(tenant.getParentTenantId())) { if (StringUtils.hasText(tenant.getParentTenantId())) {
if (!validateTenantRelation(tenant.getTenantId(), tenant.getParentTenantId())) { if (!validateTenantRelation(tenant.getTenantId(), tenant.getParentTenantId())) {
return Result.failed("无效的父子租户关系"); return Result.failed("无效的父子租户关系");
} }
Tenant parent = tenantHierarchyMapper.selectByTenantId(tenant.getParentTenantId());
// 获取父租户信息,设置层级和路径 if (parent == null) return Result.failed("父租户不存在");
Tenant parentTenant = tenantHierarchyMapper.selectByTenantId(tenant.getParentTenantId()); tenant.setTenantLevel(parent.getTenantLevel() + 1);
if (parentTenant == null) { tenant.setTenantPath(parent.getTenantPath() + tenant.getTenantId() + "/");
return Result.failed("父租户不存在");
}
tenant.setTenantLevel(parentTenant.getTenantLevel() + 1);
tenant.setTenantPath(parentTenant.getTenantPath() + tenant.getTenantId() + "/");
} else { } else {
// 根租户
tenant.setTenantLevel(1); tenant.setTenantLevel(1);
tenant.setTenantPath("/" + tenant.getTenantId() + "/"); tenant.setTenantPath("/" + tenant.getTenantId() + "/");
} }
// 设置默认值 if (tenant.getStatus() == null) tenant.setStatus(1);
if (tenant.getStatus() == null) { if (!StringUtils.hasText(tenant.getTenantType())) tenant.setTenantType("COMPANY");
tenant.setStatus(1);
}
if (!StringUtils.hasText(tenant.getTenantType())) {
tenant.setTenantType("COMPANY");
}
// 设置创建人
if (LoginUserContextHolder.getUser() != null) { if (LoginUserContextHolder.getUser() != null) {
tenant.setCreatorId(LoginUserContextHolder.getUser().getId()); tenant.setCreatorId(LoginUserContextHolder.getUser().getId());
} }
// 保存租户 int r = tenantHierarchyMapper.insert(tenant);
int result = tenantHierarchyMapper.insert(tenant); if (r > 0) return Result.succeed(tenant);
if (result > 0) { return Result.failed("创建租户失败");
log.info("创建租户成功: tenantId={}, tenantName={}", tenant.getTenantId(), tenant.getTenantName());
return Result.succeed(tenant);
} else {
return Result.failed("创建租户失败");
}
} catch (Exception e) { } catch (Exception e) {
log.error("创建租户异常: tenant={}, error={}", tenant, e.getMessage()); log.error("创建租户异常: tenant={}, error={}", tenant, e.getMessage());
return Result.failed("创建租户异常: " + e.getMessage()); return Result.failed("创建租户异常: " + e.getMessage());
@@ -262,30 +213,19 @@ public class TenantHierarchyServiceImpl implements ITenantHierarchyService {
if (!StringUtils.hasText(tenant.getTenantId())) { if (!StringUtils.hasText(tenant.getTenantId())) {
return Result.failed("租户ID不能为空"); return Result.failed("租户ID不能为空");
} }
Tenant exist = tenantHierarchyMapper.selectByTenantId(tenant.getTenantId());
if (exist == null) return Result.failed("租户不存在");
// 检查租户是否存在 if (!Objects.equals(exist.getParentTenantId(), tenant.getParentTenantId())) {
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())) { if (!validateTenantRelation(tenant.getTenantId(), tenant.getParentTenantId())) {
return Result.failed("无效的父子租户关系"); return Result.failed("无效的父子租户关系");
} }
} }
// 使用主键ID执行更新,避免未传ID导致更新不到 tenant.setId(exist.getId());
tenant.setId(existingTenant.getId()); int r = tenantHierarchyMapper.updateById(tenant);
int result = tenantHierarchyMapper.updateById(tenant); if (r > 0) return Result.succeed(tenant);
if (result > 0) { return Result.failed("更新租户失败");
log.info("更新租户成功: tenantId={}", tenant.getTenantId());
return Result.succeed(tenant);
} else {
return Result.failed("更新租户失败");
}
} catch (Exception e) { } catch (Exception e) {
log.error("更新租户异常: tenant={}, error={}", tenant, e.getMessage()); log.error("更新租户异常: tenant={}, error={}", tenant, e.getMessage());
return Result.failed("更新租户异常: " + e.getMessage()); return Result.failed("更新租户异常: " + e.getMessage());
@@ -297,29 +237,12 @@ public class TenantHierarchyServiceImpl implements ITenantHierarchyService {
@CacheEvict(value = "tenant:hierarchy", allEntries = true) @CacheEvict(value = "tenant:hierarchy", allEntries = true)
public Result<Boolean> deleteTenant(String tenantId) { public Result<Boolean> deleteTenant(String tenantId) {
try { try {
if (!StringUtils.hasText(tenantId)) { if (!StringUtils.hasText(tenantId)) return Result.failed("租户ID不能为空");
return Result.failed("租户ID不能为空");
}
// 检查是否有子租户
List<Tenant> children = tenantHierarchyMapper.selectDirectChildren(tenantId); List<Tenant> children = tenantHierarchyMapper.selectDirectChildren(tenantId);
if (children != null && !children.isEmpty()) { if (children != null && !children.isEmpty()) return Result.failed("存在子租户,无法删除");
return Result.failed("存在子租户,无法删除"); int r = tenantHierarchyMapper.updateStatusByTenantId(tenantId, 0);
} if (r > 0) return Result.succeed(true);
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) { } catch (Exception e) {
log.error("删除租户异常: tenantId={}, error={}", tenantId, e.getMessage()); log.error("删除租户异常: tenantId={}, error={}", tenantId, e.getMessage());
return Result.failed("删除租户异常: " + e.getMessage()); return Result.failed("删除租户异常: " + e.getMessage());
@@ -331,19 +254,13 @@ public class TenantHierarchyServiceImpl implements ITenantHierarchyService {
try { try {
if (page == null || page < 1) page = 1; if (page == null || page < 1) page = 1;
if (size == null || size < 1) size = 10; if (size == null || size < 1) size = 10;
int offset = (page - 1) * size; int offset = (page - 1) * size;
List<Tenant> tenants = tenantHierarchyMapper.selectTenantList(parentTenantId, tenantName, status, offset, size); List<Tenant> tenants = tenantHierarchyMapper.selectTenantList(parentTenantId, tenantName, status, offset, size);
long total = tenantHierarchyMapper.countTenantList(parentTenantId, tenantName, status); tenants = tenants == null ? Collections.emptyList() : tenants;
List<TenantInfo> tenantInfos = tenants.stream()
.map(this::convertToTenantInfo)
.collect(Collectors.toList());
log.debug("查询租户列表完成,总数: {},当前页数量: {}", total, tenantInfos.size());
return Result.succeed(tenantInfos);
List<TenantInfo> list = tenants.stream().map(this::convertToTenantInfo).collect(Collectors.toList());
return Result.succeed(list);
} catch (Exception e) { } catch (Exception e) {
log.error("查询租户列表异常: error={}", e.getMessage()); log.error("查询租户列表异常: error={}", e.getMessage());
return Result.failed("查询租户列表异常: " + e.getMessage()); return Result.failed("查询租户列表异常: " + e.getMessage());
@@ -352,77 +269,51 @@ public class TenantHierarchyServiceImpl implements ITenantHierarchyService {
@Override @Override
public boolean existsByTenantId(String tenantId) { public boolean existsByTenantId(String tenantId) {
if (!StringUtils.hasText(tenantId)) { if (!StringUtils.hasText(tenantId)) return false;
return false;
}
return tenantHierarchyMapper.existsByTenantId(tenantId) > 0; return tenantHierarchyMapper.existsByTenantId(tenantId) > 0;
} }
@Override @Override
public boolean validateTenantRelation(String tenantId, String parentTenantId) { public boolean validateTenantRelation(String tenantId, String parentTenantId) {
if (!StringUtils.hasText(tenantId)) { if (!StringUtils.hasText(tenantId)) return false;
return false; if (!StringUtils.hasText(parentTenantId)) return true;
} if (tenantId.equals(parentTenantId)) return false;
// 如果没有父租户,则合法 String current = parentTenantId;
if (!StringUtils.hasText(parentTenantId)) {
return true;
}
// 不能将自己设置为父租户
if (tenantId.equals(parentTenantId)) {
return false;
}
// 检查是否会形成循环引用
String currentTenantId = parentTenantId;
Set<String> visited = new HashSet<>(); Set<String> visited = new HashSet<>();
while (current != null && !visited.contains(current)) {
while (currentTenantId != null && !visited.contains(currentTenantId)) { visited.add(current);
visited.add(currentTenantId); if (tenantId.equals(current)) return false;
Tenant p = tenantHierarchyMapper.selectByTenantId(current);
if (currentTenantId.equals(tenantId)) { current = p == null ? null : p.getParentTenantId();
// 形成循环引用
return false;
}
Tenant currentTenant = tenantHierarchyMapper.selectByTenantId(currentTenantId);
currentTenantId = currentTenant != null ? currentTenant.getParentTenantId() : null;
} }
return true; return true;
} }
/** private TenantInfo convertToTenantInfo(Tenant t) {
* 转换为 TenantInfo if (t == null) return null;
*/
private TenantInfo convertToTenantInfo(Tenant tenant) {
if (tenant == null) {
return null;
}
return TenantInfo.builder() return TenantInfo.builder()
.tenantId(tenant.getTenantId()) .tenantId(t.getTenantId())
.tenantName(tenant.getTenantName()) .tenantName(t.getTenantName())
.parentTenantId(tenant.getParentTenantId()) .parentTenantId(t.getParentTenantId())
.tenantLevel(tenant.getTenantLevel()) .tenantLevel(t.getTenantLevel())
.tenantPath(tenant.getTenantPath()) .tenantPath(t.getTenantPath())
.tenantType(tenant.getTenantType()) .tenantType(t.getTenantType())
.tenantCode(tenant.getTenantCode()) .tenantCode(t.getTenantCode())
.contactPerson(tenant.getContactPerson()) .contactPerson(t.getContactPerson())
.contactPhone(tenant.getContactPhone()) .contactPhone(t.getContactPhone())
.address(tenant.getAddress()) .address(t.getAddress())
.description(tenant.getDescription()) .description(t.getDescription())
.status(tenant.getStatus()) .status(t.getStatus())
.statusText(tenant.getStatus() == 1 ? "启用" : "停用") .statusText(Objects.equals(t.getStatus(), 1) ? "启用" : "停用")
.hasChildren(tenant.getHasChildren()) .hasChildren(t.getHasChildren())
.childrenCount(tenant.getChildrenCount()) .childrenCount(t.getChildrenCount())
.createTime(tenant.getCreateTime() != null ? .createTime(t.getCreateTime() != null ?
LocalDateTime.ofInstant(tenant.getCreateTime().toInstant(), ZoneId.systemDefault()) : null) LocalDateTime.ofInstant(t.getCreateTime().toInstant(), ZoneId.systemDefault()) : null)
.updateTime(tenant.getUpdateTime() != null ? .updateTime(t.getUpdateTime() != null ?
LocalDateTime.ofInstant(tenant.getUpdateTime().toInstant(), ZoneId.systemDefault()) : null) LocalDateTime.ofInstant(t.getUpdateTime().toInstant(), ZoneId.systemDefault()) : null)
.creatorId(tenant.getCreatorId()) .creatorId(t.getCreatorId())
.build(); .build();
} }
} }
@@ -6,6 +6,7 @@ package com.central.common.datascope.context;
*/ */
public class DataScopeContext { public class DataScopeContext {
private static final ThreadLocal<Integer> IGNORE_TENANT_COUNTER = ThreadLocal.withInitial(() -> 0); private static final ThreadLocal<Integer> IGNORE_TENANT_COUNTER = ThreadLocal.withInitial(() -> 0);
private static final ThreadLocal<Boolean> INCLUDE_CHILDREN = new ThreadLocal<>();
/** /**
* 进入“忽略租户过滤”上下文(可重入) * 进入“忽略租户过滤”上下文(可重入)
@@ -34,5 +35,18 @@ public class DataScopeContext {
Integer val = IGNORE_TENANT_COUNTER.get(); Integer val = IGNORE_TENANT_COUNTER.get();
return val != null && val > 0; return val != null && val > 0;
} }
public static void setIncludeChildren(Boolean v) {
if (v == null) { INCLUDE_CHILDREN.remove(); return; }
INCLUDE_CHILDREN.set(v);
}
public static Boolean getIncludeChildren() {
return INCLUDE_CHILDREN.get();
}
public static void clearIncludeChildren() {
INCLUDE_CHILDREN.remove();
}
} }
@@ -49,13 +49,16 @@ public class TenantDataScopeSqlHandler implements SqlHandler {
return DO_NOTHING; return DO_NOTHING;
} }
// 2) APP 用户仅限自身租户(不跨租户) // 2) APP 用户:默认仅自身;若请求显式 includeChildren=true,则包含子孙
LoginAppUser user = SecurityTenantUtils.getCurrentUser(); LoginAppUser user = SecurityTenantUtils.getCurrentUser();
Boolean includeChildrenFlag = DataScopeContext.getIncludeChildren();
if (user != null && "APP".equals(SecurityTenantUtils.getUserType(user))) { if (user != null && "APP".equals(SecurityTenantUtils.getUserType(user))) {
return String.format("%s = '%s'", columnName, anchorTenantId); if (!Boolean.TRUE.equals(includeChildrenFlag)) {
return String.format("%s = '%s'", columnName, anchorTenantId);
}
} }
// 3) 管理端:查询锚点租户及其子租户 // 3) 管理端或包含子孙:查询锚点租户及其子租户
List<String> tenantIds = null; List<String> tenantIds = null;
try { try {
ITenantHierarchyService tenantService = SpringContextHolder.getBean(ITenantHierarchyService.class); ITenantHierarchyService tenantService = SpringContextHolder.getBean(ITenantHierarchyService.class);
@@ -64,7 +67,12 @@ public class TenantDataScopeSqlHandler implements SqlHandler {
} }
} catch (Exception ignored) { } } catch (Exception ignored) { }
if (CollectionUtils.isEmpty(tenantIds)) { if (CollectionUtils.isEmpty(tenantIds)) {
tenantIds = Arrays.asList(anchorTenantId); // fallback:如未能解析子孙,按 includeChildren 显式控制
if (Boolean.FALSE.equals(includeChildrenFlag)) {
tenantIds = Arrays.asList(anchorTenantId);
} else {
tenantIds = Arrays.asList(anchorTenantId);
}
} }
String inValues = tenantIds.stream() String inValues = tenantIds.stream()
@@ -0,0 +1,41 @@
package com.central.common.filter;
import cn.hutool.core.util.StrUtil;
import com.central.common.datascope.context.DataScopeContext;
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
/**
* 解析 includeChildren 查询参数,影响本次请求的数据范围(是否包含子孙租户)。
*/
@Slf4j
@ConditionalOnClass(Filter.class)
@Order(Ordered.HIGHEST_PRECEDENCE + 18)
public class IncludeChildrenParamFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain filterChain) throws IOException, ServletException {
try {
String inc = request.getParameter("includeChildren");
if (StrUtil.isNotBlank(inc)) {
boolean b = !"0".equals(inc) && !"false".equalsIgnoreCase(inc);
DataScopeContext.setIncludeChildren(b);
log.debug("本次请求 includeChildren = {}", b);
}
filterChain.doFilter(request, response);
} finally {
DataScopeContext.clearIncludeChildren();
}
}
}
@@ -2,4 +2,4 @@ com.central.common.filter.TenantFilter
com.central.common.filter.LoginUserFilter com.central.common.filter.LoginUserFilter
com.central.common.filter.TenantParamOverrideFilter com.central.common.filter.TenantParamOverrideFilter
com.central.common.filter.TenantQueryOverrideFilter com.central.common.filter.TenantQueryOverrideFilter
com.central.common.filter.IncludeChildrenParamFilter
+72
View File
@@ -0,0 +1,72 @@
# 多租户层级查询通用SQL与函数示例
适用前提:数据库有租户层级表 `sys_tenant`,字段包含:
- `tenant_id`:租户ID(主键/唯一)
- `parent_tenant_id`:父租户ID(根为空)
- `tenant_path`:层级路径(格式:`/root/child/leaf/`)
- `status`:状态(1=启用)
注意:若 `tenant_path` 存在历史不一致或不可完全信任的情况,不建议以其作为过滤条件。
推荐做法:
1) 优先使用“基于 parent_tenant_id 的递归CTE”(MySQL 8+);
2) 或在应用层通过服务接口获取子孙租户ID列表,SQL 使用 `IN (...)` 过滤(兼容 MySQL 5.7)。
## 1) 基于 parent_tenant_id 的递归CTE(MySQL 8+,推荐)
查询给定锚点租户(含自身)以及所有子孙租户ID,并用于业务表过滤(以 `tourisms` 为例):
```sql
WITH RECURSIVE tenant_tree AS (
SELECT tenant_id
FROM sys_tenant
WHERE tenant_id = #{anchorTenantId} AND status = 1
UNION ALL
SELECT t.tenant_id
FROM sys_tenant t
INNER JOIN tenant_tree tt ON t.parent_tenant_id = tt.tenant_id
WHERE t.status = 1
)
SELECT t.*
FROM tourisms t
JOIN tenant_tree tt ON t.tenant_id = tt.tenant_id
ORDER BY t.id DESC;
```
## 2) 应用层预取子孙ID + SQL IN 过滤(兼容 MySQL 5.7)
在应用层通过服务(如 `ITenantHierarchyService#getAllSubTenantIds(anchorTenantId)`)获取集合后,SQL 使用 `IN (...)`:
```sql
SELECT *
FROM tourisms t
WHERE t.tenant_id IN (
/* 应用层传入的列表:tid_1, tid_2, ... */
/* MyBatis: <foreach collection="tenantIds" item="tid" ...> */
)
ORDER BY t.id DESC;
```
## 3) 可选:封装为函数(返回JSON数组)
MySQL函数无法直接返回结果集,可返回JSON数组再在应用侧解析:
```sql
DELIMITER //
CREATE FUNCTION fn_sub_tenants(anchor VARCHAR(64)) RETURNS JSON
BEGIN
DECLARE result JSON;
SET result = JSON_ARRAY();
-- 路径法,追加所有子孙ID
SELECT JSON_ARRAYAGG(st2.tenant_id)
INTO result
FROM sys_tenant st1
JOIN sys_tenant st2 ON st2.tenant_path LIKE CONCAT(st1.tenant_path, '%')
WHERE st1.tenant_id = anchor AND st2.status = 1;
RETURN result;
END //
DELIMITER ;
```
使用:`SELECT fn_sub_tenants(#{anchorTenantId});`,在应用层把JSON解析成列表再用于IN过滤。
建议:优先采用“递归CTE(MySQL 8+)或应用层 IN 方案”;仅在必要时考虑数据库函数,以免影响查询计划与可移植性。
+68
View File
@@ -285,3 +285,71 @@ zlt:
- 回滚与影响 - 回滚与影响
- 仅前端改动,不涉及数据库变更;若需回滚,可恢复页面与组件的旧实现。 - 仅前端改动,不涉及数据库变更;若需回滚,可恢复页面与组件的旧实现。
- 影响路由:`/system/tenant.html`、`/system/user.html`。 - 影响路由:`/system/tenant.html`、`/system/user.html`。
---
## 12. 实施记录:景区列表按租户层级过滤(2025-09-30)
为解决“景区列表未能根据当前登录用户所属租户获取其以及子孙数据”的问题,采用“有参用参、无参取当前租户”的直连式实现(不依赖过滤器/拦截器),在接口与SQL层完成改造。
- 行为规则
- 若前端传入 `tenantId`,则以该值为锚点租户,查询“自身+全部子孙租户”的景区数据。
- 若未传 `tenantId`,则取当前登录用户所属租户(`TenantContextHolder.getTenant()`)作为锚点,按相同规则查询。
- 涉及文件与改动
- `zlt-business/order-center/src/main/java/com/central/order/controller/TourismController.java:53`
- 在 `list(@RequestParam Map<String, Object> params)` 返回前补全 `params.tenantId`:当请求未传时,从 `TenantContextHolder.getTenant()` 取当前租户写入 `params`。
- `zlt-business/order-center/src/main/resources/mapper/TourismMapper.xml:6`
- 重写 `findList` 查询,去除对 `tenant_path` 的依赖;改为两级兜底的“父子关系递归”方案:
1) 若 `p.tenantIds` 存在,直接使用 `IN (...)` 过滤(由服务层通过 `ITenantHierarchyService.getAllSubTenantIds` 预先计算,兼容无CTE环境)。
2) 否则使用 MySQL 8 的 `WITH RECURSIVE` 基于 `parent_tenant_id` 递归展开子孙租户,再与 `tourisms` 连接过滤。
- 通用SQL文档:`zlt-doc/sql/tenant-descendants-queries.md:1` 已更新为优先推荐“递归CTE/IN列表”,不再推荐以 `tenant_path` 作为过滤条件。
- 服务层补充:`zlt-business/order-center/src/main/java/com/central/order/service/impl/TourismServiceImpl.java:findList`
- 统一在服务层解析锚点租户ID(请求 tenantId 优先,否则取当前登录用户租户)。
- 获取“自身+子孙租户ID集合”逻辑:
- 优先调用 `ITenantHierarchyService#getAllSubTenantIds(anchor)`;
- 若该 Bean 不存在(跨服务不共享实现),则使用本服务内 Mapper `TenantHierarchyLiteMapper` 通过 `parent_tenant_id` 进行 BFS 递归展开(MySQL 5.7 兼容)。
- 将得到的 `tenantIds` 放入 Mapper 参数,确保 XML 走 `IN (...)` 分支,无需 CTE。
- 新增:`zlt-business/order-center/src/main/java/com/central/order/mapper/TenantHierarchyLiteMapper.java`
- 仅提供 `selectDirectChildrenIds(parentTenantId)`,用于本地 BFS 递归子孙。
- 设计说明
- 不再使用 `tenant_path` 作为过滤条件,避免路径数据潜在不一致导致的误判;
- 优先应用层预取ID集合,其次SQL层递归,两者均严格基于 `parent_tenant_id` 邻接表模型;
- 不引入新的拦截器/过滤器,接口层逻辑清晰可控、便于定位问题。
- 性能与索引建议
- 为 `sys_tenant(parent_tenant_id)`、`sys_tenant(tenant_id)`、业务表如 `tourisms(tenant_id)` 建立索引;
- 大租户树场景建议启用应用层缓存 `tenantIds`,或使用“闭包表/物化路径+触发器”进一步优化。
- 测试与兼容
- 传入 `tenantId`:应返回该租户及其子孙下的景区;
- 不传 `tenantId`:应返回当前登录租户及其子孙下的景区;
- MySQL 5.7 及以下:走 `IN (...)` 方案;MySQL 8+:走 CTE 方案。
- 后续可选扩展(如需)
- 将相同过滤策略扩展到二维码、订单、素材等列表查询,统一租户视角;
- 封装 MyBatis 片段或 XML include,减少重复 SQL;
- 在业务 Service 层提供通用方法(基于 `ITenantHierarchyService`)返回子孙租户ID集合,供 Mapper 复用。
### 12-修订(2025-10-01)
- 问题复盘
- order-center 模块无租户表,历史兜底逻辑通过本地 TenantHierarchyLiteMapper 查询 sys_tenant 导致报错:Table 'order-center-test.sys_tenant' doesn't exist。
- 修复方案(UTF-8 文档与代码统一)
- 引入 Feign 远程调用,从 user-center 获取“锚点租户(含自身)+ 子孙租户ID集合”,不再在 order-center 直接访问租户表。
- user-center 新增接口:GET /tenant/hierarchy/descendants?tenantId=xxx,返回 Result<List<String>>。
- order-center 新增 Feign 客户端及降级:
- 客户端:zlt-business/order-center/src/main/java/com/central/order/feign/TenantHierarchyRemoteService.java
- 降级:zlt-business/order-center/src/main/java/com/central/order/feign/fallback/TenantHierarchyRemoteServiceFallbackFactory.java(降级仅返回自身 tenantId)
- 服务层改造:TourismServiceImpl.findList 优先使用本地 ITenantHierarchyService(若同进程可用),否则调用 Feign 远程接口获取 tenantIds,并传入 Mapper,落到 XML 的 IN (...) 分支,避免引用本地 sys_tenant。
- 影响文件
- 新增:
- zlt-business/order-center/src/main/java/com/central/order/feign/TenantHierarchyRemoteService.java
- zlt-business/order-center/src/main/java/com/central/order/feign/fallback/TenantHierarchyRemoteServiceFallbackFactory.java
- 修改:
- zlt-business/order-center/src/main/java/com/central/order/service/impl/TourismServiceImpl.java
- zlt-business/user-center/src/main/java/com/central/user/controller/TenantHierarchyController.java(新增 descendants 接口)
- 兼容性与行为
- 继续优先 IN (...) 过滤,因此不会触发 XML 中的 CTE 查询,也就不会访问不存在的 sys_tenant 表。
- 远程调用失败时自动降级为“仅自身”,与现有退化语义一致。
- 所有修改与文档均采用 UTF-8 无 BOM 编码。
+1
View File
@@ -18,6 +18,7 @@
"tsc": "tsc --noEmit" "tsc": "tsc --noEmit"
}, },
"dependencies": { "dependencies": {
"@ant-design/plots": "^2.6.5",
"@ant-design/pro-components": "1.1.1", "@ant-design/pro-components": "1.1.1",
"@ant-design/pro-layout": "^7.22.7", "@ant-design/pro-layout": "^7.22.7",
"antd": "^4.20.0", "antd": "^4.20.0",
+5
View File
@@ -2,6 +2,7 @@ import './global.less';
import React from 'react'; import React from 'react';
import { ThemeProvider } from './theme'; import { ThemeProvider } from './theme';
import { history } from 'umi'; import { history } from 'umi';
import { clearTenantCache, ensureTenantCacheTokenGuard } from '@/utils/tenantCache';
export function rootContainer(container: React.ReactNode, _args?: any) { export function rootContainer(container: React.ReactNode, _args?: any) {
return React.createElement(ThemeProvider, null, container); return React.createElement(ThemeProvider, null, container);
@@ -21,6 +22,7 @@ export const request: any = {
try { try {
sessionStorage.removeItem('access_token'); sessionStorage.removeItem('access_token');
sessionStorage.removeItem('current_user'); sessionStorage.removeItem('current_user');
clearTenantCache();
} catch {} } catch {}
const pathname = typeof window !== 'undefined' ? window.location.pathname : '/'; const pathname = typeof window !== 'undefined' ? window.location.pathname : '/';
const search = typeof window !== 'undefined' ? window.location.search : ''; const search = typeof window !== 'undefined' ? window.location.search : '';
@@ -39,6 +41,8 @@ export const request: any = {
const token = sessionStorage.getItem('access_token'); const token = sessionStorage.getItem('access_token');
const headers: Record<string, string> = { ...(options?.headers as any) }; const headers: Record<string, string> = { ...(options?.headers as any) };
if (token) headers['Authorization'] = `Bearer ${token}`; if (token) headers['Authorization'] = `Bearer ${token}`;
// 确保缓存与当前 Token 一致(Token 变化则清缓存)
ensureTenantCacheTokenGuard();
return { url, options: { ...options, headers } }; return { url, options: { ...options, headers } };
}, },
], ],
@@ -65,6 +69,7 @@ export const request: any = {
try { try {
sessionStorage.removeItem('access_token'); sessionStorage.removeItem('access_token');
sessionStorage.removeItem('current_user'); sessionStorage.removeItem('current_user');
clearTenantCache();
} catch {} } catch {}
const pathname = typeof window !== 'undefined' ? window.location.pathname : '/'; const pathname = typeof window !== 'undefined' ? window.location.pathname : '/';
const search = typeof window !== 'undefined' ? window.location.search : ''; const search = typeof window !== 'undefined' ? window.location.search : '';
@@ -1,51 +1,79 @@
import React, { useEffect, useState } from 'react'; import React, { useEffect, useState } from 'react';
import { Space, Button, TreeSelect, Checkbox, message } from 'antd'; import { Space, Button, TreeSelect, Checkbox, message } from 'antd';
import { tenantApi, TenantTreeNode } from '@/services/tenant'; import { tenantApi } from '@/services/tenant';
interface Props { interface TenantNode {
// 租户或“包含下级”变化后的回调(外部将 tenantId/includeChildren 透传到请求参数) tenantId?: string;
onChanged?: (tenantId: string, includeChildren: boolean) => void; tenantName?: string;
// 可选:是否调用后端切换查询上下文(默认 false,不建议启用) children?: TenantNode[];
useSwitchTenant?: boolean; status?: number | boolean;
} }
const TenantScopeFilter: React.FC<Props> = ({ onChanged, useSwitchTenant = false }) => { interface Props {
const [tree, setTree] = useState<TenantTreeNode[]>([]); // 租户或“包含子租户”变化后回调(外部将 tenantId/includeChildren 透传至请求参数)
onChanged?: (tenantId: string, includeChildren: boolean) => void;
// 可选:是否调用后端切换查询上下文(默认 false)
useSwitchTenant?: boolean;
// 自动应用(变更即触发回调,隐藏“应用”按钮)
autoApply?: boolean;
}
const TenantScopeFilter: React.FC<Props> = ({ onChanged, useSwitchTenant = false, autoApply = false }) => {
const [tree, setTree] = useState<TenantNode[]>([]);
const [tenantId, setTenantId] = useState<string | undefined>(); const [tenantId, setTenantId] = useState<string | undefined>();
const [includeChildren, setIncludeChildren] = useState(true); const [includeChildren, setIncludeChildren] = useState<boolean>(true);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState<boolean>(false);
useEffect(() => { useEffect(() => {
(async () => { (async () => {
setLoading(true); setLoading(true);
try { try {
const [treeRes, currentRes] = await Promise.all([ // 获取可访问租户树
tenantApi.getAccessibleTenants(), const treeRes: any = await tenantApi.getAccessibleTenants();
tenantApi.getCurrentTenant(), let list: TenantNode[] = [];
]); if (Array.isArray(treeRes)) list = treeRes as any;
if ((treeRes as any)?.success) setTree((treeRes as any).data || []); else if (Array.isArray(treeRes?.data)) list = treeRes.data as any;
if ((currentRes as any)?.success) setTenantId((currentRes as any).data?.tenantId); else if (treeRes?.resp_code === 0 && Array.isArray(treeRes?.data)) list = treeRes.data as any;
setTree(list || []);
// 获取当前租户
const curRes: any = await tenantApi.getCurrentTenant();
const curId = curRes?.data?.tenantId || (curRes?.resp_code === 0 ? curRes?.data?.tenantId : undefined);
if (curId) setTenantId(curId);
} catch {
// 忽略错误,展示空树
} finally { } finally {
setLoading(false); setLoading(false);
} }
})(); })();
}, []); }, []);
const toTreeData = (nodes: TenantTreeNode[]): any[] => // 自动应用:参数变化即触发回调
nodes?.map((n) => ({ useEffect(() => {
title: n.tenantName, if (!autoApply) return;
if (!tenantId) return;
onChanged?.(tenantId, includeChildren);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [tenantId, includeChildren, autoApply]);
const toTreeData = (nodes?: TenantNode[]): any[] =>
(nodes || []).map((n) => ({
title: n.tenantName && n.tenantId ? `${n.tenantName} (${n.tenantId})` : (n.tenantName || n.tenantId || '-'),
value: n.tenantId, value: n.tenantId,
key: n.tenantId, key: n.tenantId,
children: n.children ? toTreeData(n.children) : undefined, children: n.children ? toTreeData(n.children) : undefined,
})) || []; }));
const handleApply = async () => { const handleApply = async () => {
if (!tenantId) return; if (!tenantId) return;
try { try {
if (useSwitchTenant) { if (useSwitchTenant) {
const res = await tenantApi.switchTenant(tenantId); const res: any = await tenantApi.switchTenant(tenantId);
if ((res as any)?.success) message.success('租户范围已更新'); if (!(res?.success ?? res?.resp_code === 0)) {
else { message.error((res as any)?.msg || '切换失败'); return; } message.error(res?.msg || '切换失败');
return;
}
message.success('租户范围已更新');
} }
onChanged?.(tenantId, includeChildren); onChanged?.(tenantId, includeChildren);
} catch { } catch {
@@ -57,8 +85,9 @@ const TenantScopeFilter: React.FC<Props> = ({ onChanged, useSwitchTenant = false
<Space> <Space>
<TreeSelect <TreeSelect
style={{ minWidth: 260 }} style={{ minWidth: 260 }}
treeDefaultExpandAll showSearch
loading={loading} loading={loading}
treeNodeFilterProp="title"
dropdownStyle={{ maxHeight: 400, overflow: 'auto' }} dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
placeholder="选择租户(含子租户)" placeholder="选择租户(含子租户)"
value={tenantId} value={tenantId}
@@ -66,7 +95,9 @@ const TenantScopeFilter: React.FC<Props> = ({ onChanged, useSwitchTenant = false
treeData={toTreeData(tree)} treeData={toTreeData(tree)}
/> />
<Checkbox checked={includeChildren} onChange={(e) => setIncludeChildren(e.target.checked)}>包含子租户</Checkbox> <Checkbox checked={includeChildren} onChange={(e) => setIncludeChildren(e.target.checked)}>包含子租户</Checkbox>
<Button type="primary" onClick={handleApply}>应用</Button> {!autoApply && (
<Button type="primary" onClick={handleApply}>应用</Button>
)}
</Space> </Space>
); );
}; };
@@ -1,6 +1,7 @@
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';
export interface TenantSelectorProps { export interface TenantSelectorProps {
nameTenant?: string; nameTenant?: string;
@@ -15,12 +16,17 @@ export interface TenantSelectorProps {
const toTreeData = (nodes?: TenantTreeNode[] | any): any[] => { const toTreeData = (nodes?: TenantTreeNode[] | any): any[] => {
const arr: TenantTreeNode[] = Array.isArray(nodes) ? nodes : []; const arr: TenantTreeNode[] = Array.isArray(nodes) ? nodes : [];
return arr.map((n) => ({ return arr.map((n) => {
title: (n as any)?.tenantId, // 显示租户ID const id = (n as any)?.tenantId as string | undefined;
value: (n as any)?.tenantId, const name = (n as any)?.tenantName as string | undefined;
key: (n as any)?.tenantId, const title = name && id ? `${name} (${id})` : (name || id || '-');
children: Array.isArray((n as any)?.children) && (n as any).children!.length ? toTreeData((n as any).children) : undefined, return {
})); title,
value: id,
key: id,
children: Array.isArray((n as any)?.children) && (n as any).children!.length ? toTreeData((n as any).children) : undefined,
};
});
}; };
const TenantSelector: React.FC<TenantSelectorProps> = ({ const TenantSelector: React.FC<TenantSelectorProps> = ({
@@ -39,12 +45,16 @@ const TenantSelector: React.FC<TenantSelectorProps> = ({
(async () => { (async () => {
setLoading(true); setLoading(true);
try { try {
const treeRes: any = await tenantApi.getAccessibleTenants(); // 优先从缓存读取可访问租户树
let list: TenantTreeNode[] = []; let list: TenantTreeNode[] = (getTenantTreeCache() as any) || [];
if (typeof treeRes?.success !== 'undefined') { if (!list || list.length === 0) {
list = treeRes.success ? (treeRes.data || []) : []; const treeRes: any = await tenantApi.getAccessibleTenants();
} else if (Array.isArray(treeRes)) { if (typeof treeRes?.success !== 'undefined') {
list = treeRes as TenantTreeNode[]; list = treeRes.success ? (treeRes.data || []) : [];
} else if (Array.isArray(treeRes)) {
list = treeRes as TenantTreeNode[];
}
if (list && list.length) setTenantTreeCache(list as any);
} }
if (!list || list.length === 0) { if (!list || list.length === 0) {
// 回退:仅当前租户 // 回退:仅当前租户
@@ -62,24 +72,92 @@ const TenantSelector: React.FC<TenantSelectorProps> = ({
if (list && list.length && !form?.getFieldValue?.(nameTenant)) { if (list && list.length && !form?.getFieldValue?.(nameTenant)) {
try { form?.setFieldsValue?.({ [nameTenant]: list[0].tenantId, [nameIncludeChildren]: true }); } catch {} 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);
}));
return resultChildren;
};
try { try {
await Promise.all( const level2 = await loadChildrenFor(list);
(list || []).map(async (node: any) => { await loadChildrenFor(level2);
if (!node || Array.isArray(node.children)) return; } catch {}
const pid = node.tenantId; // 补齐根节点状态,随后过滤仅显示启用(status=1)
if (!pid) return; try {
try { await Promise.all((list || []).map(async (node: any) => {
const res: any = await tenantApi.getTenantList({ parentTenantId: pid, current: 1, pageSize: 1000 } as any); if (node?.status == null && node?.tenantId) {
const children = res?.data?.data || []; // 先看缓存,无则请求
if (children && children.length) { const cached = getTenantDetailCache(node.tenantId);
node.children = children.map((c: any) => ({ tenantId: c.tenantId, tenantName: c.tenantName })); if (typeof (cached as any)?.status !== 'undefined') {
} node.status = (cached as any).status as any;
} catch {} } 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 {}
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 {}
setTree(list || []);
} catch (e) { } catch (e) {
message.warn('获取租户列表失败'); message.warn('获取租户列表失败');
} finally { } finally {
@@ -95,7 +173,8 @@ const TenantSelector: React.FC<TenantSelectorProps> = ({
<Form.Item name={nameTenant} label={labelTenant} rules={rulesTenant as any}> <Form.Item name={nameTenant} label={labelTenant} rules={rulesTenant as any}>
<TreeSelect <TreeSelect
style={{ minWidth: 260 }} style={{ minWidth: 260 }}
treeDefaultExpandAll showSearch
treeNodeFilterProp='title'
loading={loading} loading={loading}
dropdownStyle={{ maxHeight: 400, overflow: 'auto' }} dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
placeholder='选择租户(默认当前租户)' placeholder='选择租户(默认当前租户)'
@@ -17,6 +17,7 @@ import {
import { Link, useLocation, history } from 'umi'; import { Link, useLocation, history } from 'umi';
import ProLayout, { MenuDataItem } from '@ant-design/pro-layout'; import ProLayout, { MenuDataItem } from '@ant-design/pro-layout';
import { fetchMenuData, outLogin } from '@/services/login'; import { fetchMenuData, outLogin } from '@/services/login';
import { clearTenantCache } from '@/utils/tenantCache';
import { useTheme } from '@/theme'; import { useTheme } from '@/theme';
import { ThemeSwitch } from '@/components/ui'; import { ThemeSwitch } from '@/components/ui';
@@ -57,16 +58,15 @@ const BasicLayout: React.FC = (props: any) => {
const cand = (m.path || m.url || '').trim(); const cand = (m.path || m.url || '').trim();
if (!cand) return undefined; if (!cand) return undefined;
const lower = cand.toLowerCase(); const lower = cand.toLowerCase();
if (lower.startsWith('http')) return cand; // 外链 if (lower.startsWith('http')) return cand; // 澶栭摼
if (lower.endsWith('.html')) return cand.startsWith('/') ? cand : `/${cand}`; // 静态路由 if (lower.endsWith('.html')) return cand.startsWith('/') ? cand : `/${cand}`; // 闈欐€佽矾鐢? if (lower === '/welcome' || lower === 'welcome') return '/welcome';
if (lower === '/welcome' || lower === 'welcome') return '/welcome'; // 鍏煎鍚庣鑿滃崟鏈甫 .html 鐨勫彾瀛愯矾鐢憋紝渚嬪 /system/tenant => /system/tenant.html
// 兼容后端菜单未带 .html 的叶子路由,例如 /system/tenant => /system/tenant.html
const ensureSlash = cand.startsWith('/') ? cand : `/${cand}`; const ensureSlash = cand.startsWith('/') ? cand : `/${cand}`;
const parts = ensureSlash.split('/').filter(Boolean); const parts = ensureSlash.split('/').filter(Boolean);
if (childrenLen === 0 && parts.length >= 2) { if (childrenLen === 0 && parts.length >= 2) {
return `${ensureSlash}.html`; return `${ensureSlash}.html`;
} }
return undefined; // 作为分组 return undefined; // 浣滀负鍒嗙粍
}; };
const getIcon = (p?: string) => { const getIcon = (p?: string) => {
@@ -96,7 +96,7 @@ const BasicLayout: React.FC = (props: any) => {
const item: MenuDataItem = { const item: MenuDataItem = {
key: keyStr, key: keyStr,
name: menu.name || `菜单${index + 1}`, name: menu.name || `鑿滃崟${index + 1}`,
path, path,
icon: getIcon(path), icon: getIcon(path),
children: childrenList.map((child: MenuNode, i: number) => normalize(child, i, keyStr)), children: childrenList.map((child: MenuNode, i: number) => normalize(child, i, keyStr)),
@@ -105,18 +105,24 @@ const BasicLayout: React.FC = (props: any) => {
}; };
if (!loaded) return []; if (!loaded) return [];
const list = menus && menus.length ? menus : [{ name: '欢迎页', url: '/welcome', id: 'welcome-default' }]; const list = menus && menus.length ? menus : [{ name: '首页', url: '/welcome', id: 'welcome-default' }];
return list.map((m, i) => normalize(m, i)); const rendered = list.map((m, i) => normalize(m, i));
const hasHome = rendered.some((r) => r.path === '/welcome');
if (!hasHome) {
rendered.unshift({ key: 'welcome-fixed', name: '首页', path: '/welcome', icon: <DashboardOutlined /> });
}
return rendered;
}, [menus, mode, loaded]); }, [menus, mode, loaded]);
const rightContentRender = () => ( const rightContentRender = () => (
<Space size="middle"> <Space size="middle">
<Link to="/welcome" style={{ color: 'var(--text-primary)' }}>首页</Link>
<ThemeSwitch mode={mode} onToggle={toggle} /> <ThemeSwitch mode={mode} onToggle={toggle} />
<Dropdown <Dropdown
menu={{ menu={{
items: [ items: [
{ key: 'profile', icon: <UserOutlined />, label: '个人中心' }, { key: 'profile', icon: <UserOutlined />, label: '个人中心' },
{ key: 'settings', icon: <SettingOutlined />, label: '系统设置' }, { key: 'settings', icon: <SettingOutlined />, label: '设置' },
{ type: 'divider' as any }, { type: 'divider' as any },
{ {
key: 'logout', key: 'logout',
@@ -127,6 +133,7 @@ const BasicLayout: React.FC = (props: any) => {
try { try {
sessionStorage.removeItem('access_token'); sessionStorage.removeItem('access_token');
sessionStorage.removeItem('current_user'); sessionStorage.removeItem('current_user');
clearTenantCache();
} catch {} } catch {}
message.success('已退出登录'); message.success('已退出登录');
history.push('/user/login'); history.push('/user/login');
@@ -175,6 +182,7 @@ const BasicLayout: React.FC = (props: any) => {
); );
}} }}
headerTitleRender={(logo, title) => ( headerTitleRender={(logo, title) => (
<Link to="/welcome" style={{ textDecoration: 'none' }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 12, fontWeight: 600 }}> <div style={{ display: 'flex', alignItems: 'center', gap: 12, fontWeight: 600 }}>
<div <div
style={{ style={{
@@ -192,6 +200,7 @@ const BasicLayout: React.FC = (props: any) => {
</div> </div>
<span style={{ fontSize: 18, color: 'var(--text-primary)', fontWeight: 700 }}>{title}</span> <span style={{ fontSize: 18, color: 'var(--text-primary)', fontWeight: 700 }}>{title}</span>
</div> </div>
</Link>
)} )}
token={{ token={{
sider: { sider: {
@@ -217,3 +226,6 @@ const BasicLayout: React.FC = (props: any) => {
}; };
export default BasicLayout; export default BasicLayout;
+161 -98
View File
@@ -1,123 +1,186 @@
import React, { useEffect, useState } from 'react'; import React, { useEffect, useRef, useState } from 'react';
import { Card, Space, Typography, Row, Col, Statistic, Progress, Button } from 'antd'; import { Card, Space, Typography, Row, Col, Statistic, Segmented, Button, message } from 'antd';
import { RocketOutlined, TeamOutlined, AppstoreOutlined, CloudServerOutlined, TrophyOutlined, ThunderboltOutlined, GlobalOutlined, SafetyOutlined } from '@ant-design/icons'; import { ShoppingCartOutlined, PayCircleOutlined, ReloadOutlined } from '@ant-design/icons';
import { Line, Pie } from '@ant-design/plots';
import TenantScopeFilter from '@/components/TenantScopeFilter'; import TenantScopeFilter from '@/components/TenantScopeFilter';
import { dashboardApi } from '@/services/dashboard';
const { Title, Paragraph } = Typography; const { Title, Text } = Typography;
const Welcome: React.FC = () => { const Welcome: React.FC = () => {
const [time, setTime] = useState(new Date()); const [tenantId, setTenantId] = useState<string>();
const [includeChildren, setIncludeChildren] = useState<boolean>(true);
const [statType, setStatType] = useState<'day' | 'month' | 'year'>('day');
const [loading, setLoading] = useState<boolean>(false);
const [pageLoading, setPageLoading] = useState<boolean>(true);
const firstLoadRef = useRef(true);
const [stat, setStat] = useState<any>({ orderStats: {}, chartStats: {} });
const load = async () => {
if (firstLoadRef.current) setPageLoading(true);
setLoading(true);
try {
const res: any = await dashboardApi.statistics({ tenantId, includeChildren, statType });
setStat(res?.data || res);
} catch (e) {
message.error('加载统计失败');
} finally {
setLoading(false);
if (firstLoadRef.current) {
firstLoadRef.current = false;
setPageLoading(false);
}
}
};
// 仅当选择了租户后再拉取,避免进入页面出现“空 -> 有”的闪动
useEffect(() => { useEffect(() => {
const timer = setInterval(() => setTime(new Date()), 1000); if (!tenantId) return;
return () => clearInterval(timer); load();
}, []); // eslint-disable-next-line react-hooks/exhaustive-deps
}, [tenantId, includeChildren, statType]);
const stats = [ const orderStats = stat?.orderStats || {};
{ title: '今日订单', value: 1234, icon: <AppstoreOutlined />, color: '#667eea' }, const chartStats = stat?.chartStats || {};
{ title: '活跃用户', value: 856, icon: <TeamOutlined />, color: '#764ba2' },
{ title: '设备在线', value: 98, suffix: '%', icon: <CloudServerOutlined />, color: '#f093fb' },
{ title: '系统可用率', value: 99.9, suffix: '%', icon: <SafetyOutlined />, color: '#4facfe' },
];
const quickActions = [ const trendData = chartStats?.orderTrend || [];
{ title: '新增订单', icon: <AppstoreOutlined />, color: '#667eea' }, const distributionData = chartStats?.orderDistribution || [];
{ title: '用户管理', icon: <TeamOutlined />, color: '#764ba2' },
{ title: '设备监控', icon: <CloudServerOutlined />, color: '#f093fb' }, const trendConfig: any = {
{ title: '系统设置', icon: <SafetyOutlined />, color: '#4facfe' }, data: trendData,
]; xField: 'date',
yField: 'value',
seriesField: 'type',
smooth: true,
height: 300,
legend: { position: 'top' },
tooltip: { shared: true },
animation: false,
};
const distributionConfig: any = {
data: distributionData,
angleField: 'value',
colorField: 'type',
radius: 0.9,
label: { type: 'outer', content: '{name}\n{percentage}' },
animation: false,
};
return ( return (
<div className="page-enter" style={{ padding: 24 }}> <div className="page-enter" style={{ padding: 24 }}>
<Card className="modern-card" style={{ background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)', border: 'none', marginBottom: 24, color: 'white' }}> {/* 顶部工具区:左标题,右侧筛选/粒度/刷新 */}
<Row align="middle" justify="space-between"> <Card className="modern-card" style={{ marginBottom: 16 }}>
<Col> <Row align="middle" justify="space-between" gutter={[12, 12]}>
<Space direction="vertical" size={8}> <Col flex="none">
<Title level={2} style={{ color: 'white', margin: 0 }}> <Title level={4} style={{ margin: 0 }}>首页统计</Title>
<RocketOutlined style={{ marginRight: 12 }} /> 欢迎使用 Go-Fly Admin
</Title>
<Paragraph style={{ color: 'rgba(255,255,255,0.8)', margin: 0, fontSize: 16 }}>现代化的智能管理平台 · 科技驱动未来</Paragraph>
<Paragraph style={{ color: 'rgba(255,255,255,0.6)', margin: 0 }}>当前时间:{time.toLocaleString()}</Paragraph>
</Space>
</Col> </Col>
<Col> <Col flex="auto">
<TenantScopeFilter useSwitchTenant onChanged={() => { /* 切换后由后端上下文生效 */ }} /> <Space style={{ width: '100%', justifyContent: 'flex-end', flexWrap: 'wrap' }} size={12}>
<TenantScopeFilter autoApply onChanged={(tid, inc) => { setTenantId(tid); setIncludeChildren(!!inc); }} />
<Space>
<span>统计粒度</span>
<Segmented
options={[
{ label: '日', value: 'day' },
{ label: '月', value: 'month' },
{ label: '年', value: 'year' },
]}
value={statType}
onChange={(val) => setStatType(val as any)}
/>
</Space>
<Button type="primary" icon={<ReloadOutlined />} loading={loading && !pageLoading} onClick={load}>刷新</Button>
</Space>
</Col> </Col>
</Row> </Row>
</Card> </Card>
<Row gutter={[24, 24]} style={{ marginBottom: 24 }}> {/* KPI 指标卡:两列均分,内容居中,不留空白 */}
{stats.map((stat, index) => ( <Row gutter={[16, 16]}>
<Col xs={12} sm={12} md={6} key={index}>
<Card className="modern-card" style={{ textAlign: 'center', borderLeft: `4px solid ${stat.color}`, background: 'var(--bg-card)' }}>
<div style={{ color: stat.color, fontSize: 24, marginBottom: 8 }}>{stat.icon}</div>
<Statistic title={stat.title} value={stat.value} suffix={stat.suffix} valueStyle={{ color: 'var(--text-primary)', fontSize: 28, fontWeight: 'bold' }} />
</Card>
</Col>
))}
</Row>
<Row gutter={[24, 24]}>
<Col xs={24} md={12}> <Col xs={24} md={12}>
<Card className="modern-card" title={<span style={{ color: 'var(--text-primary)' }}><ThunderboltOutlined style={{ marginRight: 8, color: '#667eea' }} />系统状态</span>}> <Card loading={pageLoading}>
<Space direction="vertical" style={{ width: '100%' }} size={16}> <Space direction="vertical" style={{ width: '100%' }} size={12}>
<div> <Space align="center" size={8}>
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}> <ShoppingCartOutlined />
<span style={{ color: 'var(--text-secondary)' }}>CPU 使用率</span> <Text strong>订单</Text>
<span style={{ color: 'var(--text-primary)' }}>45%</span> </Space>
</div> <Row gutter={8} align="middle" style={{ width: '100%' }}>
<Progress percent={45} strokeColor="#667eea" /> <Col xs={12} sm={10} md={10}><Text type="secondary">总订单数</Text></Col>
</div> <Col xs={12} sm={14} md={14} style={{ textAlign: 'right' }}>
<div> <Statistic value={orderStats.totalOrders || 0} valueStyle={{ fontWeight: 600, whiteSpace: 'nowrap' }} groupSeparator="," />
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
<span style={{ color: 'var(--text-secondary)' }}>内存使用率</span>
<span style={{ color: 'var(--text-primary)' }}>68%</span>
</div>
<Progress percent={68} strokeColor="#764ba2" />
</div>
<div>
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
<span style={{ color: 'var(--text-secondary)' }}>磁盘使用率</span>
<span style={{ color: 'var(--text-primary)' }}>32%</span>
</div>
<Progress percent={32} strokeColor="#f093fb" />
</div>
</Space>
</Card>
</Col>
<Col xs={24} md={12}>
<Card className="modern-card" title={<span style={{ color: 'var(--text-primary)' }}><TrophyOutlined style={{ marginRight: 8, color: '#667eea' }} />快捷操作</span>}>
<Row gutter={[16, 16]}>
{quickActions.map((action, index) => (
<Col span={12} key={index}>
<Button
block
size="large"
className="tech-button"
style={{ height: 64, background: `linear-gradient(135deg, ${action.color}33, ${action.color}11)`, border: `1px solid ${action.color}44`, color: action.color, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center' }}
>
<div style={{ fontSize: 20, marginBottom: 4 }}>{action.icon}</div>
<div style={{ fontSize: 12 }}>{action.title}</div>
</Button>
</Col> </Col>
))} </Row>
</Row> <Row gutter={8} align="middle" style={{ width: '100%' }}>
<Col xs={12} sm={10} md={10}><Text type="secondary">退款订单数</Text></Col>
<Col xs={12} sm={14} md={14} style={{ textAlign: 'right' }}>
<Statistic value={orderStats.refundedOrders || 0} valueStyle={{ fontWeight: 600, whiteSpace: 'nowrap' }} groupSeparator="," />
</Col>
</Row>
<Row gutter={8} align="middle" style={{ width: '100%' }}>
<Col xs={12} sm={10} md={10}><Text type="secondary">今日订单</Text></Col>
<Col xs={12} sm={14} md={14} style={{ textAlign: 'right' }}>
<Statistic value={orderStats.todayOrders || 0} valueStyle={{ fontWeight: 600, whiteSpace: 'nowrap' }} groupSeparator="," />
</Col>
</Row>
<Row gutter={8} align="middle" style={{ width: '100%' }}>
<Col xs={12} sm={10} md={10}><Text type="secondary">今日退款</Text></Col>
<Col xs={12} sm={14} md={14} style={{ textAlign: 'right' }}>
<Statistic value={orderStats.todayRefundedOrders || 0} valueStyle={{ fontWeight: 600, whiteSpace: 'nowrap' }} groupSeparator="," />
</Col>
</Row>
</Space>
</Card>
</Col>
<Col xs={24} md={12}>
<Card loading={pageLoading}>
<Space direction="vertical" style={{ width: '100%' }} size={12}>
<Space align="center" size={8}>
<PayCircleOutlined />
<Text strong>收入</Text>
</Space>
<Row gutter={8} align="middle" style={{ width: '100%' }}>
<Col xs={12} sm={10} md={10}><Text type="secondary">订单总金额(元)</Text></Col>
<Col xs={12} sm={14} md={14} style={{ textAlign: 'right' }}>
<Statistic value={(orderStats.totalAmount || 0) / 100} precision={2} valueStyle={{ fontWeight: 600, whiteSpace: 'nowrap' }} groupSeparator="," />
</Col>
</Row>
<Row gutter={8} align="middle" style={{ width: '100%' }}>
<Col xs={12} sm={10} md={10}><Text type="secondary">退款金额(元)</Text></Col>
<Col xs={12} sm={14} md={14} style={{ textAlign: 'right' }}>
<Statistic value={(orderStats.refundAmount || 0) / 100} precision={2} valueStyle={{ fontWeight: 600, whiteSpace: 'nowrap' }} groupSeparator="," />
</Col>
</Row>
<Row gutter={8} align="middle" style={{ width: '100%' }}>
<Col xs={12} sm={10} md={10}><Text type="secondary">净收入(元)</Text></Col>
<Col xs={12} sm={14} md={14} style={{ textAlign: 'right' }}>
<Statistic value={(orderStats.netIncome || 0) / 100} precision={2} valueStyle={{ fontWeight: 600, whiteSpace: 'nowrap' }} groupSeparator="," />
</Col>
</Row>
<Row gutter={8} align="middle" style={{ width: '100%' }}>
<Col xs={12} sm={10} md={10}><Text type="secondary">净订单数(笔)</Text></Col>
<Col xs={12} sm={14} md={14} style={{ textAlign: 'right' }}>
<Statistic value={(orderStats.totalOrders || 0) - (orderStats.refundedOrders || 0)} valueStyle={{ fontWeight: 600, whiteSpace: 'nowrap' }} groupSeparator="," />
</Col>
</Row>
</Space>
</Card> </Card>
</Col> </Col>
</Row> </Row>
<Card className="modern-card" style={{ marginTop: 24 }} title={<span style={{ color: 'var(--text-primary)' }}><GlobalOutlined style={{ marginRight: 8, color: '#667eea' }} />平台特性</span>}> {/* 图表区:趋势 + 状态分布 */}
<Row gutter={[24, 24]}> <Row gutter={[16, 16]} style={{ marginTop: 16 }}>
<Col xs={24} sm={12} md={8}> <Col xs={24} md={16}>
<div style={{ textAlign: 'center', padding: 16 }}> <Card title="订单趋势(创建/完成/退款)" loading={pageLoading}>
<div style={{ fontSize: 32, color: '#667eea', marginBottom: 12 }}><RocketOutlined /></div> <Line {...trendConfig} />
<Title level={4} style={{ color: 'var(--text-primary)' }}>高性能架构</Title> </Card>
<Paragraph style={{ color: 'var(--text-secondary)' }}>基于微服务架构,支持高并发访问,确保系统稳定运行</Paragraph> </Col>
</div> <Col xs={24} md={8}>
</Col> <Card title="订单状态分布" loading={pageLoading}>
</Row> <Pie {...distributionConfig} />
</Card> </Card>
</Col>
</Row>
</div> </div>
); );
}; };
@@ -83,7 +83,7 @@ const TourismPage: React.FC = () => {
onTenantChanged={(tenantId, includeChildren) => { onTenantChanged={(tenantId, includeChildren) => {
setParams((prev) => ({ ...(prev || {}), tenantId, includeChildren })); setParams((prev) => ({ ...(prev || {}), tenantId, includeChildren }));
}} }}
onFinish={async (values) => setParams(values)} onFinish={async (values) => setParams((prev) => ({ ...(prev || {}), ...values }))}
> >
<ProFormText name="tourismName" label="景区名称" placeholder="请输入景区名称" /> <ProFormText name="tourismName" label="景区名称" placeholder="请输入景区名称" />
</SearchBarPlus> </SearchBarPlus>
@@ -149,4 +149,3 @@ const TourismPage: React.FC = () => {
}; };
export default TourismPage; export default TourismPage;
@@ -56,12 +56,16 @@ const TenantTable: React.FC<TenantTableProps> = ({ parentTenantId, actionRef, on
columns={columns} columns={columns}
toolBarRender={false} toolBarRender={false}
request={async (p) => { request={async (p) => {
const res = await tenantApi.getTenantList({ parentTenantId, tenantName: (p as any).tenantName, status: (p as any).status as any, current: (p as any).current, pageSize: (p as any).pageSize }); // 默认按启用筛选;当未选择时传 1
const status = (p as any)?.status ?? 1;
const res = await tenantApi.getTenantList({ parentTenantId, tenantName: (p as any).tenantName, status: status as any, current: (p as any).current, pageSize: (p as any).pageSize });
const list = (res as any)?.data?.data || []; const list = (res as any)?.data?.data || [];
const total = (res as any)?.data?.total || list.length; const total = (res as any)?.data?.total || list.length;
return { data: list, total, success: true }; return { data: list, total, success: true };
}} }}
pagination={{ pageSize: 10 }} pagination={{ pageSize: 10 }}
// 让搜索表单默认展示“启用”
form={{ initialValues: { status: 1 } }}
search={{ labelWidth: 'auto' }} search={{ labelWidth: 'auto' }}
/> />
); );
@@ -1,6 +1,6 @@
import React, { useCallback, useEffect, useState } from "react"; import React, { useCallback, useEffect, useState } from "react";
import { PageContainer } from "@ant-design/pro-components"; import { PageContainer } from "@ant-design/pro-components";
import { Space, message, Button } from "antd"; import { Space, message, Button, Select } from "antd";
import { ActionBar, GradientButton, GlassCard } from "@/components/ui"; import { ActionBar, GradientButton, GlassCard } from "@/components/ui";
import { PlusOutlined } from "@ant-design/icons"; import { PlusOutlined } from "@ant-design/icons";
import TenantForm from "./components/TenantForm"; import TenantForm from "./components/TenantForm";
@@ -17,6 +17,23 @@ const TenantManage: React.FC = () => {
const [editing, setEditing] = useState(false); const [editing, setEditing] = useState(false);
const [initialValues, setInitialValues] = useState<UITenantFormValues | undefined>(undefined); const [initialValues, setInitialValues] = useState<UITenantFormValues | undefined>(undefined);
const [treeCache, setTreeCache] = useState<TenantTreeNode[]>([]); const [treeCache, setTreeCache] = useState<TenantTreeNode[]>([]);
// 状态筛选:1=启用, 0=停用, 'all'=全部;默认启用
const [statusFilter, setStatusFilter] = useState<1 | 0 | 'all'>(1);
// 路径拼接:去掉前缀 null/undefined、首尾斜杠,仅用单斜杠连接
const joinPath = (base?: string, id?: string) => {
const b = String(base || '')
.trim()
.replace(/^null/gi, '')
.replace(/^undefined/gi, '')
.replace(/\/+$/g, '')
.replace(/^\/+/, '');
const t = String(id || '')
.trim()
.replace(/^\/+/, '')
.replace(/\/+$/g, '');
return b ? `${b}/${t}` : t;
};
const fetchTree = useCallback(async () => { const fetchTree = useCallback(async () => {
setLoading(true); setLoading(true);
@@ -43,7 +60,7 @@ const TenantManage: React.FC = () => {
if (list && list.length === 1 && !Array.isArray((list[0] as any).children)) { if (list && list.length === 1 && !Array.isArray((list[0] as any).children)) {
try { try {
const parentId = (list[0] as any).tenantId; const parentId = (list[0] as any).tenantId;
const resPage: any = await tenantApi.getTenantList({ parentTenantId: parentId, current: 1, pageSize: 1000 } as any); const resPage: any = await tenantApi.getTenantList({ parentTenantId: parentId, status: (statusFilter === 'all' ? undefined : statusFilter) as any, current: 1, pageSize: 1000 } as any);
const children = resPage?.data?.data || []; const children = resPage?.data?.data || [];
if (children && children.length) { if (children && children.length) {
(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 })); (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 }));
@@ -68,7 +85,7 @@ const TenantManage: React.FC = () => {
} catch {} } catch {}
// 确保至少补一层孩子,方便默认展开后可见 // 确保至少补一层孩子,方便默认展开后可见
if (!Array.isArray(node.children) || node.children.length === 0) { if (!Array.isArray(node.children) || node.children.length === 0) {
const resp: any = await tenantApi.getTenantList({ parentTenantId: node.tenantId, current: 1, pageSize: 1000 } as any); const resp: any = await tenantApi.getTenantList({ parentTenantId: node.tenantId, status: (statusFilter === 'all' ? undefined : statusFilter) as any, current: 1, pageSize: 1000 } as any);
const children = resp?.data?.data || []; const children = resp?.data?.data || [];
if (children && children.length) { 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 })); node.children = children.map((c: any) => ({ tenantId: c.tenantId, tenantName: c.tenantName, tenantType: c.tenantType, status: c.status, contactPerson: c.contactPerson, contactPhone: c.contactPhone }));
@@ -77,12 +94,73 @@ const TenantManage: React.FC = () => {
}) })
); );
} catch {} } 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 {
if (node.tenantType == null || node.status == null || node.contactPerson == null || node.contactPhone == null) {
const detail: any = await tenantApi.getTenantDetail(node.tenantId);
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 {}
const needLoad = !Array.isArray(node.children) || node.children.length === 0;
if (needLoad) {
try {
const resp: any = await tenantApi.getTenantList({ parentTenantId: node.tenantId, status: (statusFilter === 'all' ? undefined : statusFilter) as any, current: 1, pageSize: 1000 } as any);
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 }));
}
} catch {}
}
if (Array.isArray(node.children)) resultChildren.push(...node.children);
}));
return resultChildren;
};
try {
const level2 = await loadChildrenFor(list);
await loadChildrenFor(level2);
} catch {}
// 按状态筛选(仅当选择启用或停用时)
const filterTreeByStatus = (nodes?: any[]): any[] => {
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); setTreeCache(list);
setData(list); setData(finalList);
} catch (e) { } catch (e) {
message.error("获取租户数据失败"); message.error("获取租户数据失败");
} finally { setLoading(false); } } finally { setLoading(false); }
}, []); }, [statusFilter]);
useEffect(() => { fetchTree(); }, [fetchTree]); useEffect(() => { fetchTree(); }, [fetchTree]);
@@ -136,6 +214,22 @@ const TenantManage: React.FC = () => {
<Button onClick={fetchTree}>刷新</Button> <Button onClick={fetchTree}>刷新</Button>
</Space> </Space>
)} )}
right={(
<Space>
<span>状态:</span>
<Select
size="middle"
style={{ width: 120 }}
value={statusFilter}
onChange={(v: any) => setStatusFilter(v)}
options={[
{ value: 1, label: '启用' },
{ value: 0, label: '停用' },
{ value: 'all', label: '全部' },
]}
/>
</Space>
)}
/> />
<GlassCard> <GlassCard>
@@ -163,15 +257,15 @@ const TenantManage: React.FC = () => {
try { try {
const parent: any = await tenantApi.getTenantDetail(payload.parentTenantId); const parent: any = await tenantApi.getTenantDetail(payload.parentTenantId);
const p = parent?.data || {}; const p = parent?.data || {};
const base = p.tenantPath || p.tenantId || ''; const base = p?.tenantPath || p?.tenantId || payload.parentTenantId;
payload.tenantPath = base ? `${base}/${payload.tenantId}` : payload.tenantId; payload.tenantPath = joinPath(base, payload.tenantId);
payload.tenantLevel = (p.tenantLevel || 0) + 1; payload.tenantLevel = (p.tenantLevel || 0) + 1;
} catch { } catch {
payload.tenantPath = payload.parentTenantId ? `${payload.parentTenantId}/${payload.tenantId}` : payload.tenantId; payload.tenantPath = joinPath(payload.parentTenantId, payload.tenantId);
payload.tenantLevel = 1; payload.tenantLevel = 1;
} }
} else { } else {
payload.tenantPath = payload.tenantId; payload.tenantPath = joinPath(undefined, payload.tenantId);
payload.tenantLevel = 1; payload.tenantLevel = 1;
} }
} }
@@ -181,11 +275,7 @@ const TenantManage: React.FC = () => {
const cur: any = await tenantApi.getTenantDetail(payload.tenantId); const cur: any = await tenantApi.getTenantDetail(payload.tenantId);
const cd = cur?.data || {}; const cd = cur?.data || {};
if (!payload.parentTenantId && cd.parentTenantId) payload.parentTenantId = cd.parentTenantId; if (!payload.parentTenantId && cd.parentTenantId) payload.parentTenantId = cd.parentTenantId;
const joinPath = (base?: string, id?: string) => { // 使用统一的 joinPath 规范化路径
const b = String(base || '').replace(/\/+$/g, '').replace(/^null/gi, '');
const t = String(id || '').replace(/^\/+/, '');
return b ? `${b}/${t}` : t;
};
const badPath = !payload.tenantPath || /^null/i.test(String(payload.tenantPath)) || /\/$/.test(String(payload.tenantPath)); const badPath = !payload.tenantPath || /^null/i.test(String(payload.tenantPath)) || /\/$/.test(String(payload.tenantPath));
if (badPath) { if (badPath) {
let base = ''; let base = '';
@@ -1,4 +1,5 @@
import logo from '@/assets/logo.png';
import logo from '@/assets/logo.png';
import React, { useEffect, useRef, useState } from 'react'; import React, { useEffect, useRef, useState } from 'react';
import { LoginForm, ProFormText, ProFormCaptcha, ProFormCheckbox } from '@ant-design/pro-components'; import { LoginForm, ProFormText, ProFormCaptcha, ProFormCheckbox } from '@ant-design/pro-components';
import { AppstoreOutlined, LockOutlined, UserOutlined } from '@ant-design/icons'; import { AppstoreOutlined, LockOutlined, UserOutlined } from '@ant-design/icons';
@@ -26,14 +27,25 @@ const LoginPage: React.FC = () => {
if (loading) return; if (loading) return;
setLoading(true); setLoading(true);
try { try {
const res = await login({ ...values, deviceId: uuid }); const res = await login({ ...values, clientId: 'webApp', deviceId: uuid });
// 检查多种可能的token字段位置 // 检查多种可能的token字段位置
const accessToken = res?.access_token || res?.data?.access_token || res?.accessToken; const accessToken = res?.access_token || res?.data?.access_token || res?.accessToken;
if (accessToken) { if (accessToken) {
sessionStorage.setItem('access_token', accessToken); sessionStorage.setItem('access_token', accessToken);
localStorage.setItem('tenant_client_id', String(values.clientId ?? '')); // 登录后预热可访问租户树缓存,便于各页快速使用
try {
const { ensureTenantCacheTokenGuard, setTenantTreeCache } = await import('@/utils/tenantCache');
const { tenantApi } = await import('@/services/tenant');
ensureTenantCacheTokenGuard();
const treeRes: any = await tenantApi.getAccessibleTenants();
let list: any[] = [];
if (typeof treeRes?.success !== 'undefined') list = treeRes.success ? (treeRes.data || []) : [];
else if (Array.isArray(treeRes)) list = treeRes as any[];
if (list && list.length) setTenantTreeCache(list);
} catch {}
localStorage.setItem('tenant_client_id', 'webApp');
message.success('登录成功,正在跳转...'); message.success('登录成功,正在跳转...');
// 使用umi的history进行路由跳转 // 使用umi的history进行路由跳转
@@ -84,6 +96,8 @@ const LoginPage: React.FC = () => {
> >
<ProFormText <ProFormText
name="clientId" name="clientId"
initialValue="webApp"
disabled
fieldProps={{ size: 'large', prefix: <AppstoreOutlined /> }} fieldProps={{ size: 'large', prefix: <AppstoreOutlined /> }}
placeholder="请输入租户标识" placeholder="请输入租户标识"
rules={[{ required: true, message: '请输入租户标识' }]} rules={[{ required: true, message: '请输入租户标识' }]}
@@ -0,0 +1,19 @@
import { request } from 'umi';
export type StatType = 'day' | 'month' | 'year';
export interface DashboardParams {
tenantId?: string;
includeChildren?: boolean;
statType?: StatType;
[k: string]: any;
}
export const dashboardApi = {
// 首页统计(根据租户 + 子孙 + 时间粒度)
statistics: async (params?: DashboardParams) => {
const res = await request('/api-order/dashboard/statistics', { method: 'GET', params });
return res as any;
},
};
+38 -25
View File
@@ -1,4 +1,4 @@
import { request } from 'umi'; import { request } from 'umi';
export interface OrderItem { export interface OrderItem {
id: number; id: number;
@@ -12,6 +12,7 @@ export interface OrderItem {
} }
export const ordersApi = { export const ordersApi = {
// 订单列表
order: async (params: { current?: number; pageSize?: number; orderNo?: string; orderStatus?: number; tourismId?: number; payType?: number }) => { order: async (params: { current?: number; pageSize?: number; orderNo?: string; orderStatus?: number; tourismId?: number; payType?: number }) => {
const { current, pageSize, ...rest } = params || {}; const { current, pageSize, ...rest } = params || {};
const res = await request('/api-order/list', { method: 'GET', params: { page: current, limit: pageSize, ...rest } }); const res = await request('/api-order/list', { method: 'GET', params: { page: current, limit: pageSize, ...rest } });
@@ -21,19 +22,19 @@ export const ordersApi = {
const res = await request('/api-order/update/order', { method: 'POST', data }); const res = await request('/api-order/update/order', { method: 'POST', data });
return (res as any).data || res; return (res as any).data || res;
}, },
// 订单文件相关接口
// 订单文件
orderFiles: async (params: { current?: number; pageSize?: number; [k: string]: any }) => { orderFiles: async (params: { current?: number; pageSize?: number; [k: string]: any }) => {
const { current, pageSize, ...rest } = params || {}; const { current, pageSize, ...rest } = params || {};
const res = await request('/api-order/files', { const res = await request('/api-order/files', { method: 'GET', params: { page: current, limit: pageSize, ...rest } });
method: 'GET',
params: { page: current, limit: pageSize, ...rest },
});
return { data: (res as any).data, total: (res as any).count } as { data: any[]; total: number }; return { data: (res as any).data, total: (res as any).count } as { data: any[]; total: number };
}, },
deleteOrderFile: async (id: number) => { deleteOrderFile: async (id: number) => {
const res = await request(`/api-order/files/${id}`, { method: 'DELETE' }); const res = await request(`/api-order/files/${id}`, { method: 'DELETE' });
return (res as any).data || res; return (res as any).data || res;
}, },
// 二维码
qrcodeList: async (params: { current?: number; pageSize?: number }) => { qrcodeList: async (params: { current?: number; pageSize?: number }) => {
const { current, pageSize } = params || {}; const { current, pageSize } = params || {};
const res = await request('/api-order/qrcode', { method: 'GET', params: { page: current, limit: pageSize } }); const res = await request('/api-order/qrcode', { method: 'GET', params: { page: current, limit: pageSize } });
@@ -47,8 +48,9 @@ export const ordersApi = {
const res = await request(`/api-order/qrcode/${id}`, { method: 'DELETE' }); const res = await request(`/api-order/qrcode/${id}`, { method: 'DELETE' });
return (res as any).data || res; return (res as any).data || res;
}, },
// 鏃呮父鏅尯
tourism: async (params: { current?: number; pageSize?: number; [k:string]: any }) => { // 旅游景区
tourism: async (params: { current?: number; pageSize?: number; [k: string]: any }) => {
const { current, pageSize, ...rest } = params || {}; const { current, pageSize, ...rest } = params || {};
const res = await request('/api-order/tourism', { method: 'GET', params: { page: current, limit: pageSize, ...rest } }); const res = await request('/api-order/tourism', { method: 'GET', params: { page: current, limit: pageSize, ...rest } });
return { data: (res as any).data, total: (res as any).count }; return { data: (res as any).data, total: (res as any).count };
@@ -61,8 +63,9 @@ export const ordersApi = {
const res = await request(`/api-order/tourism/${id}`, { method: 'DELETE' }); const res = await request(`/api-order/tourism/${id}`, { method: 'DELETE' });
return (res as any).data || res; return (res as any).data || res;
}, },
// 棣栭〉杞挱
homeCarousel: async (params: { current?: number; pageSize?: number; [k:string]: any }) => { // 首页轮播
homeCarousel: async (params: { current?: number; pageSize?: number; [k: string]: any }) => {
const { current, pageSize, ...rest } = params || {}; const { current, pageSize, ...rest } = params || {};
const res = await request('/api-order/home/carousel', { method: 'GET', params: { page: current, limit: pageSize, ...rest } }); const res = await request('/api-order/home/carousel', { method: 'GET', params: { page: current, limit: pageSize, ...rest } });
return { data: (res as any).data, total: (res as any).count }; return { data: (res as any).data, total: (res as any).count };
@@ -75,13 +78,11 @@ export const ordersApi = {
const res = await request(`/api-order/home/carousel/${id}`, { method: 'DELETE' }); const res = await request(`/api-order/home/carousel/${id}`, { method: 'DELETE' });
return (res as any).data || res; return (res as any).data || res;
}, },
// 景区素材(图片/视频等)
// 景区资源(图片/视频等)
tourismFile: async (params: { current?: number; pageSize?: number; [k: string]: any }) => { tourismFile: async (params: { current?: number; pageSize?: number; [k: string]: any }) => {
const { current, pageSize, ...rest } = params || {}; const { current, pageSize, ...rest } = params || {};
const res = await request('/api-order/tourism/files', { const res = await request('/api-order/tourism/files', { method: 'GET', params: { page: current, limit: pageSize, ...rest } });
method: 'GET',
params: { page: current, limit: pageSize, ...rest },
});
return { data: (res as any).data, total: (res as any).count } as { data: any[]; total: number }; return { data: (res as any).data, total: (res as any).count } as { data: any[]; total: number };
}, },
saveOrUpdateTourismFile: async (data: any) => { saveOrUpdateTourismFile: async (data: any) => {
@@ -92,8 +93,9 @@ export const ordersApi = {
const res = await request(`/api-order/tourism/files/${id}`, { method: 'DELETE' }); const res = await request(`/api-order/tourism/files/${id}`, { method: 'DELETE' });
return (res as any).data || res; return (res as any).data || res;
}, },
// 退款 // 退款
refund: async (params: { current?: number; pageSize?: number; [k:string]: any }) => { refund: async (params: { current?: number; pageSize?: number; [k: string]: any }) => {
const { current, pageSize, ...rest } = params || {}; const { current, pageSize, ...rest } = params || {};
const res = await request('/api-order/refund', { method: 'GET', params: { page: current, limit: pageSize, ...rest } }); const res = await request('/api-order/refund', { method: 'GET', params: { page: current, limit: pageSize, ...rest } });
return { data: (res as any).data, total: (res as any).count }; return { data: (res as any).data, total: (res as any).count };
@@ -106,11 +108,21 @@ export const ordersApi = {
const res = await request('/api-order/refund/auto', { method: 'PUT', data: payload }); const res = await request('/api-order/refund/auto', { method: 'PUT', data: payload });
return (res as any).data || res; return (res as any).data || res;
}, },
// 仪表盘统计
dashboard: async (params?: any) => { // 首页统计
dashboard: async (params?: { tenantId?: string; includeChildren?: boolean; statType?: 'day' | 'month' | 'year'; [k: string]: any }) => {
const res = await request('/api-order/dashboard/statistics', { method: 'GET', params }); const res = await request('/api-order/dashboard/statistics', { method: 'GET', params });
return res as any; return res as any;
}, },
getDashboardOrders: async (params?: { [k: string]: any }) => {
const res = await request('/api-order/dashboard/orders', { method: 'GET', params });
return res as any;
},
getQrcodeOptions: async (params?: { [k: string]: any }) => {
const res = await request('/api-order/dashboard/qrcode/options', { method: 'GET', params });
return res as any;
},
// 分账 // 分账
getProfitSharingDetail: async (orderNo: string) => { getProfitSharingDetail: async (orderNo: string) => {
const res = await request('/api-order/profitSharing/detail', { method: 'GET', params: { orderNo } }); const res = await request('/api-order/profitSharing/detail', { method: 'GET', params: { orderNo } });
@@ -124,8 +136,9 @@ export const ordersApi = {
const res = await request('/api-order/profitSharing/statistics', { method: 'GET', params }); const res = await request('/api-order/profitSharing/statistics', { method: 'GET', params });
return res as any; return res as any;
}, },
// 视频模板 // 视频模板
getVideoTemplateList: async (params: { current?: number; pageSize?: number; [k:string]: any }) => { getVideoTemplateList: async (params: { current?: number; pageSize?: number; [k: string]: any }) => {
const { current, pageSize, ...rest } = params || {}; const { current, pageSize, ...rest } = params || {};
const res = await request('/api-order/videoTemplate/list', { method: 'GET', params: { page: current, limit: pageSize, ...rest } }); const res = await request('/api-order/videoTemplate/list', { method: 'GET', params: { page: current, limit: pageSize, ...rest } });
return { data: (res as any).data, total: (res as any).count }; return { data: (res as any).data, total: (res as any).count };
@@ -146,8 +159,9 @@ export const ordersApi = {
const res = await request(`/api-order/videoTemplate/${id}/status`, { method: 'PUT', params: { status } }); const res = await request(`/api-order/videoTemplate/${id}/status`, { method: 'PUT', params: { status } });
return (res as any).data || res; return (res as any).data || res;
}, },
// 编辑任务 // 编辑任务
getEditTaskList: async (params: { current?: number; pageSize?: number; [k:string]: any }) => { getEditTaskList: async (params: { current?: number; pageSize?: number; [k: string]: any }) => {
const { current, pageSize, ...rest } = params || {}; const { current, pageSize, ...rest } = params || {};
const res = await request('/api-order/editTask/list', { method: 'GET', params: { page: current, limit: pageSize, ...rest } }); const res = await request('/api-order/editTask/list', { method: 'GET', params: { page: current, limit: pageSize, ...rest } });
return { data: (res as any).data, total: (res as any).count }; return { data: (res as any).data, total: (res as any).count };
@@ -164,8 +178,9 @@ export const ordersApi = {
const res = await request('/api-order/auto/cut/generate', { method: 'POST', params: { orderNo } }); const res = await request('/api-order/auto/cut/generate', { method: 'POST', params: { orderNo } });
return (res as any).data || res; return (res as any).data || res;
}, },
// 微信消息 // 微信消息
getWxMessageRecords: async (params: { current?: number; pageSize?: number; [k:string]: any }) => { getWxMessageRecords: async (params: { current?: number; pageSize?: number; [k: string]: any }) => {
const { current, pageSize, ...rest } = params || {}; const { current, pageSize, ...rest } = params || {};
const res = await request('/api-order/wx/message/records', { method: 'GET', params: { page: current, limit: pageSize, ...rest } }); const res = await request('/api-order/wx/message/records', { method: 'GET', params: { page: current, limit: pageSize, ...rest } });
return { data: (res as any).data, total: (res as any).count }; return { data: (res as any).data, total: (res as any).count };
@@ -174,13 +189,11 @@ export const ordersApi = {
const res = await request('/api-order/wx/message/statistics', { method: 'GET', params }); const res = await request('/api-order/wx/message/statistics', { method: 'GET', params });
return res as any; return res as any;
}, },
// 优惠券 // 优惠券
getCouponList: async (params?: { current?: number; pageSize?: number; [k: string]: any }) => { getCouponList: async (params?: { current?: number; pageSize?: number; [k: string]: any }) => {
const { current, pageSize, ...rest } = params || {}; const { current, pageSize, ...rest } = params || {};
const res = await request('/api-order/coupon', { const res = await request('/api-order/coupon', { method: 'GET', params: { page: current, limit: pageSize, ...rest } });
method: 'GET',
params: { page: current, limit: pageSize, ...rest },
});
return { data: (res as any).data, total: (res as any).count } as { data: any[]; total: number }; return { data: (res as any).data, total: (res as any).count } as { data: any[]; total: number };
}, },
getCouponById: async (id: number) => { getCouponById: async (id: number) => {
@@ -0,0 +1,88 @@
// 租户数据缓存工具:会话级缓存(sessionStorage),按 token 隔离
// - 缓存内容:可访问租户树、按父ID的子节点、详情状态
// - 生命周期:登录成功后预热;退出登录/Token失效时清理;检测到Token变更时自动清理
type AnyNode = { tenantId?: string; tenantName?: string; status?: number | boolean; children?: AnyNode[] };
const KEY_META = 'tenant_cache_meta';
const KEY_TREE = 'tenant_cache_tree';
const KEY_CHILDREN = 'tenant_cache_children';
const KEY_DETAIL = 'tenant_cache_detail';
const safeParse = <T = any>(s?: string | null): T | undefined => {
if (!s) return undefined as any;
try { return JSON.parse(s) as T; } catch { return undefined as any; }
};
const getToken = () => {
try { return sessionStorage.getItem('access_token') || undefined; } catch { return undefined; }
};
export const ensureTenantCacheTokenGuard = () => {
try {
const meta = safeParse<{ token?: string }>(sessionStorage.getItem(KEY_META));
const cur = getToken();
if (!meta?.token || !cur || meta.token !== cur) {
// Token 为空或已变化:清理缓存
clearTenantCache();
if (cur) sessionStorage.setItem(KEY_META, JSON.stringify({ token: cur }));
}
} catch {}
};
export const setTenantTreeCache = (tree: AnyNode[]) => {
try {
ensureTenantCacheTokenGuard();
sessionStorage.setItem(KEY_TREE, JSON.stringify(tree || []));
} catch {}
};
export const getTenantTreeCache = (): AnyNode[] | undefined => {
try {
ensureTenantCacheTokenGuard();
return safeParse<AnyNode[]>(sessionStorage.getItem(KEY_TREE));
} catch { return undefined; }
};
export const setTenantChildrenCache = (parentId: string, children: AnyNode[] | undefined) => {
try {
ensureTenantCacheTokenGuard();
const map = safeParse<Record<string, AnyNode[]>>(sessionStorage.getItem(KEY_CHILDREN)) || {};
if (parentId) map[parentId] = children || [];
sessionStorage.setItem(KEY_CHILDREN, JSON.stringify(map));
} catch {}
};
export const getTenantChildrenCache = (parentId: string): AnyNode[] | undefined => {
try {
ensureTenantCacheTokenGuard();
const map = safeParse<Record<string, AnyNode[]>>(sessionStorage.getItem(KEY_CHILDREN)) || {};
return parentId ? (map[parentId] || undefined) : undefined;
} catch { return undefined; }
};
export const setTenantDetailCache = (tenantId: string, detail: AnyNode | undefined) => {
try {
ensureTenantCacheTokenGuard();
const map = safeParse<Record<string, AnyNode>>(sessionStorage.getItem(KEY_DETAIL)) || {};
if (tenantId) map[tenantId] = detail || {};
sessionStorage.setItem(KEY_DETAIL, JSON.stringify(map));
} catch {}
};
export const getTenantDetailCache = (tenantId: string): AnyNode | undefined => {
try {
ensureTenantCacheTokenGuard();
const map = safeParse<Record<string, AnyNode>>(sessionStorage.getItem(KEY_DETAIL)) || {};
return tenantId ? (map[tenantId] || undefined) : undefined;
} catch { return undefined; }
};
export const clearTenantCache = () => {
try {
sessionStorage.removeItem(KEY_TREE);
sessionStorage.removeItem(KEY_CHILDREN);
sessionStorage.removeItem(KEY_DETAIL);
sessionStorage.removeItem(KEY_META);
} catch {}
};