Commit c35f36d9 by zhouhaibao

[+]生态预警、兜底预警取值场景权限区分以及周时间计算异常修复

1 parent 86ff6a2e
......@@ -78,6 +78,7 @@ import java.util.stream.Stream;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Lazy;
......@@ -2210,60 +2211,81 @@ public class BusinessAnalysisService {
resp.setMultiCategoryStoreRatio(
calculateRatio(multiCategoryStoreCount, storeList.size(), 2));
// 获取兜底预警门店
// 4. 提取两组 ID (使用优化后的方法,假设 getBiz 返回 Integer)
// 注意:如果 getBiz 返回 String,请将下面的 1, 3 改为 "1", "3" 并修改 extract 方法中的比较逻辑
List<Integer> listIds_2_1 = extractMerchantIdsWithFallback(totalOutputGroupByMerchant, "1", "3");
List<Integer> listIds_1_1 = extractMerchantIdsWithFallback(totalOutputGroupByMerchant, "3");
// ... 多品类计算逻辑不变 ...
// 5. 处理预警逻辑 (日/周/月)
SceneBaseReq sceneBaseReq = new SceneBaseReq();
sceneBaseReq.setTempList(storeList);
sceneBaseReq.setCycleType(4);
/*
sceneBaseReq.setCycleType(request.getCycleType());
*/
// 当日期是日的时候,获取的是本周的生态预警
if (request.getCycleType() == DATE_CYCLE_TYPE){
// 1. 定义格式化器 (根据实际入参格式调整,通常是 yyyy-MM-dd)
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
// 2. 解析输入字符串为 LocalDate
LocalDate inputDate = LocalDate.parse(request.getStartTime(), formatter);
// 3. 计算本周周一 (本周起始)
LocalDate monday = inputDate.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
// 4. 计算本周周日 (本周结束)
LocalDate sunday = inputDate.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));
// 5. 转换为 LocalDateTime 以包含具体时间,确保查询范围完整
// 开始时间:周一 00:00:00
LocalDateTime startDateTime = monday.atStartOfDay();
// 结束时间:周日 23:59:59 (重要:如果数据库查询是 <=,必须包含周日全天)
LocalDateTime endDateTime = sunday.atTime(23, 59, 59);
// 6. 格式化回 String (如果 sceneBaseReq 接收的是 String)
// 如果 sceneBaseReq 的 startTime/endTime 是 Date/LocalDateTime 类型,请直接 set 对象,无需 format
sceneBaseReq.setStartTime(startDateTime.format(formatter));
sceneBaseReq.setEndTime(endDateTime.format(formatter));
}else {
sceneBaseReq.setStartTime(request.getStartTime());
sceneBaseReq.setEndTime(request.getEndTime());
sceneBaseReq.setCycleType(4); // 默认周?根据你的业务逻辑调整
// 定义用于查询的 ID 列表和时间范围
List<Integer> currentBiz2_1Ids;
List<Integer> currentBiz1_1Ids;
String startTime;
String endTime;
if (request.getCycleType() == DATE_CYCLE_TYPE) {
// 【日视图 -> 查本周数据】
String[] weekRange = getWeekRange(request.getEndTime()); // 建议用 endTime 作为基准
startTime = weekRange[0];
endTime = weekRange[1];
// 重新查询本周数据 (注意:这里需要构造一个新的 Request,不要修改原 request)
BaseReq weekRequest = new BaseReq();
BeanUtils.copyProperties(request, weekRequest); // 使用 Spring 工具类复制属性,避免浅拷贝陷阱
weekRequest.setCycleType(4); // 设置为周
weekRequest.setStartTime(startTime);
weekRequest.setEndTime(endTime);
List<DataBusinessDTO> weekData = getOutputGroupByBiz(weekRequest);
currentBiz2_1Ids = extractMerchantIdsWithFallback(weekData, "1", "3");
currentBiz1_1Ids = extractMerchantIdsWithFallback(weekData, "2");
} else {
// 【周/月视图 -> 查当前周期数据】
startTime = request.getStartTime();
endTime = request.getEndTime();
currentBiz2_1Ids = listIds_2_1;
currentBiz1_1Ids = listIds_1_1;
}
// --- 执行统一的预警查询逻辑 ---
sceneBaseReq.setStartTime(startTime);
sceneBaseReq.setEndTime(endTime);
// A. 兜底预警
sceneBaseReq.setMerchantIds(currentBiz2_1Ids);
log.info("[兜底预警] 请求参数 JSON: {}", JSONObject.toJSONString(sceneBaseReq));
List<Integer> backUpStores = businessSceneAnalysisService.findBackUpStores(sceneBaseReq);
log.info("[兜底预警] 响应结果: {}", backUpStores);
resp.setFloorProtectionWarningCount(backUpStores.size());
log.info("兜底预警门店数:{}", backUpStores.size());
// 获取生态预警门店
// B. 生态预警 (延保 + 轻改)
sceneBaseReq.setBizs(1);
List<Integer> ybEcosystemWarningStores = businessSceneAnalysisService.getDelayWarningStore(sceneBaseReq);
log.info("延保生态预警门店数:{}", ybEcosystemWarningStores);
sceneBaseReq.setMerchantIds(currentBiz2_1Ids); // 延保对应 biz 1,3
log.info("[延保生态预警] 请求参数 JSON: {}", JSONObject.toJSONString(sceneBaseReq));
List<Integer> ybStores = businessSceneAnalysisService.getDelayWarningStore(sceneBaseReq);
log.info("[延保生态预警] 响应结果: {}", ybStores);
sceneBaseReq.setBizs(2);
List<Integer> qgEcosystemWarningStores = businessSceneAnalysisService.getDelayWarningStore(sceneBaseReq);
log.info("轻改生态预警门店数:{}", qgEcosystemWarningStores);
sceneBaseReq.setMerchantIds(currentBiz1_1Ids); // 轻改对应 biz 2
log.info("[轻改生态预警] 请求参数 JSON: {}", JSONObject.toJSONString(sceneBaseReq));
List<Integer> qgStores = businessSceneAnalysisService.getDelayWarningStore(sceneBaseReq);
log.info("[轻改生态预警] 响应结果: {}", qgStores);
// 合并去重
List<Integer> ecosystemWarningStores = Stream.of(ybEcosystemWarningStores, qgEcosystemWarningStores)
.flatMap(List::stream)
.distinct() // 或用 toSet()
.collect(Collectors.toList());
long ecosystemCount = Stream.concat(ybStores.stream(), qgStores.stream())
.distinct()
.count();
resp.setEcosystemWarningCount((int) ecosystemCount);
resp.setEcosystemWarningCount(ecosystemWarningStores.size());
// 查询产值达成率
SceneBaseReq sceneBaseReq1 = new SceneBaseReq();
......@@ -2318,6 +2340,20 @@ public class BusinessAnalysisService {
.filter(Objects::nonNull) // 过滤 null 值
.reduce(BigDecimal.ZERO, BigDecimal::add);
List<Integer> storeList1 = currentMonthOutPut.stream()
.map(DataBusinessDTO::getMerchantId)
.filter(Objects::nonNull)
.distinct().collect(Collectors.toList());
// 查询产值达成率
SceneBaseReq sceneBaseReq2 = new SceneBaseReq();
sceneBaseReq2.setMerchantIds(storeList1);
sceneBaseReq2.setStartTime(request.getStartTime());
sceneBaseReq2.setEndTime(request.getEndTime());
sceneBaseReq2.setCycleType(MONTH_CYCLE_TYPE);
Map<String, BigDecimal> stringBigDecimalMap1 = businessSceneAnalysisService.queryStoreTargetOutputList(
sceneBaseReq2);
BigDecimal newtagetOutput = new BigDecimal("0.0");
for (DataBusinessDTO dto : currentMonthOutPut) {
......@@ -2325,7 +2361,7 @@ public class BusinessAnalysisService {
continue;
}
String key = dto.getMerchantId() + "##" + convertToBusinessType(Integer.valueOf(dto.getBiz()));
newtagetOutput = newtagetOutput.add(stringBigDecimalMap.getOrDefault(key, BigDecimal.ZERO)); // ✅ 关键:重新赋值!
newtagetOutput = newtagetOutput.add(stringBigDecimalMap1.getOrDefault(key, BigDecimal.ZERO)); // ✅ 关键:重新赋值!
}
log.info("当月产值{},当月目标:{}",totalOutput,newtagetOutput);
resp.setCurrentAchievementRate(
......@@ -2372,4 +2408,40 @@ public class BusinessAnalysisService {
log.error("不支持的bizs参数: {}", bizs);
return -1;
}
/**
* 从 DTO 列表中提取 MerchantId,按 Biz 过滤,空则返回 [-1]
* @param dataList 源数据
* @param bizValues 允许的 biz 值集合
*/
private List<Integer> extractMerchantIdsWithFallback(List<DataBusinessDTO> dataList, String... bizValues) {
if (dataList == null) return Arrays.asList(-1);
Set<String> targetBizSet = Arrays.stream(bizValues).collect(Collectors.toSet());
List<Integer> ids = dataList.stream()
.filter(dto -> dto.getBiz() != null && targetBizSet.contains(dto.getBiz())) // 假设 getBiz 返回 Integer
.map(DataBusinessDTO::getMerchantId)
.filter(Objects::nonNull)
.distinct() // 这里也可以先去重
.collect(Collectors.toList());
return CollectionUtils.isEmpty(ids) ? Arrays.asList(-1) : ids;
}
/**
* 根据给定日期计算本周的起止时间字符串 (yyyy-MM-dd)
*/
private String[] getWeekRange(String currentDateStr) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate inputDate = LocalDate.parse(currentDateStr, formatter);
LocalDate monday = inputDate.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
LocalDate sunday = inputDate.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));
return new String[] {
monday.format(formatter),
sunday.format(formatter)
};
}
}
  • @wangxw1
    commented
    Master

    你好,我是负责此次代码审查的资深软件开发工程师。

    这段代码主要涉及业务数据分析服务中关于“生态预警”和“产值达成率”的逻辑重构。代码引入了对日视图(Date Cycle)的特殊处理,并封装了部分通用逻辑。整体意图清晰,但存在数据准确性和类型安全方面的严重隐患。

    以下是 Top 3 关键问题与优化建议:

    一、关键问题与优化建议

    1. 日期范围精度丢失,导致数据统计不全(严重)

    • 问题描述: 原代码中显式处理了结束时间为 23:59:59(sunday.atTime(23, 59, 59))。新封装的 getWeekRange 方法仅返回 yyyy-MM-dd 格式的字符串。 如果底层 SQL 查询使用的是 create_time <= #{endTime} 或 BETWEEN 且字段类型为 DATETIME/TIMESTAMP,那么传入 2023-10-22 会被数据库解析为 2023-10-22 00:00:00。这将导致周日全天(00:00:01 至 23:59:59)的数据被遗漏。
    • 影响分析: 业务统计数据严重失真,尤其是“周”维度的预警数据会比实际少一天。
    • 优化建议: 在 getWeekRange 中补全时间部分,或返回 LocalDateTime 由上层处理格式。

      private String[] getWeekRange(String currentDateStr) {
          // ... 前置逻辑不变 ...
          return new String[] {
              monday.atStartOfDay().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")),
              sunday.atTime(23, 59, 59).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
          };
      }
      

    2. extractMerchantIdsWithFallback 存在类型匹配陷阱(高风险)

    • 问题描述: 代码中使用了 Set<String> targetBizSet 来存储传入的 biz 值(如 "1", "3"),但在 Stream filter 中直接调用 targetBizSet.contains(dto.getBiz())。 代码第 2360 行出现了 Integer.valueOf(dto.getBiz()),暗示 dto.getBiz() 可能返回的是 String,也可能是 Integer(自动拆箱/强转)。
      • 如果 dto.getBiz() 返回 Integer,Set<String>.contains(Integer) 永远返回 false,导致列表为空,触发 fallback 返回 [-1]。
      • 如果 dto.getBiz() 返回 String,虽然逻辑成立,但方法内的注释 // 假设 getBiz 返回 Integer 与实际代码逻辑严重冲突,极易误导维护者。
    • 影响分析: 若类型不匹配,所有门店 ID 都会被过滤掉,导致预警查询条件失效(变成查询 ID 为 -1 的门店),业务逻辑静默失败。
    • 优化建议: 统一转为 String 进行比对,确保类型安全。

      // 优化后的 filter 逻辑
      .filter(dto -> dto.getBiz() != null && targetBizSet.contains(String.valueOf(dto.getBiz())))
      

    3. 硬编码与 Magic Number 降低可维护性

    • 问题描述: 代码中大量出现魔术值,如 sceneBaseReq.setCycleType(4)(4 代表周?)、setBizs(1)、setBizs(2) 以及字符串 "1", "3"。 此外,BeanUtils.copyProperties 虽然方便,但在高频调用的业务逻辑中存在一定的性能开销(反射),且属于浅拷贝,容易在修改引用类型字段时产生副作用(虽然此处暂无引用字段修改,但习惯不好)。
    • 影响分析: 代码可读性差,后续如果业务含义变更(例如“周”的类型码变了),需要在多处查找替换,极易出错。
    • 优化建议: 提取常量,并尽量避免在循环或核心路径使用反射拷贝。

      private static final int CYCLE_TYPE_WEEK = 4;
      private static final String BIZ_TYPE_DELAY = "1";
      // ...
      weekRequest.setCycleType(CYCLE_TYPE_WEEK); 
      

    二、评分明细

    维度 评分 理由
    功能正确性 25/40 存在严重的日期边界丢失问题(Issue 1),可能导致周日数据全丢;类型匹配逻辑(Issue 2)存在极大的不确定性风险。
    安全性 28/30 主要是业务逻辑安全。使用 [-1] 作为空列表的 fallback 是常见的防止 SQL 语法错误的做法,虽然不优雅但未造成直接安全漏洞。
    最佳实践 12/20 存在大量 Magic Number;注释与代码实现矛盾(关于 getBiz 返回类型的注释);DateTimeFormatter 建议定义为静态常量而非每次方法调用都创建。
    性能 4/5 整体性能尚可,BeanUtils 在非高并发循环下影响有限,但有优化空间。
    提交信息 5/5 提交信息清晰,涵盖了主要变更点(生态系数、周时间计算修复)。

    总分:74分

Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!