首页统计
This commit is contained in:
@@ -18,7 +18,8 @@
|
||||
"Bash(findstr:*)",
|
||||
"Bash(npm run start:*)",
|
||||
"Bash(npm start)",
|
||||
"Bash(npm run build:*)"
|
||||
"Bash(npm run build:*)",
|
||||
"Bash(dir:*)"
|
||||
],
|
||||
"deny": [],
|
||||
"ask": []
|
||||
|
||||
+16
-11
@@ -34,6 +34,9 @@ public class DashboardController {
|
||||
@Operation(summary = "获取首页统计数据")
|
||||
@GetMapping("/statistics")
|
||||
public Result<DashboardStatisticsVO> getStatistics(
|
||||
@Parameter(description = "租户ID") @RequestParam(required = false) String tenantId,
|
||||
@Parameter(description = "是否包含子租户") @RequestParam(required = false) Boolean includeChildren,
|
||||
@Parameter(description = "统计类型(day/month/year)") @RequestParam(required = false, defaultValue = "day") String statType,
|
||||
@Parameter(description = "景区ID") @RequestParam(required = false) Long tourismId,
|
||||
@Parameter(description = "二维码ID") @RequestParam(required = false) String qrcodeId,
|
||||
@Parameter(description = "设备编号") @RequestParam(required = false) String deviceSn,
|
||||
@@ -42,19 +45,21 @@ public class DashboardController {
|
||||
@Parameter(description = "是否包含测试二维码") @RequestParam(required = false, defaultValue = "false") Boolean includeTestQrcodes) {
|
||||
try {
|
||||
Map<String, Object> params = new HashMap<>();
|
||||
// 追加统计粒度(day/month/year),从请求参数读取
|
||||
// 规范化租户与子租户范围
|
||||
String anchor = tenantId;
|
||||
try {
|
||||
org.springframework.web.context.request.ServletRequestAttributes attrs = (org.springframework.web.context.request.ServletRequestAttributes) org.springframework.web.context.request.RequestContextHolder.getRequestAttributes();
|
||||
jakarta.servlet.http.HttpServletRequest req = attrs != null ? attrs.getRequest() : null;
|
||||
String statType = req != null ? req.getParameter("statType") : null;
|
||||
if (statType != null && !statType.isEmpty()) {
|
||||
params.put("statType", statType);
|
||||
if (anchor == null || anchor.isEmpty()) {
|
||||
anchor = com.central.common.context.TenantQueryOverrideContext.getTenantId();
|
||||
if (anchor == null || anchor.isEmpty()) {
|
||||
anchor = com.central.common.context.LoginUserContextHolder.getCurrentTenantId();
|
||||
}
|
||||
}
|
||||
String incStr = req != null ? req.getParameter("includeChildren") : null;
|
||||
if (incStr != null && !incStr.isEmpty()) {
|
||||
params.put("includeChildren", incStr);
|
||||
}
|
||||
} catch (Exception ignored) {}
|
||||
} catch (Exception ignored) { }
|
||||
boolean withChildren = (includeChildren == null) || Boolean.TRUE.equals(includeChildren);
|
||||
params.put("tenantId", anchor);
|
||||
params.put("includeChildren", withChildren);
|
||||
// 其他筛选参数
|
||||
params.put("statType", statType);
|
||||
params.put("tourismId", tourismId);
|
||||
params.put("qrcodeId", qrcodeId);
|
||||
params.put("deviceSn", deviceSn);
|
||||
|
||||
+3
-1
@@ -32,7 +32,9 @@ public class UserCenterServiceFallbackFactory implements FallbackFactory<UserCen
|
||||
|
||||
@Override
|
||||
public Result<List<String>> getDescendantTenantIds(String tenantId) {
|
||||
return null;
|
||||
log.warn("获取子孙租户失败,降级返回仅当前租户: {}, error: {}", tenantId, cause.getMessage());
|
||||
// 降级策略:返回仅包含当前租户的列表
|
||||
return Result.succeed(java.util.Collections.singletonList(tenantId));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@@ -242,6 +242,10 @@ public interface DashboardMapper {
|
||||
"<if test='p.endTime != null and p.endTime != \"\"'>",
|
||||
" AND o.create_time <= #{p.endTime}",
|
||||
"</if>",
|
||||
"<if test='p.tourismIds != null and p.tourismIds.size > 0'>",
|
||||
" AND o.tourism_id IN",
|
||||
" <foreach collection='p.tourismIds' item='tid' open='(' separator=',' close=')'>#{tid}</foreach>",
|
||||
"</if>",
|
||||
"</script>"
|
||||
})
|
||||
Long getTotalAmount(@Param("p") Map<String, Object> params);
|
||||
@@ -272,6 +276,10 @@ public interface DashboardMapper {
|
||||
"<if test='p.endTime != null and p.endTime != \"\"'>",
|
||||
" AND o.create_time <= #{p.endTime}",
|
||||
"</if>",
|
||||
"<if test='p.tourismIds != null and p.tourismIds.size > 0'>",
|
||||
" AND o.tourism_id IN",
|
||||
" <foreach collection='p.tourismIds' item='tid' open='(' separator=',' close=')'>#{tid}</foreach>",
|
||||
"</if>",
|
||||
"</script>"
|
||||
})
|
||||
Long getRefundAmount(@Param("p") Map<String, Object> params);
|
||||
|
||||
@@ -79,4 +79,10 @@ public interface TourismMapper extends SuperMapper<Tourism> {
|
||||
*/
|
||||
List<Long> findTourismIdsByTenantIds(@Param("tenantIds") List<String> tenantIds);
|
||||
|
||||
/**
|
||||
* 根据租户ID集合,基于二维码表(qrcodes)反查关联的景区ID集合
|
||||
* 适用于景区记录未直接维护 tenant_id,或存在历史数据不一致的情况
|
||||
*/
|
||||
List<Long> findTourismIdsByTenantIdsFromQrcodes(@Param("tenantIds") List<String> tenantIds);
|
||||
|
||||
}
|
||||
|
||||
+144
-11
@@ -30,26 +30,75 @@ public class DashboardServiceImpl implements IDashboardService {
|
||||
private final DashboardMapper dashboardMapper;
|
||||
private final IOrderService orderService;
|
||||
private final TourismMapper tourismMapper;
|
||||
private final TenantResolverService tenantResolverService;
|
||||
|
||||
@Override
|
||||
@IgnoreTenantScope
|
||||
public DashboardStatisticsVO getDashboardStatistics(Map<String, Object> params) {
|
||||
// 依据租户层级组装景区ID集合,作为统计范围(支持 includeChildren=false 仅当前租户)
|
||||
try {
|
||||
// 获取前端传来的tenantId,如果没有则使用当前登录用户的租户
|
||||
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) {
|
||||
String s = String.valueOf(inc);
|
||||
includeChildren = !("false".equalsIgnoreCase(s) || "0".equals(s));
|
||||
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 = resolveTenantIdsFromContext(includeChildren);
|
||||
if (tenantIds != null && !tenantIds.isEmpty()) {
|
||||
// 处理时间维度参数,如果没有传时间范围,根据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;
|
||||
}
|
||||
}
|
||||
|
||||
List<String> tenantIds = tenantResolverService.resolveTenantIds(tenantId, includeChildren);
|
||||
|
||||
// 特殊处理:如果是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);
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
@@ -218,34 +267,118 @@ public class DashboardServiceImpl implements IDashboardService {
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析当前请求上下文的租户集合(包含子租户)
|
||||
* 解析租户ID集合(包含子租户)
|
||||
* @deprecated 已迁移到TenantResolverService
|
||||
*/
|
||||
private List<String> resolveTenantIdsFromContext(boolean includeChildren) {
|
||||
String anchor = TenantQueryOverrideContext.getTenantId();
|
||||
@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);
|
||||
List<String> all = tenantService != null ? tenantService.getAllSubTenantIds(anchor) : null;
|
||||
if (all != null && !all.isEmpty()) return all;
|
||||
} catch (Exception ignored) { }
|
||||
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 方法替代
|
||||
*/
|
||||
@Deprecated
|
||||
private List<String> resolveTenantIdsFromContext(boolean includeChildren) {
|
||||
return tenantResolverService.resolveTenantIds(null, includeChildren);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据租户集合查询景区ID集合
|
||||
*/
|
||||
private List<Long> resolveTourismIdsByTenants(List<String> tenantIds) {
|
||||
try {
|
||||
if (tenantIds == null || tenantIds.isEmpty()) return java.util.Collections.emptyList();
|
||||
return tourismMapper.findTourismIdsByTenantIds(tenantIds);
|
||||
// 先按景区表直接匹配租户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);
|
||||
}
|
||||
return new java.util.ArrayList<>(union);
|
||||
} catch (Exception e) {
|
||||
log.debug("根据租户查询景区失败: {}", e.getMessage());
|
||||
return java.util.Collections.emptyList();
|
||||
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
package com.central.order.service.impl;
|
||||
|
||||
import com.central.common.context.LoginUserContextHolder;
|
||||
import com.central.common.context.TenantQueryOverrideContext;
|
||||
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;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 租户解析服务
|
||||
* 专门处理租户层级关系的获取
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class TenantResolverService {
|
||||
|
||||
private final UserCenterService userCenterService;
|
||||
|
||||
/**
|
||||
* 解析租户ID集合(包含子租户)
|
||||
* @param tenantId 指定的租户ID,null时使用当前上下文
|
||||
* @param includeChildren 是否包含子租户
|
||||
* @return 租户ID列表
|
||||
*/
|
||||
public List<String> resolveTenantIds(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()) {
|
||||
log.warn("无法获取租户ID,返回空列表");
|
||||
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获取子孙租户
|
||||
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");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("获取租户层级失败: {}", e.getMessage(), e);
|
||||
}
|
||||
|
||||
// 降级:只返回当前租户
|
||||
log.warn("获取子孙租户失败,降级为仅当前租户: {}", anchor);
|
||||
return Collections.singletonList(anchor);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取所有租户(用于webApp超级管理员)
|
||||
*/
|
||||
public List<String> getAllTenantIds() {
|
||||
// TODO: 实现获取所有租户的逻辑
|
||||
// 暂时返回空,表示不限制
|
||||
return new ArrayList<>();
|
||||
}
|
||||
}
|
||||
@@ -115,4 +115,19 @@
|
||||
ORDER BY id DESC
|
||||
</select>
|
||||
|
||||
<!-- 基于二维码表按租户反查景区ID(容错方案) -->
|
||||
<select id="findTourismIdsByTenantIdsFromQrcodes" resultType="java.lang.Long">
|
||||
SELECT DISTINCT q.tourism_id
|
||||
FROM qrcodes q
|
||||
WHERE q.is_del = 0
|
||||
AND q.tourism_id IS NOT NULL
|
||||
<if test="tenantIds != null and tenantIds.size > 0">
|
||||
AND q.tenant_id IN
|
||||
<foreach collection="tenantIds" item="tid" open="(" separator="," close=")">
|
||||
#{tid}
|
||||
</foreach>
|
||||
</if>
|
||||
ORDER BY q.tourism_id DESC
|
||||
</select>
|
||||
|
||||
</mapper>
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
# 多租户订单统计功能测试指南
|
||||
|
||||
## 功能概述
|
||||
实现了基于多租户层级的订单统计功能,能够根据当前租户统计自己以及所有子孙租户的订单数据,支持日、月、年三种时间维度。
|
||||
|
||||
## 实现架构
|
||||
|
||||
### 统计逻辑流程
|
||||
1. **租户层级解析**:根据当前租户ID获取所有子孙租户ID列表
|
||||
2. **景区关联查询**:根据租户ID列表查询所有关联的景区
|
||||
3. **订单数据统计**:根据景区ID列表统计相关订单数据
|
||||
|
||||
### 核心文件改动
|
||||
|
||||
#### 后端改动
|
||||
1. **DashboardController.java** (F:\project\go-fly-platform-services\zlt-business\order-center\src\main\java\com\central\order\controller\DashboardController.java:36-56)
|
||||
- 新增参数:`tenantId`(租户ID)、`includeChildren`(是否包含子租户)、`statType`(统计类型:day/month/year)
|
||||
|
||||
2. **DashboardServiceImpl.java** (F:\project\go-fly-platform-services\zlt-business\order-center\src\main\java\com\central\order\service\impl\DashboardServiceImpl.java:36-95)
|
||||
- 实现租户层级解析逻辑
|
||||
- 支持本地服务和远程Feign调用两种方式获取子孙租户
|
||||
- 根据statType自动计算时间范围
|
||||
|
||||
3. **TenantHierarchyController.java** (F:\project\go-fly-platform-services\zlt-business\user-center\src\main\java\com\central\user\controller\TenantHierarchyController.java:159-172)
|
||||
- 提供获取子孙租户ID的REST接口
|
||||
|
||||
#### 前端支持
|
||||
1. **Welcome.tsx** (F:\project\go-fly-platform-services\zlt-web\react-web-next\src\pages\Welcome.tsx)
|
||||
- 已集成租户选择器和时间维度切换组件
|
||||
- 支持按租户和时间维度查询统计数据
|
||||
|
||||
## 测试步骤
|
||||
|
||||
### 1. 准备测试数据
|
||||
|
||||
```sql
|
||||
-- 创建测试租户层级(如果尚未创建)
|
||||
-- 父租户
|
||||
INSERT INTO sys_tenant (tenant_id, tenant_name, parent_tenant_id, tenant_level, tenant_path, status)
|
||||
VALUES ('tenant-001', '总公司', null, 1, 'tenant-001', 1);
|
||||
|
||||
-- 子租户
|
||||
INSERT INTO sys_tenant (tenant_id, tenant_name, parent_tenant_id, tenant_level, tenant_path, status)
|
||||
VALUES ('tenant-002', '分公司A', 'tenant-001', 2, 'tenant-001/tenant-002', 1);
|
||||
|
||||
INSERT INTO sys_tenant (tenant_id, tenant_name, parent_tenant_id, tenant_level, tenant_path, status)
|
||||
VALUES ('tenant-003', '分公司B', 'tenant-001', 2, 'tenant-001/tenant-003', 1);
|
||||
|
||||
-- 孙租户
|
||||
INSERT INTO sys_tenant (tenant_id, tenant_name, parent_tenant_id, tenant_level, tenant_path, status)
|
||||
VALUES ('tenant-004', '办事处A1', 'tenant-002', 3, 'tenant-001/tenant-002/tenant-004', 1);
|
||||
|
||||
-- 创建测试景区
|
||||
INSERT INTO tourisms (id, name, tenant_id, is_del) VALUES
|
||||
(1, '景区1-总公司', 'tenant-001', 0),
|
||||
(2, '景区2-分公司A', 'tenant-002', 0),
|
||||
(3, '景区3-分公司B', 'tenant-003', 0),
|
||||
(4, '景区4-办事处A1', 'tenant-004', 0);
|
||||
|
||||
-- 创建测试订单
|
||||
INSERT INTO orders (tourism_id, order_status, pay_type, create_time, amount) VALUES
|
||||
-- 总公司订单
|
||||
(1, 3, 1, '2025-01-01 10:00:00', 10000),
|
||||
(1, 3, 1, '2025-01-02 10:00:00', 20000),
|
||||
-- 分公司A订单
|
||||
(2, 3, 1, '2025-01-01 11:00:00', 15000),
|
||||
(2, 8, 1, '2025-01-02 11:00:00', 5000), -- 退款订单
|
||||
-- 分公司B订单
|
||||
(3, 3, 1, '2025-01-01 12:00:00', 30000),
|
||||
-- 办事处A1订单
|
||||
(4, 3, 1, '2025-01-01 13:00:00', 8000);
|
||||
```
|
||||
|
||||
### 2. API测试
|
||||
|
||||
#### 测试场景1:查询总公司(含所有子孙)的订单统计
|
||||
```bash
|
||||
curl -X GET "http://localhost:9900/api-order/dashboard/statistics?tenantId=tenant-001&includeChildren=true&statType=day" \
|
||||
-H "Authorization: Bearer {your_token}"
|
||||
```
|
||||
|
||||
预期结果:
|
||||
- 应返回所有4个景区的订单总和
|
||||
- totalOrders: 6
|
||||
- totalAmount: 88000 (分)
|
||||
|
||||
#### 测试场景2:查询分公司A(含子孙)的订单统计
|
||||
```bash
|
||||
curl -X GET "http://localhost:9900/api-order/dashboard/statistics?tenantId=tenant-002&includeChildren=true&statType=day" \
|
||||
-H "Authorization: Bearer {your_token}"
|
||||
```
|
||||
|
||||
预期结果:
|
||||
- 应返回景区2和景区4的订单
|
||||
- totalOrders: 3
|
||||
- totalAmount: 28000 (分)
|
||||
|
||||
#### 测试场景3:查询分公司B(不含子孙)的订单统计
|
||||
```bash
|
||||
curl -X GET "http://localhost:9900/api-order/dashboard/statistics?tenantId=tenant-003&includeChildren=false&statType=day" \
|
||||
-H "Authorization: Bearer {your_token}"
|
||||
```
|
||||
|
||||
预期结果:
|
||||
- 仅返回景区3的订单
|
||||
- totalOrders: 1
|
||||
- totalAmount: 30000 (分)
|
||||
|
||||
#### 测试场景4:按月统计
|
||||
```bash
|
||||
curl -X GET "http://localhost:9900/api-order/dashboard/statistics?tenantId=tenant-001&includeChildren=true&statType=month" \
|
||||
-H "Authorization: Bearer {your_token}"
|
||||
```
|
||||
|
||||
预期结果:
|
||||
- 返回最近12个月的统计数据
|
||||
- 订单趋势按月分组
|
||||
|
||||
#### 测试场景5:按年统计
|
||||
```bash
|
||||
curl -X GET "http://localhost:9900/api-order/dashboard/statistics?tenantId=tenant-001&includeChildren=true&statType=year" \
|
||||
-H "Authorization: Bearer {your_token}"
|
||||
```
|
||||
|
||||
预期结果:
|
||||
- 返回最近5年的统计数据
|
||||
- 订单趋势按年分组
|
||||
|
||||
### 3. 前端界面测试
|
||||
|
||||
1. 登录系统,进入首页
|
||||
2. 在右上角选择不同的租户
|
||||
3. 切换"包含子租户"开关,观察数据变化
|
||||
4. 切换统计粒度(日/月/年),观察图表变化
|
||||
5. 验证数据准确性:
|
||||
- 订单总数是否正确
|
||||
- 金额计算是否准确
|
||||
- 趋势图是否按时间维度正确显示
|
||||
|
||||
### 4. 数据准确性验证SQL
|
||||
|
||||
```sql
|
||||
-- 验证租户001及其子孙的订单总数
|
||||
SELECT COUNT(*) as total_orders, SUM(amount) as total_amount
|
||||
FROM orders o
|
||||
JOIN tourisms t ON o.tourism_id = t.id
|
||||
WHERE t.tenant_id IN (
|
||||
WITH RECURSIVE tenant_tree AS (
|
||||
SELECT tenant_id FROM sys_tenant WHERE tenant_id = 'tenant-001'
|
||||
UNION ALL
|
||||
SELECT st.tenant_id
|
||||
FROM sys_tenant st
|
||||
JOIN tenant_tree tt ON st.parent_tenant_id = tt.tenant_id
|
||||
)
|
||||
SELECT tenant_id FROM tenant_tree
|
||||
)
|
||||
AND o.order_status IN (1, 3, 4, 5, 7, 8, 9)
|
||||
AND (o.pay_type = 1 OR o.pay_type IS NULL);
|
||||
|
||||
-- 按日分组统计
|
||||
SELECT DATE_FORMAT(o.create_time, '%Y-%m-%d') as date,
|
||||
COUNT(*) as order_count,
|
||||
SUM(o.amount) as amount
|
||||
FROM orders o
|
||||
JOIN tourisms t ON o.tourism_id = t.id
|
||||
WHERE t.tenant_id IN ('tenant-001', 'tenant-002', 'tenant-003', 'tenant-004')
|
||||
AND o.order_status IN (1, 3, 4, 5, 7, 8, 9)
|
||||
GROUP BY DATE_FORMAT(o.create_time, '%Y-%m-%d')
|
||||
ORDER BY date;
|
||||
```
|
||||
|
||||
## 注意事项
|
||||
|
||||
1. **性能优化**
|
||||
- 对于大租户树,建议启用应用层缓存租户ID列表
|
||||
- 确保 `tourisms.tenant_id` 和 `orders.tourism_id` 有索引
|
||||
|
||||
2. **权限控制**
|
||||
- 管理端用户(BACKEND)默认可切换租户
|
||||
- C端用户(APP)仅能查看自身租户数据
|
||||
|
||||
3. **故障降级**
|
||||
- 当远程获取租户层级失败时,自动降级为仅查询当前租户
|
||||
|
||||
4. **日志监控**
|
||||
- 关注日志中的 "统计范围" 信息,确认租户和景区范围正确
|
||||
- 如出现 "远程获取租户层级失败" 警告,检查user-center服务状态
|
||||
|
||||
## 常见问题
|
||||
|
||||
### Q1: 统计数据为空?
|
||||
- 检查当前租户是否有关联的景区
|
||||
- 检查景区是否有订单数据
|
||||
- 查看后端日志确认租户ID和景区ID列表
|
||||
|
||||
### Q2: 子租户数据未包含?
|
||||
- 确认 `includeChildren` 参数为 true
|
||||
- 检查 sys_tenant 表中的 parent_tenant_id 关系是否正确
|
||||
- 验证 TenantHierarchyService 是否正确返回子孙租户
|
||||
|
||||
### Q3: 时间维度切换无效?
|
||||
- 确认 `statType` 参数值为 day/month/year 之一
|
||||
- 检查 DashboardMapper 中的 SQL 是否正确处理时间分组
|
||||
|
||||
## 性能测试建议
|
||||
|
||||
1. 模拟大量租户层级(100+ 租户,3-5层深度)
|
||||
2. 每个租户关联 5-10 个景区
|
||||
3. 每个景区生成 1000+ 订单
|
||||
4. 测试不同时间维度的查询响应时间
|
||||
5. 监控数据库查询性能,必要时添加索引
|
||||
|
||||
## 后续优化建议
|
||||
|
||||
1. 添加租户层级缓存机制,减少递归查询
|
||||
2. 实现订单数据预聚合,提升统计查询性能
|
||||
3. 支持更多统计维度(按景区、按设备、按二维码等)
|
||||
4. 添加数据导出功能(Excel/CSV)
|
||||
@@ -0,0 +1,180 @@
|
||||
# 租户层级统计测试方案
|
||||
|
||||
## 修复内容总结
|
||||
|
||||
### 1. 创建专门的租户解析服务
|
||||
- **文件**: `TenantResolverService.java`
|
||||
- **功能**: 专门处理租户层级关系的获取,通过Feign调用user-center服务
|
||||
|
||||
### 2. 修复Feign降级策略
|
||||
- **文件**: `UserCenterServiceFallbackFactory.java`
|
||||
- **修复**: 当远程调用失败时,返回仅包含当前租户的列表,而不是null
|
||||
|
||||
### 3. 优化统计服务
|
||||
- **文件**: `DashboardServiceImpl.java`
|
||||
- **修复**: 使用TenantResolverService统一处理租户解析
|
||||
|
||||
## 测试验证步骤
|
||||
|
||||
### 步骤1: 验证服务间通信
|
||||
|
||||
1. **启动服务**
|
||||
```bash
|
||||
# 启动user-center服务
|
||||
cd zlt-business/user-center
|
||||
mvn spring-boot:run
|
||||
|
||||
# 启动order-center服务
|
||||
cd zlt-business/order-center
|
||||
mvn spring-boot:run
|
||||
```
|
||||
|
||||
2. **查看日志**
|
||||
重点关注以下日志:
|
||||
- `TenantResolverService` - "开始获取租户 xxx 的所有子孙租户"
|
||||
- `TenantResolverService` - "成功获取租户层级: xxx -> n 个租户"
|
||||
- `DashboardServiceImpl` - "统计范围 - 租户IDs: n 个租户, 景区IDs: m 个景区"
|
||||
|
||||
### 步骤2: API测试
|
||||
|
||||
#### 2.1 测试租户层级获取接口
|
||||
```bash
|
||||
# 直接测试user-center的租户层级接口
|
||||
curl -X GET "http://localhost:9900/api-user/tenant/hierarchy/{tenantId}" \
|
||||
-H "Authorization: Bearer {token}"
|
||||
```
|
||||
|
||||
预期返回:
|
||||
```json
|
||||
{
|
||||
"resp_code": 0,
|
||||
"resp_msg": "ok",
|
||||
"datas": ["tenantId", "child1", "child2", "grandchild1"]
|
||||
}
|
||||
```
|
||||
|
||||
#### 2.2 测试订单统计接口(含子租户)
|
||||
```bash
|
||||
curl -X GET "http://localhost:9900/api-order/dashboard/statistics?tenantId={tenantId}&includeChildren=true&statType=day" \
|
||||
-H "Authorization: Bearer {token}"
|
||||
```
|
||||
|
||||
观察日志应包含:
|
||||
- 租户解析过程
|
||||
- 获取到的子孙租户列表
|
||||
- 查询的景区ID列表
|
||||
|
||||
### 步骤3: 数据验证SQL
|
||||
|
||||
```sql
|
||||
-- 1. 查看租户层级关系
|
||||
WITH RECURSIVE tenant_tree AS (
|
||||
SELECT tenant_id, parent_tenant_id, tenant_name, 1 as level
|
||||
FROM sys_tenant
|
||||
WHERE tenant_id = '目标租户ID'
|
||||
|
||||
UNION ALL
|
||||
|
||||
SELECT t.tenant_id, t.parent_tenant_id, t.tenant_name, tt.level + 1
|
||||
FROM sys_tenant t
|
||||
JOIN tenant_tree tt ON t.parent_tenant_id = tt.tenant_id
|
||||
)
|
||||
SELECT * FROM tenant_tree ORDER BY level, tenant_id;
|
||||
|
||||
-- 2. 查看租户关联的景区
|
||||
SELECT
|
||||
st.tenant_id,
|
||||
st.tenant_name,
|
||||
t.id as tourism_id,
|
||||
t.name as tourism_name
|
||||
FROM sys_tenant st
|
||||
LEFT JOIN tourisms t ON st.tenant_id = t.tenant_id
|
||||
WHERE st.tenant_id IN (
|
||||
-- 这里填入上面查询得到的所有租户ID
|
||||
'tenant1', 'tenant2', 'tenant3'
|
||||
);
|
||||
|
||||
-- 3. 验证订单统计
|
||||
SELECT
|
||||
t.tenant_id,
|
||||
COUNT(DISTINCT o.id) as order_count,
|
||||
SUM(o.order_amount) as total_amount
|
||||
FROM orders o
|
||||
JOIN tourisms t ON o.tourism_id = t.id
|
||||
WHERE t.tenant_id IN (
|
||||
-- 这里填入上面查询得到的所有租户ID
|
||||
'tenant1', 'tenant2', 'tenant3'
|
||||
)
|
||||
AND o.order_status IN (1, 3, 4, 5, 7, 8, 9)
|
||||
GROUP BY t.tenant_id;
|
||||
```
|
||||
|
||||
### 步骤4: 前端验证
|
||||
|
||||
1. 登录系统,访问首页
|
||||
2. 选择一个有子租户的父租户
|
||||
3. 确保"包含子租户"开关打开
|
||||
4. 观察统计数据是否包含子租户的订单
|
||||
|
||||
### 步骤5: 问题排查
|
||||
|
||||
如果子租户数据仍然未被统计,检查:
|
||||
|
||||
1. **网络通信**
|
||||
- order-center能否访问user-center服务
|
||||
- 检查服务注册中心(如Nacos)中服务是否正常注册
|
||||
|
||||
2. **日志分析**
|
||||
```bash
|
||||
# 查看order-center日志
|
||||
tail -f logs/order-center.log | grep -E "TenantResolver|租户"
|
||||
|
||||
# 查看user-center日志
|
||||
tail -f logs/user-center.log | grep -E "TenantHierarchy|租户"
|
||||
```
|
||||
|
||||
3. **Feign配置**
|
||||
检查`application.yml`中Feign超时配置:
|
||||
```yaml
|
||||
feign:
|
||||
client:
|
||||
config:
|
||||
default:
|
||||
connectTimeout: 5000
|
||||
readTimeout: 10000
|
||||
```
|
||||
|
||||
4. **数据完整性**
|
||||
- 确认sys_tenant表中parent_tenant_id关系正确
|
||||
- 确认tourisms表中tenant_id字段有值
|
||||
- 确认orders表中tourism_id关联正确
|
||||
|
||||
## 期望结果
|
||||
|
||||
1. 选择父租户时,统计数据应包含:
|
||||
- 父租户自身的订单
|
||||
- 所有子租户的订单
|
||||
- 所有孙租户的订单
|
||||
|
||||
2. 日志中应显示:
|
||||
- 正确的租户ID列表
|
||||
- 正确的景区ID列表
|
||||
- SQL查询包含正确的IN条件
|
||||
|
||||
3. 前端界面:
|
||||
- 订单数 = 父租户订单 + 所有子孙租户订单
|
||||
- 金额 = 父租户金额 + 所有子孙租户金额
|
||||
|
||||
## 常见问题
|
||||
|
||||
### Q: Feign调用超时
|
||||
A: 增加超时时间或检查网络连接
|
||||
|
||||
### Q: 获取不到子租户
|
||||
A: 检查sys_tenant表的parent_tenant_id字段是否正确
|
||||
|
||||
### Q: 统计数据为0
|
||||
A: 检查景区是否关联了正确的tenant_id
|
||||
|
||||
### Q: webApp看不到所有数据
|
||||
A: webApp应该返回空的tenantIds列表,让SQL不加租户过滤
|
||||
@@ -82,7 +82,7 @@ const Welcome: React.FC = () => {
|
||||
<span>统计粒度</span>
|
||||
<Segmented
|
||||
options={[
|
||||
{ label: '日', value: 'day' },
|
||||
{ label: '周', value: 'day' },
|
||||
{ label: '月', value: 'month' },
|
||||
{ label: '年', value: 'year' },
|
||||
]}
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
# 多租户订单统计修复验证说明
|
||||
|
||||
## 问题修复清单
|
||||
|
||||
### 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` - 降级处理日志
|
||||
|
||||
通过这些日志可以追踪统计范围是否正确。
|
||||
Reference in New Issue
Block a user