!36 1:首页多租户查询优化 2:景点列表查询优化

Merge pull request !36 from 鸭先知/feature_dzc
This commit is contained in:
2025-10-09 13:22:54 +00:00
committed by Gitee
36 changed files with 1143 additions and 572 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;
@@ -54,7 +54,9 @@ public class DashboardController {
anchor = com.central.common.context.LoginUserContextHolder.getCurrentTenantId();
}
}
} catch (Exception ignored) { }
} catch (Exception ignored) {
log.error("获取当前登录用户租户失败");
}
boolean withChildren = (includeChildren == null) || Boolean.TRUE.equals(includeChildren);
params.put("tenantId", anchor);
params.put("includeChildren", withChildren);
@@ -190,6 +192,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 +204,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,10 @@ public interface DashboardMapper {
"<if test='p.deviceSn != null and p.deviceSn != \"\"'>",
" AND o.device_sn = #{p.deviceSn}",
"</if>",
"<if test='p.tourismIds != null and p.tourismIds.size > 0'>",
" AND o.tourism_id IN",
" <foreach collection='p.tourismIds' item='tid' open='(' separator=',' close=')'>#{tid}</foreach>",
"</if>",
"</script>"
})
Long getYesterdayOrders(@Param("p") Map<String, Object> params);
@@ -501,10 +505,187 @@ public interface DashboardMapper {
"<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>",
"<if test='p.tourismIds != null and p.tourismIds.size > 0'>",
" AND o.tourism_id IN",
" <foreach collection='p.tourismIds' item='tid' open='(' separator=',' close=')'>#{tid}</foreach>",
"</if>",
"GROUP BY ",
"<choose>",
" <when test=\"p.statType == 'year'\"> DATE_FORMAT(o.create_time, '%Y') </when>",
" <when test=\"p.statType == 'month'\"> DATE_FORMAT(o.create_time, '%Y-%m') </when>",
" <otherwise> DATE_FORMAT(o.create_time, '%Y-%m-%d') </otherwise>",
"</choose>",
"UNION ALL",
"SELECT",
" <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>",
"<if test='p.tourismIds != null and p.tourismIds.size > 0'>",
" AND o.tourism_id IN",
" <foreach collection='p.tourismIds' item='tid' open='(' separator=',' close=')'>#{tid}</foreach>",
"</if>",
"GROUP BY ",
"<choose>",
" <when test=\"p.statType == 'year'\"> DATE_FORMAT(o.create_time, '%Y') </when>",
" <when test=\"p.statType == 'month'\"> DATE_FORMAT(o.create_time, '%Y-%m') </when>",
" <otherwise> DATE_FORMAT(o.create_time, '%Y-%m-%d') </otherwise>",
"</choose>",
"UNION ALL",
"SELECT",
" <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>",
"<if test='p.tourismIds != null and p.tourismIds.size > 0'>",
" AND o.tourism_id IN",
" <foreach collection='p.tourismIds' item='tid' open='(' separator=',' close=')'>#{tid}</foreach>",
"</if>",
"GROUP BY ",
"<choose>",
" <when test=\"p.statType == 'year'\"> DATE_FORMAT(o.create_time, '%Y') </when>",
" <when test=\"p.statType == 'month'\"> DATE_FORMAT(o.create_time, '%Y-%m') </when>",
" <otherwise> DATE_FORMAT(o.create_time, '%Y-%m-%d') </otherwise>",
"</choose>",
"UNION ALL",
"SELECT",
" <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.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",
"</script>"
})
List<TrendDataVO> getDailyOrderSummary(@Param("p") Map<String, Object> params);
@Select({
"<script>",
"SELECT",
@@ -1,11 +1,13 @@
package com.central.order.mapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.central.common.datascope.annotation.IgnoreTenantScope;
import com.central.db.mapper.SuperMapper;
import com.central.order.model.Tourism;
import com.central.order.model.TourismWithDistance;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.math.BigDecimal;
import java.util.List;
@@ -85,4 +87,13 @@ public interface TourismMapper extends SuperMapper<Tourism> {
*/
List<Long> findTourismIdsByTenantIdsFromQrcodes(@Param("tenantIds") List<String> tenantIds);
}
/**
* 获取全部景区ID(用于webApp统计全库时的范围构建)
*/
List<Long> findAllTourismIds();
/**
* 根据单个租户ID查询景区ID集合(XML映射)
*/
List<Long> findTourismIdsByTenantId(@Param("tenantId") String tenantId);
}
@@ -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;
}
@@ -1,14 +1,11 @@
package com.central.order.service.impl;
import com.central.common.context.LoginUserContextHolder;
import com.central.common.context.TenantQueryOverrideContext;
import com.central.common.datascope.annotation.IgnoreTenantScope;
import com.central.common.model.PageResult;
import com.central.common.service.ITenantHierarchyService;
import com.central.common.utils.SpringContextHolder;
import com.central.order.mapper.DashboardMapper;
import com.central.order.mapper.TourismMapper;
import com.central.order.model.Order;
import com.central.order.model.OrderStatistics;
import com.central.order.model.vo.*;
import com.central.order.service.IDashboardService;
import com.central.order.service.IOrderService;
@@ -35,108 +32,104 @@ public class DashboardServiceImpl implements IDashboardService {
@Override
@IgnoreTenantScope
public DashboardStatisticsVO getDashboardStatistics(Map<String, Object> params) {
// 依据租户层级组装景区ID集合,作为统计范围(支持 includeChildren=false 仅当前租户)
// 核心流程:租户 → 子孙租户 → 景区 → 订单统计
try {
// 获取前端传来的tenantId,如果没有则使用当前登录用户的租户
// Step 1: 获取当前租户ID
String tenantId = params != null && params.get("tenantId") != null ?
String.valueOf(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) {}
// Step 2: 获取自己及所有子孙租户(始终包含子租户,确保数据汇总正确)
List<String> tenantIds = tenantResolverService.resolveTenantIds(tenantId, true);
// 处理时间维度参数,如果没有传时间范围,根据statType自动生成
String statType = params != null && params.get("statType") != null ?
String.valueOf(params.get("statType")) : "day";
if (params != null && (params.get("startTime") == null || "".equals(params.get("startTime")))) {
java.time.LocalDate now = java.time.LocalDate.now();
java.time.format.DateTimeFormatter formatter = java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd");
switch (statType) {
case "year":
// 最近5年
params.put("startTime", now.minusYears(1).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("endTime", now.format(formatter) + " 23:59:59");
break;
case "day":
default:
// 最近7天
params.put("startTime", now.minusDays(6).format(formatter));
params.put("endTime", now.format(formatter) + " 23:59:59");
break;
}
if (tenantIds == null || tenantIds.isEmpty()) {
log.warn("无法获取租户列表,tenantId: {}", tenantId);
// 返回空数据
DashboardStatisticsVO emptyStats = new DashboardStatisticsVO();
emptyStats.setOrderStats(new OrderStatisticsVO());
emptyStats.setChartStats(new ChartStatistics());
emptyStats.setFilterOptions(new FilterOptions());
return emptyStats;
}
List<String> tenantIds = tenantResolverService.resolveTenantIds(tenantId, includeChildren);
log.info("租户 {} 获取到 {} 个租户(含自己及子孙)", tenantId, tenantIds.size());
params.put("tenantIds", tenantIds);
// 特殊处理:如果是webApp且没有获取到租户列表,则查询所有景区
if ("webApp".equals(tenantId) && (tenantIds == null || tenantIds.isEmpty())) {
// 不设置tourismIds,让查询返回所有景区的数据
log.info("webApp租户统计所有数据,时间范围: {} 到 {}",
params.get("startTime"), params.get("endTime"));
} else if (tenantIds != null && !tenantIds.isEmpty()) {
List<Long> tourismIds = resolveTourismIdsByTenants(tenantIds);
if (tourismIds != null && !tourismIds.isEmpty()) {
params.put("tourismIds", tourismIds);
log.info("统计范围 - 租户IDs: {} 个租户, 景区IDs: {} 个景区, 时间范围: {} 到 {}",
tenantIds.size(), tourismIds.size(), params.get("startTime"), params.get("endTime"));
} else {
// 没有找到景区,设置一个不存在的ID,避免查询到所有数据
params.put("tourismIds", java.util.Collections.singletonList(-1L));
log.warn("租户 {} 没有关联的景区", tenantIds);
}
// Step 3: 根据租户集合查询所有关联的景
List<Long> tourismIds = resolveTourismIdsByTenants(tenantIds);
if (tourismIds == null || tourismIds.isEmpty()) {
log.warn("租户集合无关联景区,tenantIds: {}", tenantIds);
// 设置空的景区列表,确保查询不会返回任何数据
tourismIds = new ArrayList<>();
tourismIds.add(-1L); // 添加一个不存在的ID,确保查询结果为空
}
params.put("tourismIds", tourismIds);
log.info("租户 {} 关联 {} 个景区,开始统计订单数据", tenantId, tourismIds.size());
// 保留必要的查询条件,不要删除
// 时间条件等其他参数应该保留,让前端或调用方控制
} catch (Exception e) {
log.warn("解析租户/景区范围失败,使用默认上下文: {}", e.getMessage());
log.error("解析租户/景区范围失败: {}", e.getMessage(), e);
}
DashboardStatisticsVO statistics = new DashboardStatisticsVO();
DashboardStatisticsVO statistics = new DashboardStatisticsVO();
try {
// 1. 获取订单统计(包含对账数据)
statistics.setOrderStats(getOrderStatistics(params));
// 2. 获取图表统计
statistics.setChartStats(getChartStatistics(params));
// 3. 获取筛选选项
statistics.setFilterOptions(getFilterOptions(params));
} catch (Exception e) {
log.error("获取仪表盘统计数据失败", e);
}
return statistics;
}
@Override
public PageResult<Order> getDashboardOrders(Map<String, Object> params) {
try {
// 获取订单列表
PageResult<Order> result = orderService.findList(params);
// 添加调试日志
log.info("获取仪表盘订单列表 - 参数: {}, 结果数量: {}", params, result.getCount());
return result;
// 与统计接口保持一致的逻辑
// Step 1: 获取当前租户ID
String tenantId = params != null && params.get("tenantId") != null ?
String.valueOf(params.get("tenantId")) : null;
// Step 2: 获取自己及所有子孙租户
List<String> tenantIds = tenantResolverService.resolveTenantIds(tenantId, true);
if (tenantIds == null || tenantIds.isEmpty()) {
log.warn("无法获取租户列表,tenantId: {}", tenantId);
return PageResult.<Order>builder()
.data(new ArrayList<>())
.count(0L)
.resp_code(0)
.build();
}
params.put("tenantIds", tenantIds);
// Step 3: 根据租户集合查询所有关联的景区
List<Long> tourismIds = resolveTourismIdsByTenants(tenantIds);
if (tourismIds != null && !tourismIds.isEmpty()) {
params.put("tourismIds", tourismIds);
log.info("查询订单列表 - 租户: {}, 关联景区数: {}", tenantId, tourismIds.size());
} else {
// 无关联景区,设置空结果保护
params.put("tourismIds", java.util.Collections.singletonList(-1L));
log.warn("租户 {} 无关联景区", tenantId);
}
} catch (Exception e) {
log.error("获取仪表盘订单列表失败", e);
return new PageResult<>();
log.error("解析订单列表租户/景区范围失败:{}", e.getMessage(), e);
}
// 获取订单列表
PageResult<Order> result = orderService.findList(params);
// 添加调试日志
log.info("获取仪表盘订单列表 - 参数: {}, 结果数量: {}", params, result.getCount());
return result;
}
/**
@@ -153,44 +146,41 @@ public class DashboardServiceImpl implements IDashboardService {
// 计算订单增长率
Long yesterdayOrders = dashboardMapper.getYesterdayOrders(params);
if (yesterdayOrders > 0) {
if (yesterdayOrders != null && yesterdayOrders > 0) {
BigDecimal growth = new BigDecimal(stats.getTodayOrders() - yesterdayOrders)
.divide(new BigDecimal(yesterdayOrders), 4, RoundingMode.HALF_UP)
.multiply(new BigDecimal(100));
.divide(new BigDecimal(yesterdayOrders), 4, RoundingMode.HALF_UP)
.multiply(new BigDecimal(100));
stats.setOrderGrowth(growth);
}
// 计算完成率
Long completedOrders = dashboardMapper.getCompletedOrders(params);
if (stats.getTotalOrders() > 0) {
if (stats.getTotalOrders() != null && stats.getTotalOrders() > 0) {
BigDecimal completionRate = new BigDecimal(completedOrders)
.divide(new BigDecimal(stats.getTotalOrders()), 4, RoundingMode.HALF_UP)
.multiply(new BigDecimal(100));
.divide(new BigDecimal(stats.getTotalOrders()), 4, RoundingMode.HALF_UP)
.multiply(new BigDecimal(100));
stats.setCompletionRate(completionRate);
}
// 设置总完成订单数
stats.setCompletedOrders(completedOrders);
// 获取总收款订单数量
// 获取总收款订单数
Long totalPaidOrders = dashboardMapper.getTotalPaidOrders(params);
stats.setTotalPaidOrders(totalPaidOrders);
// 添加调试日志
// 调试日志
log.info("总收款订单数统计 - 参数: {}, 结果: {}", params, totalPaidOrders);
log.info("时间范围详情 - startTime: {}, endTime: {}", params.get("startTime"), params.get("endTime"));
// 获取今日收款订单数量
Long todayPaidOrders = dashboardMapper.getTodayPaidOrders(params);
stats.setTodayPaidOrders(todayPaidOrders);
// 添加调试日志
log.info("今日收款订单数统计 - 参数: {}, 结果: {}", params, todayPaidOrders);
// 获取退款订单数量
// 获取退款订单数
Long refundedOrders = dashboardMapper.getRefundedOrders(params);
stats.setRefundedOrders(refundedOrders);
// 获取今日退款订单数量
// 获取今日退款订单数
Long todayRefundedOrders = dashboardMapper.getTodayRefundedOrders(params);
stats.setTodayRefundedOrders(todayRefundedOrders);
@@ -214,39 +204,40 @@ public class DashboardServiceImpl implements IDashboardService {
*/
private ChartStatistics getChartStatistics(Map<String, Object> params) {
ChartStatistics chartStats = new ChartStatistics();
try {
// 获取订单趋势数据
List<TrendDataVO> orderTrend = dashboardMapper.getOrderTrend(params);
chartStats.setOrderTrend(orderTrend);
// 获取订单状态分布数据
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);
chartStats.setQrcodeOrderCount(qrcodeOrderCount);
} catch (Exception e) {
log.error("获取图表统计数据失败", e);
// 设置空数据避免前端报错
chartStats.setOrderTrend(new ArrayList<>());
chartStats.setOrderDistribution(new ArrayList<>());
chartStats.setIncomeBreakdown(new ArrayList<>());
chartStats.setDailySummary(new ArrayList<>());
chartStats.setQrcodeOrderCount(new ArrayList<>());
}
return chartStats;
}
@@ -255,105 +246,13 @@ public class DashboardServiceImpl implements IDashboardService {
*/
private FilterOptions getFilterOptions(Map<String, Object> params) {
FilterOptions options = new FilterOptions();
// 获取景区列表
options.setTourismList(dashboardMapper.getTourismOptions());
// 获取二维码列表
options.setQrcodeList(dashboardMapper.getQrcodeOptions(params));
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);
}
/**
* 解析当前请求上下文的租户集合(包含子租户)
* @deprecated 使用 TenantResolverService.resolveTenantIds 方法替代
@@ -368,20 +267,48 @@ public class DashboardServiceImpl implements IDashboardService {
*/
private List<Long> resolveTourismIdsByTenants(List<String> tenantIds) {
try {
if (tenantIds == null || tenantIds.isEmpty()) return java.util.Collections.emptyList();
// 先按景区表直接匹配租户ID
List<Long> byTourism = tourismMapper.findTourismIdsByTenantIds(tenantIds);
java.util.Set<Long> union = new java.util.LinkedHashSet<>();
if (byTourism != null) union.addAll(byTourism);
// 容错:部分环境景区未直连租户,改用二维码表反查所关联的景区ID
if (union.isEmpty()) {
List<Long> byQrcodes = tourismMapper.findTourismIdsByTenantIdsFromQrcodes(tenantIds);
if (byQrcodes != null) union.addAll(byQrcodes);
if (tenantIds == null || tenantIds.isEmpty()) {
log.warn("租户集合为空,无法查询景区");
return java.util.Collections.emptyList();
}
return new java.util.ArrayList<>(union);
log.debug("开始查询 {} 个租户关联的景区", tenantIds.size());
// 使用Set去重,遍历每个租户查询其景区
java.util.Set<Long> allTourismIds = new java.util.LinkedHashSet<>();
// 遍历每个租户,单独查询其关联的景区
for (String tenantId : tenantIds) {
// 使用无租户过滤的查询方法
List<Long> singleTenantTourisms = queryTourismIdsWithoutTenantFilter(tenantId);
if (singleTenantTourisms != null && !singleTenantTourisms.isEmpty()) {
allTourismIds.addAll(singleTenantTourisms);
}
}
if (allTourismIds.isEmpty()) {
log.warn("租户集合 {} 没有关联的景区", tenantIds);
return java.util.Collections.emptyList();
}
// 转换为List返回
List<Long> tourismIds = new java.util.ArrayList<>(allTourismIds);
log.debug("从景区表查询到 {} 个景区(去重后)", tourismIds.size());
return tourismIds;
} catch (Exception e) {
log.debug("根据租户查询景区失败: {}", e.getMessage());
log.error("根据租户查询景区失败: {}", e.getMessage(), e);
return java.util.Collections.emptyList();
}
}
/**
* 忽略多租户过滤,查询指定租户的景区
*/
@IgnoreTenantScope
public List<Long> queryTourismIdsWithoutTenantFilter(String tenantId) {
return tourismMapper.findTourismIdsByTenantId(tenantId) ;
}
}
@@ -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集合(包含子租户)
@@ -43,38 +43,25 @@ public class TenantResolverService {
return Collections.emptyList();
}
// webApp是特殊的超级租户,应该返回空列表(查询所有数据)
if ("webApp".equals(anchor)) {
log.info("webApp租户统计所有数据");
return Collections.emptyList(); // 空列表表示不限制租户
}
// 如果不包含子租户,只返回当前租户
if (!includeChildren) {
log.info("不包含子租户,仅返回当前租户: {}", anchor);
return Collections.singletonList(anchor);
}
// 通过Feign调用user-center获取子孙租户
// 通过Feign调用user-center获取子孙租户(包括webApp)
try {
log.info("开始获取租户 {} 的所有子孙租户", anchor);
Result<List<String>> result = userCenterService.getDescendantTenantIds(anchor);
List<String> tenantIds = userCenterService.getSonTenantIds(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");
if (tenantIds == null || tenantIds.isEmpty()) {
log.warn("租户 {} 没有子孙租户,返回自身", anchor);
return Collections.singletonList(anchor);
}
return tenantIds;
} catch (Exception e) {
log.error("获取租户层级失败: {}", e.getMessage(), e);
}
// 降级:只返回当前租户
log.warn("获取子孙租户失败,降级为仅当前租户: {}", anchor);
return Collections.singletonList(anchor);
@@ -1,6 +1,8 @@
package com.central.order.service.impl;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.central.common.datascope.annotation.IgnoreTenantScope;
import com.central.common.feign.UserService;
import com.central.common.model.PageResult;
import com.central.common.model.Result;
import com.central.common.service.impl.SuperServiceImpl;
@@ -37,6 +39,8 @@ public class TourismServiceImpl extends SuperServiceImpl<TourismMapper, Tourism>
@Autowired
private FileCenterService fileCenterService;
@Autowired
private UserService userCenterService;
/**
* 列表
@@ -44,8 +48,22 @@ public class TourismServiceImpl extends SuperServiceImpl<TourismMapper, Tourism>
* @return
*/
@Override
@IgnoreTenantScope
public PageResult<Tourism> findList(Map<String, Object> params){
Page<Tourism> page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit"));
String anchor= MapUtils.getString(params,"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) {
log.error("获取当前登录用户租户失败");
}
List<String> tenantIds = userCenterService.getSonTenantIds(anchor);
params.put("tenantIds",tenantIds);
List<Tourism> list = baseMapper.findList(page, params);
return PageResult.<Tourism>builder().data(list).resp_code(0).count(page.getTotal()).build();
}
@@ -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>
@@ -130,4 +130,20 @@
ORDER BY q.tourism_id DESC
</select>
<!-- 全部景区ID(webApp全库统计使用) -->
<select id="findAllTourismIds" resultType="java.lang.Long">
SELECT id FROM tourisms WHERE is_del = 0 ORDER BY id DESC
</select>
<!-- 根据单个租户ID查询景区ID集合 -->
<select id="findTourismIdsByTenantId" resultType="java.lang.Long">
SELECT id FROM tourisms
WHERE is_del = 0
<if test="tenantId != null and tenantId != ''">
AND tenant_id = #{tenantId}
</if>
ORDER BY id DESC
</select>
</mapper>
@@ -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());
}
}
}
@@ -0,0 +1,115 @@
package com.central.common.autoconfigure;
import com.central.common.filter.IncludeChildrenParamFilter;
import com.central.common.filter.LoginUserFilter;
import com.central.common.filter.TenantFilter;
import com.central.common.filter.TenantParamOverrideFilter;
import com.central.common.filter.TenantQueryOverrideFilter;
import com.central.common.service.UserTenantInitializer;
import jakarta.servlet.Filter;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.core.Ordered;
/**
* 多租户相关自动配置
* - 注册登录用户与租户解析相关过滤器
* - 暴露用户租户初始化器(登录成功后用于计算可访问租户范围)
*/
@AutoConfiguration
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
@ConditionalOnClass(Filter.class)
public class TenantInitializerAutoConfiguration {
// LoginUserFilter - 提取并缓存当前登录用户
@Bean
@ConditionalOnMissingBean
public LoginUserFilter loginUserFilter() {
return new LoginUserFilter();
}
@Bean
@ConditionalOnMissingBean(name = "loginUserFilterRegistration")
public FilterRegistrationBean<LoginUserFilter> loginUserFilterRegistration(LoginUserFilter filter) {
FilterRegistrationBean<LoginUserFilter> reg = new FilterRegistrationBean<>(filter);
reg.setOrder(Ordered.HIGHEST_PRECEDENCE + 10);
reg.addUrlPatterns("/*");
return reg;
}
// IncludeChildrenParamFilter - 解析 includeChildren 参数
@Bean
@ConditionalOnMissingBean
public IncludeChildrenParamFilter includeChildrenParamFilter() {
return new IncludeChildrenParamFilter();
}
@Bean
@ConditionalOnMissingBean(name = "includeChildrenParamFilterRegistration")
public FilterRegistrationBean<IncludeChildrenParamFilter> includeChildrenParamFilterRegistration(IncludeChildrenParamFilter filter) {
FilterRegistrationBean<IncludeChildrenParamFilter> reg = new FilterRegistrationBean<>(filter);
reg.setOrder(Ordered.HIGHEST_PRECEDENCE + 18);
reg.addUrlPatterns("/*");
return reg;
}
// TenantParamOverrideFilter - 解析前端传入的 tenantId 参数(覆盖查询锚点)
@Bean
@ConditionalOnMissingBean
public TenantParamOverrideFilter tenantParamOverrideFilter() {
return new TenantParamOverrideFilter();
}
@Bean
@ConditionalOnMissingBean(name = "tenantParamOverrideFilterRegistration")
public FilterRegistrationBean<TenantParamOverrideFilter> tenantParamOverrideFilterRegistration(TenantParamOverrideFilter filter) {
FilterRegistrationBean<TenantParamOverrideFilter> reg = new FilterRegistrationBean<>(filter);
reg.setOrder(Ordered.HIGHEST_PRECEDENCE + 19);
reg.addUrlPatterns("/*");
return reg;
}
// TenantQueryOverrideFilter - 校验并应用租户覆盖锚点
@Bean
@ConditionalOnMissingBean
public TenantQueryOverrideFilter tenantQueryOverrideFilter() {
return new TenantQueryOverrideFilter();
}
@Bean
@ConditionalOnMissingBean(name = "tenantQueryOverrideFilterRegistration")
public FilterRegistrationBean<TenantQueryOverrideFilter> tenantQueryOverrideFilterRegistration(TenantQueryOverrideFilter filter) {
FilterRegistrationBean<TenantQueryOverrideFilter> reg = new FilterRegistrationBean<>(filter);
reg.setOrder(Ordered.HIGHEST_PRECEDENCE + 20);
reg.addUrlPatterns("/*");
return reg;
}
// TenantFilter - 兼容旧的 tenantId 参数(可选)
@Bean
@ConditionalOnMissingBean
public TenantFilter tenantFilter() {
return new TenantFilter();
}
@Bean
@ConditionalOnMissingBean(name = "tenantFilterRegistration")
public FilterRegistrationBean<TenantFilter> tenantFilterRegistration(TenantFilter filter) {
FilterRegistrationBean<TenantFilter> reg = new FilterRegistrationBean<>(filter);
reg.setOrder(Ordered.HIGHEST_PRECEDENCE + 50);
reg.addUrlPatterns("/*");
return reg;
}
// 用户租户信息初始化器(若业务侧未显式定义 Bean,则由此提供)
@Bean
@ConditionalOnMissingBean
public UserTenantInitializer userTenantInitializer() {
return new UserTenantInitializer();
}
}
@@ -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 {
}
}
@@ -1,5 +1 @@
com.central.common.filter.TenantFilter
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`:全量。
+450 -68
View File
@@ -1,27 +1,90 @@
import React, { useEffect, useRef, useState } from 'react';
import { Card, Space, Typography, Row, Col, Statistic, Segmented, Button, message } from 'antd';
import { ShoppingCartOutlined, PayCircleOutlined, ReloadOutlined } from '@ant-design/icons';
import { Line, Pie } from '@ant-design/plots';
import { Card, Space, Typography, Row, Col, Button, message, DatePicker, Segmented, List, Tag, Statistic, InputNumber, Slider } from 'antd';
import { ReloadOutlined } from '@ant-design/icons';
import { Line, Pie, Column } from '@ant-design/plots';
import TenantScopeFilter from '@/components/TenantScopeFilter';
import { dashboardApi } from '@/services/dashboard';
import { ordersApi } from '@/services/orders';
import moment, { Moment } from 'moment';
const { Title, Text } = Typography;
const { RangePicker } = DatePicker;
type RangeType = 'date' | 'week' | 'month' | 'year';
const makeDefaultToday = (): [Moment, Moment] => [moment().startOf('day'), moment().endOf('day')];
const computeRangeByType = (type: RangeType, anchor?: Moment): [Moment, Moment] => {
const base = (anchor ? anchor.clone() : moment());
const unit = type === 'date' ? 'day' : type;
return [base.clone().startOf(unit as any), base.clone().endOf(unit as any)];
};
const Welcome: React.FC = () => {
// 租户维度
const [tenantId, setTenantId] = useState<string>();
const [includeChildren, setIncludeChildren] = useState<boolean>(true);
const [statType, setStatType] = useState<'day' | 'month' | 'year'>('day');
// 时间范围(默认今日 00:00:00 - 23:59:59)
const [rangeType, setRangeType] = useState<RangeType>('date');
const [range, setRange] = useState<[Moment, Moment]>(makeDefaultToday());
// 加载状态
const [loading, setLoading] = useState<boolean>(false);
const [pageLoading, setPageLoading] = useState<boolean>(true);
const [ordersLoading, setOrdersLoading] = useState<boolean>(false);
const firstLoadRef = useRef(true);
const [stat, setStat] = useState<any>({ orderStats: {}, chartStats: {} });
const load = async () => {
// 数据
const [stat, setStat] = useState<any>({ orderStats: {}, chartStats: {} });
const [orders, setOrders] = useState<any[]>([]);
const [ordersTotal, setOrdersTotal] = useState<number>(0);
const [page, setPage] = useState<number>(1);
const [pageSize, setPageSize] = useState<number>(10);
// 趋势模式:状态曲线 or 景区柱状
const [trendMode, setTrendMode] = useState<'status' | 'tourism'>('status');
const [aggLoading, setAggLoading] = useState<boolean>(false);
const [statusSeries, setStatusSeries] = useState<{ date: string; type: string; value: number }[]>([]);
const [tourismBars, setTourismBars] = useState<{ name: string; value: number }[]>([]);
// 分账比例(平台),默认 70%
const [splitPercent, setSplitPercent] = useState<number>(70);
// 统一获取 start/end 时间字符串
const getTimeParams = () => {
const [start, end] = range || makeDefaultToday();
// 使用本地时间字符串,避免 ISO(UTC) 引起后端解析或时区偏差
return { startTime: start.format('YYYY-MM-DD HH:mm:ss'), endTime: end.format('YYYY-MM-DD HH:mm:ss') };
};
// 加载统计与订单列表
const load = async (opts?: { page?: number; pageSize?: number }) => {
if (firstLoadRef.current) setPageLoading(true);
setLoading(true);
try {
const res: any = await dashboardApi.statistics({ tenantId, includeChildren, statType });
const { startTime, endTime } = getTimeParams();
// 首页统计(默认排除测试二维码)
const statType = (rangeType === 'month' ? 'month' : (rangeType === 'year' ? 'year' : 'day')) as 'day'|'month'|'year';
const res: any = await dashboardApi.statistics({ tenantId, includeChildren, startTime, endTime, statType, includeTestQrcodes: false });
setStat(res?.data || res);
// 右侧订单列表(默认排除测试二维码)
setOrdersLoading(true);
try {
const curPage = opts?.page ?? page;
const curSize = opts?.pageSize ?? pageSize;
const ordersRes: any = await ordersApi.getDashboardOrders({ tenantId, includeChildren, startTime, endTime, includeTestQrcodes: false, page: curPage, limit: curSize });
const data = ordersRes?.data?.data || ordersRes?.data || [];
const total = ordersRes?.data?.count ?? ordersRes?.count ?? (Array.isArray(data) ? data.length : 0);
setOrders(Array.isArray(data) ? data : []);
setOrdersTotal(Number(total) || 0);
setPage(curPage);
setPageSize(curSize);
} catch {
setOrders([]);
setOrdersTotal(0);
} finally {
setOrdersLoading(false);
}
} catch (e) {
message.error('加载统计失败');
} finally {
@@ -33,134 +96,311 @@ const Welcome: React.FC = () => {
}
};
// 仅当选择了租户后再拉取,避免进入页面出现“空 -> 有”的闪动
// 首次/依赖变更自动加载
useEffect(() => {
if (!tenantId) return;
load();
// 条件变化重置到第 1 页
setPage(1);
load({ page: 1, pageSize });
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [tenantId, includeChildren, statType]);
}, [tenantId, includeChildren, rangeType, range]);
const orderStats = stat?.orderStats || {};
// 趋势聚合:当筛选条件或模式变化时刷新
useEffect(() => {
if (!tenantId) return;
// 趋势分析已关闭,跳过聚合
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [tenantId, includeChildren, rangeType, range]);
// Chart 数据
const chartStats = stat?.chartStats || {};
const trendData = chartStats?.orderTrend || [];
const orderStats = stat?.orderStats || {};
const totalAmountYuan = (orderStats.totalAmount || 0) / 100;
const platformAmount = Number(((totalAmountYuan * splitPercent) / 100).toFixed(2));
const tenantAmount = Number((totalAmountYuan - platformAmount).toFixed(2));
const trendData = (chartStats?.dailySummary || []).map((d: any) => ({ ...d, value: Number(d?.value ?? 0) }));
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' },
// 由于当前 @ant-design/plots 版本未注册 spider/outer 等 label 形状,关闭标签以避免 Unknown Component 错误
label: false,
animation: false,
};
// 事件:分段切换 -> 根据当前范围起点计算该粒度的起止
const handleRangeTypeChange = (val: any) => {
const t = (val as RangeType) || 'date';
setRangeType(t);
const anchor = range?.[0] || moment();
setRange(computeRangeByType(t, anchor));
};
// 事件:手动选择时间范围
const handleRangeChange = (vals: any) => {
if (!Array.isArray(vals) || vals.length !== 2 || !vals[0] || !vals[1]) {
setRange(makeDefaultToday());
return;
}
let s = vals[0] as Moment;
let e = vals[1] as Moment;
if (rangeType !== 'date') {
s = s.clone().startOf('day');
e = e.clone().endOf('day');
}
setRange([s, e]);
};
// 拉取当前筛选条件下的订单数据,前端聚合生成:
// - 状态曲线(按天、按状态统计订单数)
// - 景区柱状(按景区统计订单数)
const loadAggregations = async () => {
if (!tenantId) return;
setAggLoading(true);
try {
const { startTime, endTime } = getTimeParams();
// 分页抓取,最多抓取一定数量以避免阻塞
const maxRecords = 5000;
const pageSizeAgg = 200;
let cp = 1;
let pulled = 0;
const collected: any[] = [];
// 先探测总量
let total = 0;
try {
const probe: any = await ordersApi.getDashboardOrders({ tenantId, includeChildren, startTime, endTime, includeTestQrcodes: false, page: 1, limit: 1 });
total = Number(probe?.data?.count ?? probe?.count ?? 0) || 0;
} catch {}
if (total === 0) {
setStatusSeries([]);
setTourismBars([]);
return;
}
const target = Math.min(total, maxRecords);
while (pulled < target) {
const res: any = await ordersApi.getDashboardOrders({ tenantId, includeChildren, startTime, endTime, includeTestQrcodes: false, page: cp, limit: pageSizeAgg });
const list = res?.data?.data || res?.data || [];
if (!Array.isArray(list) || list.length === 0) break;
collected.push(...list);
pulled += list.length;
cp += 1;
if (list.length < pageSizeAgg) break;
}
// 聚合:按天、按状态计数
const byDateStatus = new Map<string, Map<number, number>>();
const byTourism = new Map<string, number>();
for (const it of collected) {
const date = (it?.createTime ? moment(it.createTime) : moment()).format('YYYY-MM-DD');
const st = Number(it?.orderStatus);
const name = it?.tourismName || '未知景区';
// 状态聚合
if (!byDateStatus.has(date)) byDateStatus.set(date, new Map<number, number>());
const m = byDateStatus.get(date)!;
m.set(st, (m.get(st) || 0) + 1);
// 景区聚合
byTourism.set(name, (byTourism.get(name) || 0) + 1);
}
// 转换为折线图数据(时间升序)
const dates = Array.from(byDateStatus.keys()).sort((a, b) => a.localeCompare(b));
const series: { date: string; type: string; value: number }[] = [];
for (const d of dates) {
const m = byDateStatus.get(d)!;
for (const opt of STATUS_OPTIONS) {
const v = m.get(opt.value) || 0;
if (v > 0) series.push({ date: d, type: opt.label, value: v });
}
}
// 转换为柱状图数据(按数量降序,取前 20)
const bars: { name: string; value: number }[] = Array.from(byTourism.entries())
.map(([name, value]) => ({ name, value }))
.sort((a, b) => b.value - a.value)
.slice(0, 20);
setStatusSeries(series);
setTourismBars(bars);
} catch {
setStatusSeries([]);
setTourismBars([]);
} finally {
setAggLoading(false);
}
};
// 订单状态:1. 待支付 2. 已取消 3. 支付成功 4. 设备执行中 5. 素材上传中 6. 素材上传完成 7. 用户已下载完成 8. 退款中 9. 退款成功 10. 退款失败
// Tag 颜色使用 antd v4 预设色
const STATUS_OPTIONS: { value: number; label: string; color?: string }[] = [
{ value: 1, label: '待支付', color: 'gold' },
{ value: 2, label: '已取消' },
{ value: 3, label: '支付成功', color: 'green' },
{ value: 4, label: '设备执行中', color: 'blue' },
{ value: 5, label: '素材上传中', color: 'geekblue' },
{ value: 6, label: '素材上传完成', color: 'cyan' },
{ value: 7, label: '用户已下载完成', color: 'purple' },
{ value: 8, label: '退款中', color: 'orange' },
{ value: 9, label: '退款成功', color: 'lime' },
{ value: 10, label: '退款失败', color: 'red' },
];
const PAY_TYPE_OPTIONS: { value: number; label: string; color?: string }[] = [
{ value: 1, label: '微信支付', color: 'green' },
{ value: 2, label: '优惠券支付', color: 'blue' },
];
// 将金额(元)格式化为千分位两位小数
const fmtCurrency = (yuan?: number) => {
const v = Number(yuan || 0);
return v.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
};
// 从订单行中解析金额(优先 orderAmount,其次 amount)。
// orderAmount 多为“分”的整数字符串,如 "5000" => 50.00 元。
const getOrderAmountYuan = (it: any): number => {
try {
const oa = (it || {}).orderAmount;
if (oa != null) {
const n = Number(oa);
if (Number.isFinite(n)) return n / 100;
const f = parseFloat(String(oa));
if (Number.isFinite(f)) return f;
}
const a = (it || {}).amount;
if (a != null) {
const n = Number(a);
if (Number.isFinite(n)) return n / 100;
}
} catch {}
return 0;
};
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">
<Title level={4} style={{ margin: 0 }}>首页统计</Title>
</Col>
<Col flex="none"><Title level={4} style={{ margin: 0 }}>首页统计</Title></Col>
<Col flex="auto">
<Space style={{ width: '100%', justifyContent: 'flex-end', flexWrap: 'wrap' }} size={12}>
<TenantScopeFilter autoApply onChanged={(tid, inc) => { setTenantId(tid); setIncludeChildren(!!inc); }} />
<Space>
<span>统计粒度</span>
<span>统计时间</span>
<Segmented
options={[
{ label: '周', value: 'day' },
{ label: '月', value: 'month' },
{ label: '年', value: 'year' },
]}
value={statType}
onChange={(val) => setStatType(val as any)}
options={[{ label: '日', value: 'date' }, { label: '周', value: 'week' }, { label: '月', value: 'month' }, { label: '年', value: 'year' }]}
value={rangeType}
onChange={handleRangeTypeChange}
/>
<RangePicker
showTime={rangeType === 'date'}
allowClear={false}
value={range as any}
picker={rangeType as any}
onChange={handleRangeChange}
/>
<Button type="primary" icon={<ReloadOutlined />} loading={loading && !pageLoading} onClick={() => load()}>刷新</Button>
</Space>
<Button type="primary" icon={<ReloadOutlined />} loading={loading && !pageLoading} onClick={load}>刷新</Button>
</Space>
</Col>
</Row>
</Card>
{/* KPI 指标卡:两列均分,内容居中,不留空白 */}
{/* 第一行:总订单概览 / 金额统计(两侧对称) */}
<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>
</Space>
<Text strong>总订单概览</Text>
<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} valueStyle={{ fontWeight: 600, whiteSpace: 'nowrap' }} groupSeparator="," />
<Statistic value={orderStats.totalOrders || 0} valueStyle={{ fontWeight: 600, whiteSpace: 'nowrap' }} />
</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.refundedOrders || 0} valueStyle={{ fontWeight: 600, whiteSpace: 'nowrap' }} groupSeparator="," />
<Statistic value={orderStats.refundedOrders || 0} valueStyle={{ fontWeight: 600, whiteSpace: 'nowrap' }} />
</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' }} />
</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>
</Space>
<Text strong>金额统计</Text>
<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="," />
<Statistic value={(orderStats.totalAmount || 0) / 100} precision={2} valueStyle={{ fontWeight: 600, whiteSpace: 'nowrap' }} />
</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="," />
<Statistic value={(orderStats.refundAmount || 0) / 100} precision={2} valueStyle={{ fontWeight: 600, whiteSpace: 'nowrap' }} />
</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.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="," />
<Statistic value={(orderStats.netIncome || 0) / 100} precision={2} valueStyle={{ fontWeight: 600, whiteSpace: 'nowrap' }} />
</Col>
</Row>
</Space>
@@ -168,18 +408,160 @@ const Welcome: React.FC = () => {
</Col>
</Row>
{/* 图表区:趋势 + 状态分布 */}
{/* 分账明细框 */}
<Row gutter={[16, 16]} style={{ marginTop: 16 }}>
<Col xs={24} md={16}>
<Card title="订单趋势(创建/完成/退款)" loading={pageLoading}>
<Line {...trendConfig} />
<Col span={24}>
<Card title="分账明细" loading={pageLoading}>
<Space direction="vertical" size={12} style={{ width: '100%' }}>
<Row align="middle" gutter={12}>
<Col flex="none"><Text>平台分账比例</Text></Col>
<Col flex="240px">
<InputNumber min={0} max={100} value={splitPercent} onChange={(v) => setSplitPercent(Number(v) || 0)} />
<span style={{ marginLeft: 8 }}>%</span>
</Col>
<Col flex="auto">
<Slider min={0} max={100} value={splitPercent} onChange={(v) => setSplitPercent(Number(v))} />
</Col>
<Col flex="none">
<Button onClick={() => setSplitPercent(70)}>重置为 70%</Button>
</Col>
</Row>
<Row gutter={12}>
<Col xs={24} md={8}>
<Card size="small">
<Space direction="vertical" style={{ width: '100%' }}>
<Text type="secondary">订单总金额(元)</Text>
<Statistic value={totalAmountYuan} precision={2} />
</Space>
</Card>
</Col>
<Col xs={24} md={8}>
<Card size="small">
<Space direction="vertical" style={{ width: '100%' }}>
<Text type="secondary">平台分账额度(元)</Text>
<Statistic value={platformAmount} precision={2} />
</Space>
</Card>
</Col>
<Col xs={24} md={8}>
<Card size="small">
<Space direction="vertical" style={{ width: '100%' }}>
<Text type="secondary">租户分账额度(元)</Text>
<Statistic value={tenantAmount} precision={2} />
</Space>
</Card>
</Col>
</Row>
</Space>
</Card>
</Col>
<Col xs={24} md={8}>
<Card title="订单状态分布" loading={pageLoading}>
</Row>
{/* 第一行:订单状态分布 + 右侧订单列表 */}
<Row gutter={[16, 16]}>
<Col xs={24} md={12}>
<Card title="订单状态分布" loading={pageLoading} style={{ height: '100%' }}>
<Pie {...distributionConfig} />
</Card>
</Col>
<Col xs={24} md={12}>
<Card title={`订单列表(共 ${ordersTotal} 条)`} loading={pageLoading} style={{ height: '100%' }}>
<List
loading={ordersLoading}
dataSource={orders}
pagination={{
current: page,
pageSize,
total: ordersTotal,
showSizeChanger: true,
showQuickJumper: true,
onChange: (cp, ps) => { load({ page: cp, pageSize: ps }); },
}}
renderItem={(item: any) => (
<List.Item>
<List.Item.Meta
title={
<Space>
<span>订单号:{item?.orderNo}</span>
{typeof item?.orderStatus !== 'undefined' ? (() => {
const s = STATUS_OPTIONS.find(o => o.value === item.orderStatus);
return <Tag color={s?.color}>{s?.label || '未知'}</Tag>;
})() : null}
</Space>
}
description={
<Space size={16} wrap>
<span>金额:¥{fmtCurrency(getOrderAmountYuan(item))}</span>
{typeof item?.payType !== 'undefined' ? (
<span>
支付方式:
<Tag color={PAY_TYPE_OPTIONS.find(o => o.value === item.payType)?.color || 'default'}>
{PAY_TYPE_OPTIONS.find(o => o.value === item.payType)?.label || '未知'}
</Tag>
</span>
) : null}
<span>景区:{item?.tourismName || '-'}</span>
<span>时间:{item?.createTime || '-'}</span>
</Space>
}
/>
</List.Item>
)}
/>
</Card>
</Col>
</Row>
{/* 第二行:趋势分析(状态曲线 / 景区柱状) */}
<Row gutter={[16, 16]} style={{ marginTop: 16 }}>
<Col span={24}>
<Card
title={
<Space>
<span>趋势分析</span>
<Segmented
options={[{ label: '状态曲线', value: 'status' }, { label: '景区柱状', value: 'tourism' }]}
value={trendMode}
onChange={(v) => setTrendMode(v as any)}
/>
</Space>
}
style={{ display: 'none' }}
loading={pageLoading || aggLoading}
>
{trendMode === 'status' ? (
<Line
data={statusSeries}
xField="date"
yField="value"
seriesField="type"
smooth
height={340}
legend={{ position: 'top' }}
color={(d: any) => {
const label = d?.type;
const opt = STATUS_OPTIONS.find(o => o.label === label);
const colorMap: any = {
gold: '#FAAD14', green: '#52C41A', blue: '#1677FF', geekblue: '#2F54EB', cyan: '#13C2C2', purple: '#722ED1', orange: '#FA8C16', lime: '#A0D911', red: '#F5222D', default: '#5B8FF9'
};
return colorMap[opt?.color || 'default'] || '#5B8FF9';
}}
point={{ size: 2, shape: 'circle' }}
tooltip={{ shared: true }}
/>
) : (
<Column
data={tourismBars}
xField="name"
yField="value"
height={360}
xAxis={{ label: { autoHide: true, autoRotate: true } }}
meta={{ value: { alias: '订单数' } }}
tooltip={{ formatter: (d: any) => ({ name: '订单数', value: String(d?.value ?? 0) }) }}
/>
)}
</Card>
</Col>
</Row>
</div>
);
-108
View File
@@ -1,108 +0,0 @@
# 多租户订单统计修复验证说明
## 问题修复清单
### 1. ✅ 租户层级统计问题修复
**文件**:`DashboardServiceImpl.java`
**修改内容**:
- 行261-342:重写`resolveTenantIds`方法
- 添加本地和远程两种方式获取子孙租户
- 增加详细日志追踪
- 添加降级机制
### 2. ✅ webApp超级租户统计修复
**文件**:`DashboardServiceImpl.java`
**修改内容**:
- 行274-303:特殊处理webApp租户
- webApp获取所有顶级租户及其子孙
- 无法获取时不设置tourismIds(查询所有数据)
### 3. ✅ 订单金额统计SQL修复
**文件**:`DashboardMapper.java`
**修改内容**:
- 行242-247:`getTotalAmount`添加tourismIds过滤
- 行273-278:`getRefundAmount`添加tourismIds过滤
## 验证步骤
### 1. 后端验证
```sql
-- 验证租户层级关系
SELECT * FROM sys_tenant WHERE parent_tenant_id IS NOT NULL;
-- 验证景区与租户关系
SELECT t.id, t.name, t.tenant_id, st.tenant_name
FROM tourisms t
LEFT JOIN sys_tenant st ON t.tenant_id = st.tenant_id;
-- 验证订单统计
SELECT
t.tenant_id,
COUNT(o.id) as order_count,
SUM(o.order_amount) as total_amount
FROM orders o
JOIN tourisms t ON o.tourism_id = t.id
GROUP BY t.tenant_id;
```
### 2. API测试
#### 测试普通租户(含子孙)
```bash
GET /api-order/dashboard/statistics?tenantId={父租户ID}&includeChildren=true&statType=day
```
预期:返回该租户及所有子孙租户的订单统计
#### 测试webApp超级租户
```bash
GET /api-order/dashboard/statistics?tenantId=webApp&includeChildren=true&statType=day
```
预期:返回所有租户的订单统计
#### 测试单个租户(不含子孙)
```bash
GET /api-order/dashboard/statistics?tenantId={租户ID}&includeChildren=false&statType=day
```
预期:仅返回指定租户的订单统计
### 3. 前端验证
1. 登录系统访问首页
2. 切换不同租户,观察数据变化
3. 切换"包含子租户"开关,验证数据范围
4. 切换统计粒度(周/月/年),验证时间维度
## 编译问题说明
当前环境Java版本为8,项目需要Java 17。请确保:
1. 安装Java 17(推荐OpenJDK 17或Oracle JDK 17)
2. 设置JAVA_HOME环境变量
3. 运行`mvn clean compile -pl zlt-business/order-center -am`
## 核心逻辑流程
```
用户请求统计
↓
获取租户ID(前端传入 or 当前登录用户)
↓
判断是否webApp
├─是→ 获取所有租户
└─否→ 获取当前租户[+子孙租户]
↓
查询租户关联的景区
↓
根据景区ID统计订单
↓
返回统计结果
```
## 日志监控点
关键日志位置:
- `DashboardServiceImpl:89` - webApp统计日志
- `DashboardServiceImpl:95` - 租户景区范围日志
- `DashboardServiceImpl:317` - 本地租户层级获取
- `DashboardServiceImpl:331` - 远程租户层级获取
- `DashboardServiceImpl:340` - 降级处理日志
通过这些日志可以追踪统计范围是否正确。