多租户层级查询优化

This commit is contained in:
2025-10-09 14:33:15 +08:00
parent da9bf97667
commit 6bfc01d2fc
25 changed files with 581 additions and 309 deletions
@@ -1,11 +1,11 @@
package com.central.order.controller;
import com.central.common.feign.UserService;
import com.central.common.model.PageResult;
import com.central.common.model.Result;
import com.central.common.model.SysUser;
import com.central.order.constants.EditTaskStatus;
import com.central.order.enums.OrderStatus;
import com.central.order.feign.UserCenterService;
import com.central.order.model.*;
import com.central.order.model.dto.CallbackDTO;
import com.central.order.model.params.EditTaskQueryParams;
@@ -46,7 +46,7 @@ public class AutoCutVideoController {
private WxMiniSubscribeService wxMiniSubscribeService;
@Autowired
private UserCenterService userCenterService;
private UserService userCenterService;
@Autowired
private ITourismService tourismService;
@@ -190,6 +190,8 @@ public class DashboardController {
@Operation(summary = "获取首页订单列表")
@GetMapping("/orders")
public Result<PageResult<Order>> getDashboardOrders(
@Parameter(description = "租户ID") @RequestParam(required = false) String tenantId,
@Parameter(description = "是否包含子租户") @RequestParam(required = false) Boolean includeChildren,
@Parameter(description = "景区ID") @RequestParam(required = false) Long tourismId,
@Parameter(description = "二维码ID") @RequestParam(required = false) String qrcodeId,
@Parameter(description = "设备编号") @RequestParam(required = false) String deviceSn,
@@ -200,6 +202,19 @@ public class DashboardController {
@Parameter(description = "每页数量") @RequestParam(defaultValue = "10") Integer limit) {
try {
Map<String, Object> params = new HashMap<>();
// 规范化租户与子租户范围
String anchor = tenantId;
try {
if (anchor == null || anchor.isEmpty()) {
anchor = com.central.common.context.TenantQueryOverrideContext.getTenantId();
if (anchor == null || anchor.isEmpty()) {
anchor = com.central.common.context.LoginUserContextHolder.getCurrentTenantId();
}
}
} catch (Exception ignored) { }
boolean withChildren = (includeChildren == null) || Boolean.TRUE.equals(includeChildren);
params.put("tenantId", anchor);
params.put("includeChildren", withChildren);
params.put("tourismId", tourismId);
params.put("qrcodeId", qrcodeId);
params.put("deviceSn", deviceSn);
@@ -4,6 +4,7 @@ import com.alibaba.csp.sentinel.util.StringUtil;
import com.central.common.constant.CommonConstant;
import com.central.common.context.LoginUserContextHolder;
import com.central.common.context.TenantContextHolder;
import com.central.common.feign.UserService;
import com.central.common.model.LoginAppUser;
import com.central.common.model.PageResult;
import com.central.common.model.Result;
@@ -13,7 +14,6 @@ import com.central.order.enums.CommonStatus;
import com.central.order.enums.OrderStatus;
import com.central.order.feign.DeviceCenterService;
import com.central.order.feign.FileCenterService;
import com.central.order.feign.UserCenterService;
import com.central.order.model.*;
import com.central.order.service.*;
import com.central.wechat.config.WxPayConfigFactory;
@@ -75,7 +75,7 @@ public class OrderController {
private ITourismFileService tourismFileService;
@Autowired
private UserCenterService userCenterService;
private UserService userCenterService;
@Autowired
private FileCenterService fileCenterService;
@@ -2,11 +2,11 @@ package com.central.order.controller;
import com.central.common.context.LoginUserContextHolder;
import com.central.common.context.TenantContextHolder;
import com.central.common.feign.UserService;
import com.central.common.model.*;
import com.central.order.constants.EditTaskStatus;
import com.central.order.enums.OrderStatus;
import com.central.order.feign.FileCenterService;
import com.central.order.feign.UserCenterService;
import com.central.order.model.*;
import com.central.order.service.*;
import com.central.order.util.DateUtils;
@@ -71,7 +71,7 @@ public class OrderFileController {
private String cdnUrl;
@Autowired
private UserCenterService userCenterService;
private UserService userCenterService;
@Autowired
private WxMiniSubscribeService wxMiniSubscribeService;
@@ -1,12 +1,12 @@
package com.central.order.controller;
import com.central.common.context.TenantContextHolder;
import com.central.common.feign.UserService;
import com.central.common.model.PageResult;
import com.central.common.model.Result;
import com.central.common.model.SysUser;
import com.central.order.enums.OrderStatus;
import com.central.order.enums.RefundState;
import com.central.order.feign.UserCenterService;
import com.central.order.model.Order;
import com.central.order.model.QrCode;
import com.central.order.service.IOrderService;
@@ -53,7 +53,7 @@ public class RefundController {
private IWxTemplateMessageService templateMessageService;
@Autowired
private UserCenterService userCenterService;
private UserService userCenterService;
@Autowired
private WechatConfigService wechatConfigService;
@@ -1,42 +0,0 @@
package com.central.order.feign;
import com.central.common.constant.ServiceNameConstants;
import com.central.common.model.Result;
import com.central.common.model.SysUser;
import com.central.order.feign.fallback.UserCenterServiceFallbackFactory;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
import java.util.Map;
/**
* user-center模块远程调用
*
* @author lsl
* @version 1.0
* @description user-center模块远程调用
* @create 2025/1/13
**/
@FeignClient(name = ServiceNameConstants.USER_SERVICE, fallbackFactory = UserCenterServiceFallbackFactory.class, dismiss404 = true)
public interface UserCenterService {
/**
* 通过ID查询用户信息
*
* @param id 用户ID
* @return
*/
@GetMapping("/users/{id}")
SysUser findUserById(@PathVariable("id") Long id);
/**
* 获取指定租户(含自身)及其所有子孙租户ID
* @param tenantId 锚点租户ID
*/
@GetMapping("/tenant/hierarchy/{tenantId}")
Result<List<String>> getDescendantTenantIds(@PathVariable("tenantId") String tenantId) throws Exception;
}
@@ -1,41 +0,0 @@
package com.central.order.feign.fallback;
import com.central.common.model.Result;
import com.central.common.model.SysUser;
import com.central.order.feign.UserCenterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.openfeign.FallbackFactory;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* 用户中心调用失败回调
*
* @author caiji
* @version 1.0
* @description 用户中心调用失败回调
* @create 2024/8/6 11:33
**/
@Slf4j
@Component
public class UserCenterServiceFallbackFactory implements FallbackFactory<UserCenterService> {
@Override
public UserCenterService create(Throwable cause) {
return new UserCenterService() {
@Override
public SysUser findUserById(Long id) {
return null;
}
@Override
public Result<List<String>> getDescendantTenantIds(String tenantId) {
log.warn("获取子孙租户失败,降级返回仅当前租户: {}, error: {}", tenantId, cause.getMessage());
// 降级策略:返回仅包含当前租户的列表
return Result.succeed(java.util.Collections.singletonList(tenantId));
}
};
}
}
@@ -1,12 +1,12 @@
package com.central.order.listener;
import com.alibaba.fastjson.JSON;
import com.central.common.feign.UserService;
import com.central.common.model.SysUser;
import com.central.order.enums.MessageTemplateEnum;
import com.central.order.enums.OrderStatus;
import com.central.order.enums.OrderStatusChangeEnum;
import com.central.order.event.OrderStatusChangeEvent;
import com.central.order.feign.UserCenterService;
import com.central.order.model.Message;
import com.central.order.model.Order;
import com.central.order.model.QrCode;
@@ -37,7 +37,7 @@ public class OrderStatusChangeListener {
@Autowired
private IOrderService orderService;
@Autowired
private UserCenterService userCenterService;
private UserService userCenterService;
@Autowired
private WxMiniSubscribeService wxMiniSubscribeService;
@@ -471,6 +471,16 @@ public interface DashboardMapper {
"<if test='p.deviceSn != null and p.deviceSn != \"\"'>",
" AND o.device_sn = #{p.deviceSn}",
"</if>",
"<choose>",
" <when 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>",
" </when>",
" <when test='p.tenantIds != null and p.tenantIds.size > 0'>",
" AND q.tenant_id IN",
" <foreach collection='p.tenantIds' item='tid' open='(' separator=',' close=')'>#{tid}</foreach>",
" </when>",
"</choose>",
"</script>"
})
Long getYesterdayOrders(@Param("p") Map<String, Object> params);
@@ -495,16 +505,223 @@ public interface DashboardMapper {
"<if test='p.deviceSn != null and p.deviceSn != \"\"'>",
" AND o.device_sn = #{p.deviceSn}",
"</if>",
"<choose>",
" <when 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>",
" </when>",
" <when test='p.tenantIds != null and p.tenantIds.size > 0'>",
" AND q.tenant_id IN",
" <foreach collection='p.tenantIds' item='tid' open='(' separator=',' close=')'>#{tid}</foreach>",
" </when>",
"</choose>",
"<if test='p.startTime != null and p.startTime != \"\"'>",
" AND o.create_time >= #{p.startTime}",
"</if>",
"<if test='p.endTime != null and p.endTime != \"\"'>",
" AND o.create_time &lt;= #{p.endTime}",
"</if>",
"<if test='p.tourismIds != null and p.tourismIds.size > 0'>",
" AND o.tourism_id IN",
" <foreach collection='p.tourismIds' item='tid' open='(' separator=',' close=')'>#{tid}</foreach>",
"</if>",
"</script>"
})
Long getCompletedOrders(@Param("p") Map<String, Object> params);
// 每日订单总数、订单总金额(元)、退款订单数、退款金额(元)趋势
@Select({
"<script>",
"SELECT",
" <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>",
" '订单数' as type,",
" COUNT(*) as value",
"FROM orders o",
"JOIN qrcodes q ON o.code_id = q.code_id",
"WHERE 1=1",
"<if test='p.includeTestQrcodes == null or p.includeTestQrcodes == false'>",
" AND q.is_test = 0",
"</if>",
"AND o.order_status IN (1, 3, 4, 5, 7, 8, 9)",
"AND (o.pay_type = 1 OR o.pay_type IS NULL)",
"<if test='p.startTime != null and p.startTime != \"\"'>",
" AND o.create_time &gt;= #{p.startTime}",
"</if>",
"<if test='p.endTime != null and p.endTime != \"\"'>",
" AND o.create_time &lt;= #{p.endTime}",
"</if>",
"<if test='p.tourismId != null'>",
" AND o.tourism_id = #{p.tourismId}",
"</if>",
"<if test='p.qrcodeId != null and p.qrcodeId != \"\"'>",
" AND o.code_id = #{p.qrcodeId}",
"</if>",
"<if test='p.deviceSn != null and p.deviceSn != \"\"'>",
" AND o.device_sn = #{p.deviceSn}",
"</if>",
"<choose>",
" <when 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>",
" </when>",
" <when test='p.tenantIds != null and p.tenantIds.size > 0'>",
" AND q.tenant_id IN",
" <foreach collection='p.tenantIds' item='tid' open='(' separator=',' close=')'>#{tid}</foreach>",
" </when>",
"</choose>",
"GROUP BY ",
"<choose>",
" <when test=\"p.statType == 'year'\"> DATE_FORMAT(o.create_time, '%Y') </when>",
" <when test=\"p.statType == 'month'\"> DATE_FORMAT(o.create_time, '%Y-%m') </when>",
" <otherwise> DATE_FORMAT(o.create_time, '%Y-%m-%d') </otherwise>",
"</choose>",
"UNION ALL",
"SELECT",
" <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>",
" '订单金额(元)' as type,",
" COALESCE(SUM(o.order_amount)/100, 0) as value",
"FROM orders o",
"JOIN qrcodes q ON o.code_id = q.code_id",
"WHERE 1=1",
"<if test='p.includeTestQrcodes == null or p.includeTestQrcodes == false'>",
" AND q.is_test = 0",
"</if>",
"AND o.order_status IN (1, 3, 4, 5, 6, 7, 8, 9)",
"AND (o.pay_type = 1 OR o.pay_type IS NULL)",
"<if test='p.startTime != null and p.startTime != \"\"'>",
" AND o.create_time &gt;= #{p.startTime}",
"</if>",
"<if test='p.endTime != null and p.endTime != \"\"'>",
" AND o.create_time &lt;= #{p.endTime}",
"</if>",
"<if test='p.tourismId != null'>",
" AND o.tourism_id = #{p.tourismId}",
"</if>",
"<if test='p.qrcodeId != null and p.qrcodeId != \"\"'>",
" AND o.code_id = #{p.qrcodeId}",
"</if>",
"<if test='p.deviceSn != null and p.deviceSn != \"\"'>",
" AND o.device_sn = #{p.deviceSn}",
"</if>",
"<choose>",
" <when 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>",
" </when>",
" <when test='p.tenantIds != null and p.tenantIds.size > 0'>",
" AND q.tenant_id IN",
" <foreach collection='p.tenantIds' item='tid' open='(' separator=',' close=')'>#{tid}</foreach>",
" </when>",
"</choose>",
"GROUP BY ",
"<choose>",
" <when test=\"p.statType == 'year'\"> DATE_FORMAT(o.create_time, '%Y') </when>",
" <when test=\"p.statType == 'month'\"> DATE_FORMAT(o.create_time, '%Y-%m') </when>",
" <otherwise> DATE_FORMAT(o.create_time, '%Y-%m-%d') </otherwise>",
"</choose>",
"UNION ALL",
"SELECT",
" <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>",
" '退款订单数' as type,",
" SUM(CASE WHEN o.order_status = 8 THEN 1 ELSE 0 END) as value",
"FROM orders o",
"JOIN qrcodes q ON o.code_id = q.code_id",
"WHERE 1=1",
"<if test='p.includeTestQrcodes == null or p.includeTestQrcodes == false'>",
" AND q.is_test = 0",
"</if>",
"AND (o.pay_type = 1 OR o.pay_type IS NULL)",
"<if test='p.startTime != null and p.startTime != \"\"'>",
" AND o.create_time &gt;= #{p.startTime}",
"</if>",
"<if test='p.endTime != null and p.endTime != \"\"'>",
" AND o.create_time &lt;= #{p.endTime}",
"</if>",
"<if test='p.tourismId != null'>",
" AND o.tourism_id = #{p.tourismId}",
"</if>",
"<if test='p.qrcodeId != null and p.qrcodeId != \"\"'>",
" AND o.code_id = #{p.qrcodeId}",
"</if>",
"<if test='p.deviceSn != null and p.deviceSn != \"\"'>",
" AND o.device_sn = #{p.deviceSn}",
"</if>",
"<choose>",
" <when 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>",
" </when>",
" <when test='p.tenantIds != null and p.tenantIds.size > 0'>",
" AND q.tenant_id IN",
" <foreach collection='p.tenantIds' item='tid' open='(' separator=',' close=')'>#{tid}</foreach>",
" </when>",
"</choose>",
"GROUP BY ",
"<choose>",
" <when test=\"p.statType == 'year'\"> DATE_FORMAT(o.create_time, '%Y') </when>",
" <when test=\"p.statType == 'month'\"> DATE_FORMAT(o.create_time, '%Y-%m') </when>",
" <otherwise> DATE_FORMAT(o.create_time, '%Y-%m-%d') </otherwise>",
"</choose>",
"UNION ALL",
"SELECT",
" <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>",
" '退款金额(元)' as type,",
" COALESCE(SUM(CASE WHEN o.order_status = 8 THEN o.order_amount ELSE 0 END)/100, 0) as value",
"FROM orders o",
"JOIN qrcodes q ON o.code_id = q.code_id",
"WHERE 1=1",
"<if test='p.includeTestQrcodes == null or p.includeTestQrcodes == false'>",
" AND q.is_test = 0",
"</if>",
"AND (o.pay_type = 1 OR o.pay_type IS NULL)",
"<if test='p.startTime != null and p.startTime != \"\"'>",
" AND o.create_time &gt;= #{p.startTime}",
"</if>",
"<if test='p.endTime != null and p.endTime != \"\"'>",
" AND o.create_time &lt;= #{p.endTime}",
"</if>",
"<if test='p.tourismId != null'>",
" AND o.tourism_id = #{p.tourismId}",
"</if>",
"<if test='p.qrcodeId != null and p.qrcodeId != \"\"'>",
" AND o.code_id = #{p.qrcodeId}",
"</if>",
"<if test='p.deviceSn != null and p.deviceSn != \"\"'>",
" AND o.device_sn = #{p.deviceSn}",
"</if>",
"<if test='p.tenantIds != null and p.tenantIds.size > 0'>",
" AND q.tenant_id IN",
" <foreach collection='p.tenantIds' 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",
"</script>"
})
List<TrendDataVO> getDailyOrderSummary(@Param("p") Map<String, Object> params);
@Select({
"<script>",
"SELECT",
@@ -538,6 +755,10 @@ public interface DashboardMapper {
"<if test='p.deviceSn != null and p.deviceSn != \"\"'>",
" AND o.device_sn = #{p.deviceSn}",
"</if>",
"<if test='p.tenantIds != null and p.tenantIds.size > 0'>",
" AND q.tenant_id IN",
" <foreach collection='p.tenantIds' item='tid' open='(' separator=',' close=')'>#{tid}</foreach>",
"</if>",
"<if test='p.startTime != null and p.startTime != \"\"'>",
" AND o.create_time >= #{p.startTime}",
"</if>",
@@ -574,6 +795,10 @@ public interface DashboardMapper {
"<if test='p.deviceSn != null and p.deviceSn != \"\"'>",
" AND o.device_sn = #{p.deviceSn}",
"</if>",
"<if test='p.tenantIds != null and p.tenantIds.size > 0'>",
" AND q.tenant_id IN",
" <foreach collection='p.tenantIds' item='tid' open='(' separator=',' close=')'>#{tid}</foreach>",
"</if>",
"<if test='p.startTime != null and p.startTime != \"\"'>",
" AND o.create_time >= #{p.startTime}",
"</if>",
@@ -10,13 +10,17 @@ import java.util.List;
public class ChartStatistics {
@Schema(description = "订单趋势")
private List<TrendDataVO> orderTrend;
@Schema(description = "订单状态分布")
private List<DistributionDataVO> orderDistribution;
@Schema(description = "收入构成")
private List<IncomeDataVO> incomeBreakdown;
@Schema(description = "二维码订单数量")
private List<QrcodeOrderDataVO> qrcodeOrderCount;
}
@Schema(description = "每日订单总数与订单总金额(元)")
private List<TrendDataVO> dailySummary;
}
@@ -3,6 +3,7 @@ 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.feign.UserService;
import com.central.common.model.PageResult;
import com.central.common.service.ITenantHierarchyService;
import com.central.common.utils.SpringContextHolder;
@@ -65,12 +66,12 @@ public class DashboardServiceImpl implements IDashboardService {
switch (statType) {
case "year":
// 最近5年
params.put("startTime", now.minusYears(1).withDayOfYear(1).format(formatter));
params.put("startTime", now.withDayOfYear(1).format(formatter));
params.put("endTime", now.format(formatter) + " 23:59:59");
break;
case "month":
// 最近12个月
params.put("startTime", now.minusMonths(1).withDayOfMonth(1).format(formatter));
params.put("startTime", now.withDayOfMonth(1).format(formatter));
params.put("endTime", now.format(formatter) + " 23:59:59");
break;
case "day":
@@ -83,6 +84,7 @@ public class DashboardServiceImpl implements IDashboardService {
}
List<String> tenantIds = tenantResolverService.resolveTenantIds(tenantId, includeChildren);
params.put("tenantIds", tenantIds);
// 特殊处理:如果是webApp且没有获取到租户列表,则查询所有景区
if ("webApp".equals(tenantId) && (tenantIds == null || tenantIds.isEmpty())) {
@@ -97,7 +99,6 @@ public class DashboardServiceImpl implements IDashboardService {
tenantIds.size(), tourismIds.size(), params.get("startTime"), params.get("endTime"));
} else {
// 没有找到景区,设置一个不存在的ID,避免查询到所有数据
params.put("tourismIds", java.util.Collections.singletonList(-1L));
log.warn("租户 {} 没有关联的景区", tenantIds);
}
}
@@ -126,6 +127,35 @@ public class DashboardServiceImpl implements IDashboardService {
@Override
public PageResult<Order> getDashboardOrders(Map<String, Object> params) {
try {
// 与统计接口一致:解析租户与景区范围(含子孙租户)
try {
String tenantId = params != null && params.get("tenantId") != null ? String.valueOf(params.get("tenantId")) : null;
boolean includeChildren = true;
try {
Object inc = params != null ? params.get("includeChildren") : null;
if (inc != null) {
if (inc instanceof Boolean) {
includeChildren = (Boolean) inc;
} else {
String s = String.valueOf(inc);
includeChildren = !("false".equalsIgnoreCase(s) || "0".equals(s));
}
}
} catch (Exception ignored) {}
List<String> tenantIds = tenantResolverService.resolveTenantIds(tenantId, includeChildren);
params.put("tenantIds", tenantIds);
if (!"webApp".equals(tenantId) && 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());
}
// 获取订单列表
PageResult<Order> result = orderService.findList(params);
@@ -224,15 +254,19 @@ public class DashboardServiceImpl implements IDashboardService {
List<DistributionDataVO> orderDistribution = dashboardMapper.getOrderDistribution(params);
chartStats.setOrderDistribution(orderDistribution);
// 获取收入构成数据
List<IncomeDataVO> incomeBreakdown = dashboardMapper.getIncomeBreakdown(params);
chartStats.setIncomeBreakdown(incomeBreakdown);
// 添加收入统计调试日志
log.info("收入构成统计 - 参数: {}, 结果数量: {}", params, incomeBreakdown.size());
for (IncomeDataVO item : incomeBreakdown) {
log.info("收入构成 - 类型: {}, 金额: {}", item.getType(), item.getValue());
}
// 获取收入构成数据
List<IncomeDataVO> incomeBreakdown = dashboardMapper.getIncomeBreakdown(params);
chartStats.setIncomeBreakdown(incomeBreakdown);
// 添加收入统计调试日志
log.info("收入构成统计 - 参数: {}, 结果数量: {}", params, incomeBreakdown.size());
for (IncomeDataVO item : incomeBreakdown) {
log.info("收入构成 - 类型: {}, 金额: {}", item.getType(), item.getValue());
}
// 每日订单总数与总金额(元)
List<TrendDataVO> dailySummary = dashboardMapper.getDailyOrderSummary(params);
chartStats.setDailySummary(dailySummary);
// 获取二维码订单数量数据
List<QrcodeOrderDataVO> qrcodeOrderCount = dashboardMapper.getQrcodeOrderCount(params);
@@ -244,6 +278,7 @@ public class DashboardServiceImpl implements IDashboardService {
chartStats.setOrderTrend(new ArrayList<>());
chartStats.setOrderDistribution(new ArrayList<>());
chartStats.setIncomeBreakdown(new ArrayList<>());
chartStats.setDailySummary(new ArrayList<>());
chartStats.setQrcodeOrderCount(new ArrayList<>());
}
@@ -266,93 +301,6 @@ public class DashboardServiceImpl implements IDashboardService {
return options;
}
/**
* 解析租户ID集合(包含子租户)
* @deprecated 已迁移到TenantResolverService
*/
@Deprecated
private List<String> resolveTenantIds_old(String tenantId, boolean includeChildren) {
// 优先使用前端传来的tenantId,否则从上下文获取
String anchor = tenantId;
if (anchor == null || anchor.isEmpty()) {
anchor = TenantQueryOverrideContext.getTenantId();
}
if (anchor == null || anchor.isEmpty()) {
anchor = LoginUserContextHolder.getCurrentTenantId();
}
if (anchor == null || anchor.isEmpty()) {
return java.util.Collections.emptyList();
}
// webApp是特殊的超级租户,应该返回所有租户数据
if ("webApp".equals(anchor)) {
// 查询所有租户ID
try {
ITenantHierarchyService tenantService = SpringContextHolder.getBean(ITenantHierarchyService.class);
if (tenantService != null) {
// 获取所有顶级租户及其子孙
List<String> allTenants = new ArrayList<>();
List<com.central.common.model.TenantInfo> topTenants = tenantService.getTenantList(null, null, null, null, null).getData();
if (topTenants != null) {
for (com.central.common.model.TenantInfo tenant : topTenants) {
if (tenant.getTenantId() != null && !"webApp".equals(tenant.getTenantId())) {
List<String> subTenants = tenantService.getAllSubTenantIds(tenant.getTenantId());
if (subTenants != null && !subTenants.isEmpty()) {
allTenants.addAll(subTenants);
}
}
}
}
if (!allTenants.isEmpty()) {
log.info("webApp租户统计所有租户: {}", allTenants);
return allTenants;
}
}
} catch (Exception e) {
log.warn("webApp获取所有租户失败: {}", e.getMessage());
}
// 如果失败了,返回空列表(将查询所有数据)
return new ArrayList<>();
}
// 如果不包含子租户,只返回当前租户
if (!includeChildren) {
return java.util.Collections.singletonList(anchor);
}
// 获取当前租户及其所有子孙租户
try {
// 优先尝试使用本地的ITenantHierarchyService
ITenantHierarchyService tenantService = SpringContextHolder.getBean(ITenantHierarchyService.class);
if (tenantService != null) {
List<String> all = tenantService.getAllSubTenantIds(anchor);
if (all != null && !all.isEmpty()) {
log.info("本地获取租户层级成功: {} -> {}", anchor, all);
return all;
}
}
} catch (Exception e) {
log.debug("本地获取租户层级失败,尝试远程调用: {}", e.getMessage());
}
// 如果本地服务不可用,尝试远程调用
try {
com.central.order.feign.UserCenterService userCenterService = SpringContextHolder.getBean(com.central.order.feign.UserCenterService.class);
if (userCenterService != null) {
com.central.common.model.Result<List<String>> result = userCenterService.getDescendantTenantIds(anchor);
if (result != null && result.getResp_code() == 0 && result.getData() != null) {
log.info("远程获取租户层级成功: {} -> {}", anchor, result.getData());
return result.getData();
}
}
} catch (Exception e) {
log.warn("远程获取租户层级失败: {}", e.getMessage());
}
// 如果都失败了,只返回当前租户
log.warn("获取租户层级失败,降级为仅当前租户: {}", anchor);
return java.util.Collections.singletonList(anchor);
}
/**
* 解析当前请求上下文的租户集合(包含子租户)
@@ -369,7 +317,7 @@ public class DashboardServiceImpl implements IDashboardService {
private List<Long> resolveTourismIdsByTenants(List<String> tenantIds) {
try {
if (tenantIds == null || tenantIds.isEmpty()) return java.util.Collections.emptyList();
// 先按景区表直接匹配租户ID
// 先按景区表直接匹配租户ID】
List<Long> byTourism = tourismMapper.findTourismIdsByTenantIds(tenantIds);
java.util.Set<Long> union = new java.util.LinkedHashSet<>();
if (byTourism != null) union.addAll(byTourism);
@@ -4,6 +4,7 @@ import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.central.common.context.TenantContextHolder;
import com.central.common.feign.UserService;
import com.central.common.lock.DistributedLock;
import com.central.common.model.PageResult;
import com.central.common.model.SysUser;
@@ -11,7 +12,6 @@ import com.central.common.service.impl.SuperServiceImpl;
import com.central.order.enums.OrderStatus;
import com.central.order.event.OrderStatusChangeEvent;
import com.central.order.feign.FileCenterService;
import com.central.order.feign.UserCenterService;
import com.central.order.mapper.OrderFileMapper;
import com.central.order.mapper.OrderMapper;
import com.central.order.mapper.TourismFileMapper;
@@ -74,7 +74,7 @@ public class OrderServiceImpl extends SuperServiceImpl<OrderMapper, Order> imple
private ApplicationEventPublisher eventPublisher;
@Autowired
private UserCenterService userCenterService;
private UserService userCenterService;
@Autowired
private FileCenterService fileCenterService;
@@ -2,8 +2,8 @@ package com.central.order.service.impl;
import com.central.common.context.LoginUserContextHolder;
import com.central.common.context.TenantQueryOverrideContext;
import com.central.common.feign.UserService;
import com.central.common.model.Result;
import com.central.order.feign.UserCenterService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
@@ -21,7 +21,7 @@ import java.util.List;
@RequiredArgsConstructor
public class TenantResolverService {
private final UserCenterService userCenterService;
private final UserService userCenterService;
/**
* 解析租户ID集合(包含子租户)
@@ -58,23 +58,11 @@ public class TenantResolverService {
// 通过Feign调用user-center获取子孙租户
try {
log.info("开始获取租户 {} 的所有子孙租户", anchor);
Result<List<String>> result = userCenterService.getDescendantTenantIds(anchor);
if (result != null) {
if (result.getResp_code() == 0 && result.getData() != null && !result.getData().isEmpty()) {
List<String> tenantIds = result.getData();
log.info("成功获取租户层级: {} -> {} 个租户: {}", anchor, tenantIds.size(), tenantIds);
return tenantIds;
} else {
log.warn("获取租户层级返回异常: code={}, msg={}", result.getResp_code(), result.getResp_msg());
}
} else {
log.warn("获取租户层级返回null");
}
List<String> tenantIds = userCenterService.getSonTenantIds(anchor);
return tenantIds;
} catch (Exception e) {
log.error("获取租户层级失败: {}", e.getMessage(), e);
}
// 降级:只返回当前租户
log.warn("获取子孙租户失败,降级为仅当前租户: {}", anchor);
return Collections.singletonList(anchor);
@@ -1,11 +1,11 @@
package com.central.order.service.impl;
import com.central.common.exception.BusinessException;
import com.central.common.feign.UserService;
import com.central.common.model.FileInfo;
import com.central.common.model.SysUser;
import com.central.order.constants.EditTaskStatus;
import com.central.order.feign.FileCenterService;
import com.central.order.feign.UserCenterService;
import com.central.order.model.EditTask;
import com.central.order.model.Order;
import com.central.order.model.OrderFile;
@@ -40,7 +40,7 @@ public class VideoEditServiceImpl implements IVideoEditService {
@Autowired
private IOrderService orderService;
@Autowired
private UserCenterService userCenterService;
private UserService userCenterService;
@Autowired
private ITourismService tourismService;
@Autowired
@@ -8,6 +8,7 @@
FROM orders o
LEFT JOIN tourisms t ON o.tourism_id = t.id
<where>
<!-- 业务筛选条件 -->
<if test="p.orderNo != null and p.orderNo != ''">
AND o.order_no LIKE CONCAT('%', #{p.orderNo}, '%')
</if>
@@ -20,15 +21,33 @@
<if test="p.deviceSn != null and p.deviceSn != ''">
AND o.device_sn LIKE CONCAT('%', #{p.deviceSn}, '%')
</if>
<!-- 兼容 dashboard 透传的 qrcodeId 与现有 codeId 参数名 -->
<if test="p.codeId != null and p.codeId != ''">
AND o.code_id LIKE CONCAT('%', #{p.codeId}, '%')
</if>
<if test="p.qrcodeId != null and p.qrcodeId != ''">
AND o.code_id LIKE CONCAT('%', #{p.qrcodeId}, '%')
</if>
<if test="p.userId != null and p.userId != ''">
AND o.user_id LIKE CONCAT('%', #{p.userId}, '%')
</if>
<if test="p.mobile != null and p.mobile != ''">
AND o.mobile LIKE CONCAT('%', #{p.mobile}, '%')
</if>
<!-- 时间范围(与仪表盘统计口径一致) -->
<if test="p.startTime != null and p.startTime != ''">
AND o.create_time &gt;= #{p.startTime}
</if>
<if test="p.endTime != null and p.endTime != ''">
AND o.create_time &lt;= #{p.endTime}
</if>
<!-- 景区集合过滤(由租户+子孙→景区ID集合的去重结果提供) -->
<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>
</where>
ORDER BY o.create_time DESC
</select>
@@ -1,9 +1,6 @@
package com.central.user.controller;
import com.central.common.model.CodeEnum;
import com.central.common.model.Result;
import com.central.common.model.Tenant;
import com.central.common.model.TenantInfo;
import com.central.common.model.*;
import com.central.common.service.ITenantHierarchyService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
@@ -171,6 +168,18 @@ public class TenantHierarchyController {
}
}
/**
* 获取自己以及子孙租户
*
* @param tenantId 租户id
*/
@GetMapping(value = "/son/tenantId", params = "tenantId")
@Operation(summary = "获取自己以及子孙租户")
public List<String> getSonTenantIds(String tenantId) {
return tenantHierarchyService.getAllSubTenantIds(tenantId);
}
private String normalizePathForSave(String rawPath, String parentId, String tenantId) {
try {
String path = stripPathSafe(rawPath);
@@ -97,6 +97,11 @@ public class LoginUserContextHolder {
return Arrays.asList(currentTenantId);
}
// 优先使用登录时已初始化的可访问租户列表(包含自身与子孙)
if (user != null && user.getAccessibleTenantIds() != null && !user.getAccessibleTenantIds().isEmpty()) {
return user.getAccessibleTenantIds();
}
// 管理员用户可以查询当前租户及其所有子租户
try {
ITenantHierarchyService tenantService = getBean(ITenantHierarchyService.class);
@@ -233,4 +238,4 @@ public class LoginUserContextHolder {
return null;
}
}
}
}
@@ -27,6 +27,10 @@ public interface UserService {
@GetMapping(value = "/users/name/{username}")
SysUser selectByUsername(@PathVariable("username") String username);
@GetMapping("/users/{id}")
SysUser findUserById(@PathVariable("id") Long id);
/**
* feign rpc访问远程/users-anon/login接口
*
@@ -81,4 +85,10 @@ public interface UserService {
@GetMapping("/users-anon/miniApp")
MiniAppConfig getByAppid(@RequestParam("appCode") String appCode);
/**
* 获取自己以及子孙租户
*/
@GetMapping(value = "/tenant/hierarchy/son/tenantId", params = "tenantId")
List<String> getSonTenantIds(@RequestParam("tenantId") String tenantId);
}
@@ -27,6 +27,11 @@ public class UserServiceFallbackFactory implements FallbackFactory<UserService>
return new SysUser();
}
@Override
public SysUser findUserById(Long id) {
return null;
}
@Override
public SysUser findByUsername(String username) {
log.error("通过用户名查询用户异常:{}", username, throwable);
@@ -78,6 +83,12 @@ public class UserServiceFallbackFactory implements FallbackFactory<UserService>
public MiniAppConfig getByAppid(String appid) {
return null;
}
@Override
public List<String> getSonTenantIds(String tenantId) {
log.error("获取自己以及子孙租户列表异常:{}", tenantId, throwable);
return Collections.emptyList();
}
};
}
}
@@ -1,7 +1,6 @@
package com.central.common.service;
import com.central.common.model.LoginAppUser;
import com.central.common.service.ITenantHierarchyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@@ -13,9 +12,6 @@ import java.util.List;
/**
* 用户租户信息初始化器
* 在用户登录时初始化租户相关信息
*
* @author zlt
* @date 2024-12-19
*/
@Component
@Slf4j
@@ -25,10 +21,7 @@ public class UserTenantInitializer {
private ITenantHierarchyService tenantHierarchyService;
/**
* 初始化用户租户信息
* 在用户登录成功后调用此方法
*
* @param user 登录用户
* 初始化用户租户信息(登录成功后调用)
*/
public void initializeUserTenantInfo(LoginAppUser user) {
if (user == null) {
@@ -38,7 +31,7 @@ public class UserTenantInitializer {
String userTenantId = getUserTenantId(user);
if (!StringUtils.hasText(userTenantId)) {
log.warn("用户 {} 未分配租户", user.getUsername());
log.warn("用户 {} 未分配租户ID,将使用默认租户配置", user.getUsername());
setDefaultTenantInfo(user);
return;
}
@@ -71,45 +64,32 @@ public class UserTenantInitializer {
}
/**
* 获取用户租户ID
* 优先从用户属性中获取,如果没有则从公司字段获取
* 获取用户租户ID:优先 attributes.company,其次 user.company
*/
private String getUserTenantId(LoginAppUser user) {
// 优先从属性中获取
Object companyFromAttributes = user.getAttributes().get("company");
if (companyFromAttributes != null && StringUtils.hasText(companyFromAttributes.toString())) {
return companyFromAttributes.toString();
}
// 从company字段获取
if (StringUtils.hasText(user.getCompany())) {
return user.getCompany();
}
return null;
}
/**
* 判断是否为管理用户
* 管理用户可以切换租户,普通用户只能访问自己的租户
* 管理用户可切换租户,普通用户仅访问自身租户
*/
private boolean isManagementUser(LoginAppUser user) {
// 根据用户类型判断:BACKEND用户为管理员,APP用户为C端用户
String userType = getUserType(user);
return "BACKEND".equals(userType);
}
/**
* 获取用户类型
*/
private String getUserType(LoginAppUser user) {
// 优先从属性中获取
Object typeFromAttributes = user.getAttributes().get("type");
if (typeFromAttributes != null) {
return typeFromAttributes.toString();
}
// 默认返回BACKEND(兼容处理)
return "BACKEND";
}
@@ -123,6 +103,7 @@ public class UserTenantInitializer {
}
// 管理员用户可以访问当前租户及其所有子租户
// 优先通过本地服务查询(若存在)
if (tenantHierarchyService != null) {
try {
List<String> subTenants = tenantHierarchyService.getAllSubTenantIds(userTenantId);
@@ -130,11 +111,9 @@ public class UserTenantInitializer {
return subTenants;
}
} catch (Exception e) {
log.warn("获取子租户列表失败: tenantId={}, error={}", userTenantId, e.getMessage());
log.warn("获取子租户列表失败(本地): tenantId={}, error={}", userTenantId, e.getMessage());
}
}
// 降级处理:返回用户自己的租户
return Arrays.asList(userTenantId);
}
@@ -168,32 +147,25 @@ public class UserTenantInitializer {
if (user == null) {
return false;
}
// 检查基本字段
if (!StringUtils.hasText(user.getCurrentTenantId())) {
return false;
}
// 检查可访问租户列表
List<String> accessibleTenants = user.getAccessibleTenantIds();
if (accessibleTenants == null || accessibleTenants.isEmpty()) {
return false;
}
// 检查当前租户是否在可访问列表中
return accessibleTenants.contains(user.getCurrentTenantId());
}
/**
* 刷新用户租户信息
* 可在租户信息变更后调用
* 刷新用户租户信息(在租户变更后调用)
*/
public void refreshUserTenantInfo(LoginAppUser user) {
if (user == null) {
return;
}
log.info("刷新用户 {} 的租户信息", user.getUsername());
initializeUserTenantInfo(user);
}
}
}
@@ -204,14 +204,23 @@ public class LoginUserUtils {
*/
private static void initializeUserTenantInfo(LoginAppUser user) {
try {
UserTenantInitializer tenantInitializer = SpringUtil.getBean(UserTenantInitializer.class);
org.springframework.context.ApplicationContext ctx = SpringUtil.getApplicationContext();
UserTenantInitializer tenantInitializer = null;
if (ctx != null) {
try {
tenantInitializer = ctx.getBeanProvider(UserTenantInitializer.class).getIfAvailable();
} catch (Exception ignore) {
// 忽略:容器中不存在该 Bean
}
}
if (tenantInitializer != null) {
tenantInitializer.initializeUserTenantInfo(user);
} else {
log.debug("未发现 UserTenantInitializer Bean,跳过租户初始化");
}
} catch (Exception e) {
// 如果租户初始化器不存在或初始化失败,记录日志但不影响登录
// 这样可以保证在租户功能未完全部署时,系统仍能正常运行
System.err.println("租户信息初始化失败,但不影响登录: " + e.getMessage());
// 记录为 warn,且不影响登录流程
log.warn("租户信息初始化失败(忽略,不影响登录): {}", e.getMessage());
}
}
}
@@ -19,10 +19,10 @@ import java.io.IOException;
import java.util.List;
/**
* 读取可选的 tenantId 查询参数,作为本次请求的租户范围覆盖锚点�?
* 规则�?
* - APP 用户忽略该参数(记录warn)�?
* - BACKEND 用户仅在参数属于“可访问租户集”时生效;否则忽略并warn�?
* 读取可选的 tenantId 查询参数,作为本次请求的租户范围覆盖锚点。
* 规则:
* - APP 用户忽略该参数(记录 warn)
* - BACKEND 用户仅在参数属于“可访问租户集”时生效;否则忽略并 warn
*/
@Slf4j
@ConditionalOnClass(Filter.class)
@@ -39,18 +39,29 @@ public class TenantQueryOverrideFilter extends OncePerRequestFilter {
LoginAppUser user = LoginUserContextHolder.getUser();
if (user == null) {
// 未登录,忽略参数
log.debug("忽略tenantId参数(未登录?: {}", overrideTenant);
log.debug("忽略 tenantId 参数(未登录): {}", overrideTenant);
} else {
String userType = (String) user.getAttributes().getOrDefault("type", "BACKEND");
if ("APP".equals(userType)) {
log.warn("APP用户不支持覆盖tenantId, user={}, tenantId={}", user.getUsername(), overrideTenant);
log.warn("APP 用户不支持覆盖 tenantId,user={}, tenantId={}", user.getUsername(), overrideTenant);
} else {
List<String> accessible = user.getAccessibleTenantIds();
if (accessible != null && accessible.contains(overrideTenant)) {
TenantQueryOverrideContext.setTenantId(overrideTenant);
log.debug("本次请求使用覆盖租户ID: {}", overrideTenant);
// 特例:webApp 超级租户(仅允许具备切换权限的后端用户)
if ("webApp".equals(overrideTenant)) {
boolean canSwitch = user.isCanSwitchTenant();
if (canSwitch) {
TenantQueryOverrideContext.setTenantId(overrideTenant);
log.debug("本次请求使用覆盖租户ID(webApp): {}", overrideTenant);
} else {
log.warn("当前用户无权切换至 webApp,user={}", user.getUsername());
}
} else {
log.warn("覆盖tenantId不在可访问范围? user={}, tenantId={}", user.getUsername(), overrideTenant);
List<String> accessible = user.getAccessibleTenantIds();
if (accessible != null && accessible.contains(overrideTenant)) {
TenantQueryOverrideContext.setTenantId(overrideTenant);
log.debug("本次请求使用覆盖租户ID: {}", overrideTenant);
} else {
log.warn("覆盖的 tenantId 不在可访问范围,user={}, tenantId={}", user.getUsername(), overrideTenant);
}
}
}
}
@@ -62,4 +73,3 @@ public class TenantQueryOverrideFilter extends OncePerRequestFilter {
}
}
@@ -3,3 +3,4 @@ com.central.common.filter.LoginUserFilter
com.central.common.filter.TenantParamOverrideFilter
com.central.common.filter.TenantQueryOverrideFilter
com.central.common.filter.IncludeChildrenParamFilter
com.central.common.autoconfigure.TenantInitializerAutoConfiguration
+64 -1
View File
@@ -352,4 +352,67 @@ zlt:
- 兼容性与行为
- 继续优先 IN (...) 过滤,因此不会触发 XML 中的 CTE 查询,也就不会访问不存在的 sys_tenant 表。
- 远程调用失败时自动降级为“仅自身”,与现有退化语义一致。
- 所有修改与文档均采用 UTF-8 无 BOM 编码。
- 所有修改与文档均采用 UTF-8 无 BOM 编码。
## 13. 首页统计(含子孙租户)实现步骤(去重保障)
目标:当用户在 react-web-next 后台选择任意层级的租户时,首页统计需覆盖“所选租户自身 + 所有子孙租户”范围内的所有景区及订单,且统计数据不重复。
实现要点:先基于租户层级解析出租户ID集合,再反查景区ID集合(去重),最后所有统计 SQL 统一按“景区ID集合”过滤。
步骤一:参数规范化(Controller)
- 接口:`zlt-business/order-center/src/main/java/com/central/order/controller/DashboardController.java: /dashboard/statistics`、`/dashboard/orders`
- 处理:
- 支持 `tenantId`(选中锚点租户)与 `includeChildren`(是否包含子孙租户,默认 true)。
- 若未传 `tenantId`,从 `TenantQueryOverrideContext` → `LoginUserContextHolder.getCurrentTenantId()` 解析。
步骤二:解析“租户含子孙”集合(Service)
- 服务:`TenantResolverService.resolveTenantIds(String tenantId, boolean includeChildren)`(order-center)
- 策略:
- includeChildren=false → 仅返回当前租户;
- includeChildren=true → 首选本地 `ITenantHierarchyService#getAllSubTenantIds`;失败则调用 user-center Feign:`GET /tenant/hierarchy/{tenantId}`;两者都失败降级为仅自身。
- 特殊租户 `webApp`:返回空集合表示“不过滤租户”(全量)。
步骤三:由租户集合反查景区ID集合(去重)
- Mapper:`zlt-business/order-center/src/main/resources/mapper/TourismMapper.xml`
- 方法:
- `findTourismIdsByTenantIds(tenantIds)`:按景区表的 `tenant_id` 直接反查;
- 容错 `findTourismIdsByTenantIdsFromQrcodes(tenantIds)`:若景区未直连租户,则基于二维码表 `qrcodes(tenant_id)` 反查 `tourism_id`;
- Service 侧:使用 `LinkedHashSet` 合并两种来源的景区ID,确保唯一性(避免重复统计)。
步骤四:统计/图表 SQL 统一按景区范围过滤
- Mapper:`zlt-business/order-center/src/main/java/com/central/order/mapper/DashboardMapper.java`
- 规则:
- 首选 `o.tourism_id IN (#{p.tourismIds...})`;
- 个别场景缺少景区ID集合时,回退按 `q.tenant_id IN (#{p.tenantIds...})`(`JOIN qrcodes q`);
- 首页统计仅统计微信支付(`o.pay_type = 1 OR o.pay_type IS NULL`),保持与既有规则一致;
- 通过 `COUNT(*)`/`SUM(...)` + 去重后的景区集合,保证无重复统计。
步骤五:首页订单列表与统计口径一致
- 服务:`DashboardServiceImpl.getDashboardOrders(Map<String,Object> params)`
- 动作:与 `getDashboardStatistics` 相同的“租户 → 子孙 → 景区ID集合(去重)”预处理,随后调用订单列表查询。
- 订单列表 Mapper 补充按 `tourismIds` 与 `startTime/endTime` 的过滤,保证与统计口径一致。
步骤六:前端透传与默认值
- 前端(react-web-next)透传 `tenantId` 与 `includeChildren`;
- 若用户未显式设置,后端默认 `includeChildren=true`;
- 未传 `tenantId` 时后端自动从上下文解析。
步骤七:边界与验证
- 租户无景区:返回 0,不外扩范围;
- 父租户无订单但子孙有订单:因按“去重后的景区集合”过滤,仍可统计到子孙订单;
- 景区在两条路径被同时反查到:`LinkedHashSet` 去重,避免重复;
- `webApp`:返回全量(不传 `tourismIds`),仅受全局时间/支付类型等条件限制。
步骤八:性能与索引
- 索引:`tourisms(tenant_id)`、`qrcodes(tenant_id)`、`orders(tourism_id, create_time)`;
- 大树场景建议缓存“租户→子孙集合”,定期刷新;
- SQL 日志可选开启:`zlt.datascope.enabled-sql-debug=true`(请勿在生产长期开启)。
步骤九:自测清单
- 选择一级租户:含自身+所有下级;
- 选择二级租户:含自身+所有子孙;
- 子孙存在订单但父级景区无订单:应统计到;
- 重复景区来源(景区表与二维码表):结果不重复;
- `includeChildren=false`:仅自身;
- `webApp`:全量。
+99 -33
View File
@@ -33,7 +33,6 @@ const Welcome: React.FC = () => {
}
};
// 仅当选择了租户后再拉取,避免进入页面出现“空 -> 有”的闪动
useEffect(() => {
if (!tenantId) return;
load();
@@ -43,33 +42,79 @@ const Welcome: React.FC = () => {
const orderStats = stat?.orderStats || {};
const chartStats = stat?.chartStats || {};
const trendData = chartStats?.orderTrend || [];
// 每日趋势:订单数/订单金额(元)/退款订单数/退款金额(元)
const trendData = chartStats?.dailySummary || [];
const distributionData = chartStats?.orderDistribution || [];
const trendColors: Record<string, string> = {
'订单数': '#1668DC',
'订单金额(元)': '#FA8C16',
'退款订单数': '#A0D911',
'退款金额(元)': '#F5222D',
};
const trendConfig: any = {
data: trendData,
xField: 'date',
yField: 'value',
seriesField: 'type',
smooth: true,
height: 300,
height: 320,
legend: { position: 'top' },
tooltip: { shared: true },
color: ({ type }: any) => trendColors[type] || '#5B8FF9',
lineStyle: { lineWidth: 2 },
point: { size: 2, shape: 'circle' },
tooltip: {
shared: true,
customContent: (title: string, items: any[]) => {
if (!items || !items.length) return '';
const rows = items
.map((it) => {
const name = it?.name || it?.data?.type;
const v = it?.data?.value ?? 0;
const isAmount = name && String(name).includes('金额');
const text = isAmount ? `¥${Number(v).toFixed(2)}` : `${Math.round(Number(v))}`;
const color = it?.color || '#333';
return `<div style="display:flex;align-items:center;gap:8px;">
<span style="display:inline-block;width:8px;height:8px;border-radius:50%;background:${color}"></span>
<span>${name}</span>
<span style="margin-left:auto;font-weight:600;">${text}</span>
</div>`;
})
.join('');
return `<div style="padding:8px 8px 4px 8px;min-width:200px;">
<div style="margin-bottom:6px;font-weight:600;">${title}</div>
${rows}
</div>`;
},
},
animation: false,
};
const distributionPalette = [
'#1668DC', '#5AD8A6', '#F6BD16', '#E8684A', '#6DC8EC', '#9270CA', '#FF9D4D', '#269A99', '#FF99C3', '#1D9ED1',
];
const distributionConfig: any = {
data: distributionData,
angleField: 'value',
colorField: 'type',
radius: 0.9,
label: { type: 'outer', content: '{name}\n{percentage}' },
color: distributionPalette,
legend: { position: 'right' },
label: {
type: 'spider',
content: (data: any) => {
const total = (distributionData || []).reduce((s: number, d: any) => s + (Number(d.value) || 0), 0);
const pct = total > 0 ? `${((Number(data.value) / total) * 100).toFixed(1)}%` : '0%';
return `${data.type} ${pct} (${data.value})`;
},
},
animation: false,
};
return (
<div className="page-enter" style={{ padding: 24 }}>
{/* 顶部工具区:左标题,右侧筛选/粒度/刷新 */}
{/* 顶部工具区 */}
<Card className="modern-card" style={{ marginBottom: 16 }}>
<Row align="middle" justify="space-between" gutter={[12, 12]}>
<Col flex="none">
@@ -96,14 +141,14 @@ const Welcome: React.FC = () => {
</Row>
</Card>
{/* KPI 指标卡:两列均分,内容居中,不留空白 */}
{/* 第一行:总订单概览 / 收入总览(两侧对称,各3项) */}
<Row gutter={[16, 16]}>
<Col xs={24} md={12}>
<Card loading={pageLoading}>
<Card loading={pageLoading} style={{ height: '100%' }}>
<Space direction="vertical" style={{ width: '100%' }} size={12}>
<Space align="center" size={8}>
<ShoppingCartOutlined />
<Text strong>订单</Text>
<Text strong>总订单概览</Text>
</Space>
<Row gutter={8} align="middle" style={{ width: '100%' }}>
<Col xs={12} sm={10} md={10}><Text type="secondary">总订单数</Text></Col>
@@ -118,35 +163,29 @@ const Welcome: React.FC = () => {
</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={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="," />
<Statistic value={(orderStats.totalOrders || 0) - (orderStats.refundedOrders || 0)} valueStyle={{ fontWeight: 600, whiteSpace: 'nowrap' }} groupSeparator="," />
</Col>
</Row>
</Space>
</Card>
</Col>
<Col xs={24} md={12}>
<Card loading={pageLoading}>
<Card loading={pageLoading} style={{ height: '100%' }}>
<Space direction="vertical" style={{ width: '100%' }} size={12}>
<Space align="center" size={8}>
<PayCircleOutlined />
<Text strong>收入</Text>
<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={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={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>
@@ -157,32 +196,59 @@ const Welcome: React.FC = () => {
<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>
</Col>
</Row>
{/* 图表区:趋势 + 状态分布 */}
{/* 第二行:今日统计 / 状态分布(两侧对称) */}
<Row gutter={[16, 16]} style={{ marginTop: 16 }}>
<Col xs={24} md={16}>
<Card title="订单趋势(创建/完成/退款)" loading={pageLoading}>
<Line {...trendConfig} />
<Col xs={24} md={12}>
<Card loading={pageLoading} style={{ height: '100%' }}>
<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.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>
<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.todayPaidOrders || 0} valueStyle={{ fontWeight: 600, whiteSpace: 'nowrap' }} groupSeparator="," />
</Col>
</Row>
</Space>
</Card>
</Col>
<Col xs={24} md={8}>
<Card title="订单状态分布" loading={pageLoading}>
<Col xs={24} md={12}>
<Card title="订单状态分布" loading={pageLoading} style={{ height: '100%' }}>
<Pie {...distributionConfig} />
</Card>
</Col>
</Row>
{/* 第三行:每日趋势(满宽) */}
<Row gutter={[16, 16]} style={{ marginTop: 16 }}>
<Col span={24}>
<Card title="每日趋势:订单数 / 订单金额 / 退款" loading={pageLoading}>
<Line {...trendConfig} />
</Card>
</Col>
</Row>
</div>
);
};
export default Welcome;