Commit 104a6325 by 林永健

feat(analysis): 优化产值趋势查询与门店权限过滤逻辑

- 在BusinessSceneAnalysisController中调整MerchantFilter参数,支持控制是否查询产值统计数据
- BusinessSceneAnalysisController中新增对门店列表的产值过滤调用,完善权限过滤流程
- LoginService新增filterOutputMerchant方法,实现根据产值数据过滤门店权限
- LoginService新增辅助方法mergeRequestMerchant和convertDateType,辅助权限和周期类型处理
- SceneBaseRequest支持getMerchantFilter重载,允许传入查询产值统计开关参数
- BusinessSceneAnalysisService中trendOutput方法重构为基于时间区间分段并行查询指标数据
- BusinessSceneAnalysisService利用GetDataStatsService新增parallelCallTimeListMap方法,提升多时间段指标查询性能
- trendOutput中新增月度达成率按月多门店查询逻辑,实现多目标产值数据汇总和达成率计算
- 优化日志输出,增加关键查询时间和数据指标日志,提升监控和调试能力
1 parent d44f3796
...@@ -313,93 +313,55 @@ public class BusinessSceneAnalysisService { ...@@ -313,93 +313,55 @@ public class BusinessSceneAnalysisService {
*/ */
public List<TrendOutputResponse> trendOutput(SceneBaseReq req) { public List<TrendOutputResponse> trendOutput(SceneBaseReq req) {
List<TrendOutputResponse> res; List<TrendOutputResponse> res;
boolean isMonth = req.getCycleType() == 3 && req.isWithTargetRatio();
List<DataBusinessDTO> trendOutputList = new ArrayList<>(); // 根据周期类型处理时间显示格式
Map<Date, BigDecimal> monthTargetOutputMap = new HashMap<>(); DateField dateUnit = DateUtils.getHutoolDateUnit(req.getCycleType());
Date startTime = DateUtils.getStartTimeWithCycleType(DateUtil.parseDate(req.getStartTime()), req.getCycleType());
Date endTime = DateUtils.getEndTimeWithCycleType(DateUtil.parseDate(req.getEndTime()), req.getCycleType());
List<DateTime> dateRange = DateUtil.rangeToList(startTime, endTime, dateUnit);
List<Pair<String, String>> datePairRange = dateRange.stream()
.map(p -> Pair.of(DateUtil.formatDate(p), DateUtil.formatDate(DateUtils.getEndTimeWithCycleType(p, req.getCycleType()))))
.collect(Collectors.toList());
log.info("查询时间段: {}", datePairRange);
// 分时段查询指标
Map<Pair<String, String>, List<DataBusinessDTO>> datePairDataMap = new HashMap<>();
try { try {
req.setMerchantIds(getMerchantIdPermission(req, false)); req.setMerchantIds(getMerchantIdPermission(req, false));
// 查询指标数据 // 查询指标数据
DataBizQueryParamsDTO queryParams = req.convertQueryParam(); DataBizQueryParamsDTO queryParams = req.convertQueryParam();
queryParams.setBrandIds(dataStatsConfig.defaultBrandId);
// 自定义的周期,在进行指标查询趋势图时,需要改为按日周期去查 // 自定义的周期,在进行指标查询趋势图时,需要改为按日周期去查
if (queryParams.getDateType() == 4) { if (queryParams.getDateType() == 4) {
queryParams.setDateType(0); queryParams.setDateType(0);
} }
queryParams.setBrandIds(dataStatsConfig.defaultBrandId);
if (CollectionUtils.isEmpty(req.getItemCodeList())) { if (CollectionUtils.isEmpty(req.getItemCodeList())) {
queryParams.setItemCodes(DataStatsConstants.ITEM_CODE_A036); queryParams.setItemCodes(DataStatsConstants.ITEM_CODE_A036);
}else { }else {
// 暂时只处理一个指标 // 暂时只处理一个指标
queryParams.setItemCodes(req.getItemCodeList().get(0)); queryParams.setItemCodes(req.getItemCodeList().get(0));
} }
trendOutputList = businessAnalysisService.getTotalOutputGroupByMerchant(queryParams); if (isMonth) {
if (CollectionUtils.isEmpty(trendOutputList)) { // 按月统计,需要查询达成率,要每个月的权限门店
log.warn("查询产值趋势及达成率返回空"); queryParams.setExts("merchantIds");
}
// 查询目标产值(周期=月时才展示)
if (queryParams.getDateType() == 2 && req.isWithTargetRatio()) {
byte businessType = req.convertToBusinessType(queryParams.getBizs());
RpcPagination<MerchantOutputTargetConfigDTO> pagination = new RpcPagination<>();
pagination.setPageSize(Integer.MAX_VALUE);
pagination.setPageNum(1);
MerchantOutputTargetConfigDTO condition = new MerchantOutputTargetConfigDTO();
condition.setMerchantIdList(req.getMerchantIds());
condition.setBusinessType(businessType);
pagination.setCondition(condition);
Date startDate = DateUtil.parseDate(queryParams.getStartDate());
Date endDate = DateUtil.parseDate(queryParams.getEndDate());
DateUtil.rangeToList(startDate, endDate, DateField.MONTH).forEach(begin -> {
String targetMonth = DateUtil.format(begin, DatePattern.NORM_MONTH_PATTERN);
condition.setTargetMonth(targetMonth);
RpcResponse<RpcPagination<MerchantOutputTargetConfigDTO>> outputTargetConfigResp = merchantOutputTargetConfigRemote.listWithPage(pagination);
if (outputTargetConfigResp.isFailed() || outputTargetConfigResp.getResult() == null) {
log.error("获取目标产值失败, pagination: {}", pagination);
return;
}
BigDecimal targetMonthValue = outputTargetConfigResp.getResult().getList().stream()
.map(MerchantOutputTargetConfig::getTargetValue)
.filter(Objects::nonNull)
.reduce(BigDecimal.ZERO, BigDecimal::add);
monthTargetOutputMap.put(DateUtil.parse(targetMonth, DatePattern.NORM_MONTH_PATTERN), targetMonthValue);
});
log.info("查询目标产值:{}", monthTargetOutputMap);
} }
datePairDataMap.putAll(getDataStatsService.parallelCallTimeListMap(datePairRange, queryParams));
}catch (Exception e){ }catch (Exception e){
log.error("获取门店产值权限失败,构建默认趋势图", e); log.error("获取门店产值权限失败,构建默认趋势图", e);
} }
// 构建响应结果
Map<Date, List<DataBusinessDTO>> dataGroupByStart = trendOutputList.stream().collect(Collectors.groupingBy(p -> DateUtil.parseDate(p.getStartDate())));
// 根据周期类型处理时间显示格式
DateField dateUnit = DateUtils.getHutoolDateUnit(req.getCycleType());
Date startTime = DateUtils.getStartTimeWithCycleType(DateUtil.parseDate(req.getStartTime()), req.getCycleType());
Date endTime = DateUtils.getEndTimeWithCycleType(DateUtil.parseDate(req.getEndTime()), req.getCycleType());
List<DateTime> dateRange = DateUtil.rangeToList(startTime, endTime, dateUnit);
int range = dateRange.size(); int range = dateRange.size();
res = dateRange.stream().map(begin -> { res = dateRange.stream().map(beginTime -> {
String begin = DateUtil.formatDate(beginTime);
String end = DateUtil.formatDate(DateUtils.getEndTimeWithCycleType(beginTime, req.getCycleType()));
TrendOutputResponse item = new TrendOutputResponse(); TrendOutputResponse item = new TrendOutputResponse();
if (dataGroupByStart.containsKey(begin)) {
List<DataBusinessDTO> dateList = dataGroupByStart.get(begin);
DataBusinessDTO data = mergeDataList(dateList);
item.setStoreCount(BigDecimal.valueOf(dateList.size()));
item.setOutput(ObjectUtil.defaultIfNull(scaleItemValue(data.getItemValue()), BigDecimal.ZERO));
item.setStartTime(data.getStartDate());
item.setEndTime(data.getEndDate());
Date key = DateUtil.parse(item.getStartTime());
BigDecimal ratio = null;
if (monthTargetOutputMap.containsKey(key)) {
ratio = computeOutputRatio(item.getOutput(), monthTargetOutputMap.get(key));
}
item.setRatio(ObjectUtil.defaultIfNull(ratio, BigDecimal.ZERO));
} else {
item.setOutput(BigDecimal.ZERO); item.setOutput(BigDecimal.ZERO);
item.setStoreCount(BigDecimal.ZERO); item.setStoreCount(BigDecimal.ZERO);
item.setRatio(BigDecimal.ZERO); item.setRatio(BigDecimal.ZERO);
item.setStartTime(DateUtil.formatDate(begin)); item.setStartTime(begin);
item.setEndTime(DateUtil.formatDate(DateUtils.getEndTimeWithCycleType(begin, req.getCycleType()))); item.setEndTime(end);
}
switch (req.getCycleType()) { switch (req.getCycleType()) {
case 1: // 按日 case 1: // 按日
case 4: // 自定义 case 4: // 自定义
...@@ -414,6 +376,26 @@ public class BusinessSceneAnalysisService { ...@@ -414,6 +376,26 @@ public class BusinessSceneAnalysisService {
item.setTime(th == 0 ? "当前周" : "前" + th + "周"); item.setTime(th == 0 ? "当前周" : "前" + th + "周");
break; break;
} }
Pair<String, String> key = Pair.of(begin, end);
if (!datePairDataMap.containsKey(key)) {
return item;
}
List<DataBusinessDTO> dataList = datePairDataMap.get(key);
List<Integer> merchantIds = dataList.stream().map(p -> p.getMerchantId()).collect(Collectors.toList());
DataBusinessDTO data = mergeDataList(dataList);
item.setOutput(data.getItemValue());
// 计算达成率,根据产值门店查询目标值
if (isMonth) {
SceneBaseReq pairReq = new SceneBaseReq();
BeanUtils.copyProperties(req, pairReq);
pairReq.setMerchantIds(merchantIds);
BigDecimal pairTargetOutput = queryStoreTargetOutput(pairReq).values().stream().reduce(BigDecimal.ZERO, BigDecimal::add);
log.info("查询时间段: {}, 门店: {}, 累计: {}, 目标产值:{}", key, dataList, data, pairTargetOutput);
item.setRatio(computeOutputRatio(item.getOutput(), pairTargetOutput));
}
return item; return item;
}).collect(Collectors.toList()); }).collect(Collectors.toList());
log.info("查询产值趋势及达成率:{}", res); log.info("查询产值趋势及达成率:{}", res);
......
...@@ -220,5 +220,42 @@ public class GetDataStatsService { ...@@ -220,5 +220,42 @@ public class GetDataStatsService {
return resultMap; return resultMap;
} }
public Map<Pair<String, String>, List<DataBusinessDTO>> parallelCallTimeListMap(List<Pair<String, String>> dateList, DataBizQueryParamsDTO queryDataBiz) {
Map<Pair<String, String>, List<DataBusinessDTO>> resultMap = new ConcurrentHashMap<>();
List<CompletableFuture<Void>> futures = new ArrayList<>();
for (Pair<String, String> dateItem : dateList) {
DataBizQueryParamsDTO queryCopy = new DataBizQueryParamsDTO();
BeanUtil.copyProperties(queryDataBiz, queryCopy);
queryCopy.setStartDate(dateItem.getKey());
queryCopy.setEndDate(dateItem.getValue());
String jsonBody = JSONUtil.toJsonStr(queryCopy);
futures.add(CompletableFuture.runAsync(() -> {
try {
DataResp<List<DataBusinessDTO>> dataResp = this.getListDataResp(jsonBody);
List<DataBusinessDTO> content = dataResp.getContent();
if (CollUtil.isEmpty(content)) {
log.info("dateItem:{}, dataResp:{}", dateItem, JSONUtil.toJsonPrettyStr(dataResp));
return;
}
resultMap.put(dateItem, content);
} catch (Exception e) {
log.error("Error processing itemCode: {}, cause: {}", dateItem, ExceptionUtils.getStackTrace(e));
resultMap.put(dateItem, null);
}
}, taskExecutor));
}
// 等待所有任务完成
try {
CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).get();
} catch (Exception e) {
log.error("Parallel call interrupted", e);
Thread.currentThread().interrupt();
}
return resultMap;
}
} }
  • @wangxw1
    commented
    Master

    Auto Review Result:

    代码审查报告

    问题描述和优化建议

    1. 功能实现的正确性与健壮性(40分)

    • 问题:BusinessSceneAnalysisService 中 trendOutput 方法重构后,部分逻辑处理不够清晰,特别是月度达成率的计算和数据合并部分。
    • 影响:可能会影响达成率计算的准确性,导致业务逻辑不清晰。
    • 建议:进一步拆分复杂逻辑,增加单元测试覆盖,确保每个子逻辑的正确性。

    2. 安全性与潜在风险(30分)

    • 问题:在 parallelCallTimeListMap 方法中,如果某个时间段的数据查询失败,会将该时间段的结果设置为 null。这可能导致后续处理逻辑出现问题。
    • 影响:可能会抛出 NullPointerException,影响程序稳定性。
    • 建议:在 parallelCallTimeListMap 方法中,将失败的时间段的结果初始化为空列表,而不是 null,并在后续处理中统一处理。

    3. 是否符合最佳实践(20分)

    • 问题:parallelCallTimeListMap 方法中,使用了 CompletableFuture 进行并行处理,但没有设置超时机制,可能导致线程池被耗尽。
    • 影响:长时间运行的任务可能会导致系统资源耗尽,影响系统性能。
    • 建议:为 CompletableFuture.runAsync 添加超时机制,确保任务在合理时间内完成。

    4. 性能与资源利用效率(5分)

    • 问题:parallelCallTimeListMap 方法中,使用了 ConcurrentHashMap 来存储结果,但在某些情况下,这可能会导致锁竞争,降低性能。
    • 影响:在高并发情况下,可能会出现性能瓶颈。
    • 建议:考虑使用 Collections.synchronizedMap 或其他并发友好型的数据结构来替代 ConcurrentHashMap,或者优化并发访问模式。

    5. Commits信息的清晰性与准确性(5分)

    • 问题:提交信息详细描述了改动内容,但没有明确指出具体的代码变更位置和变更的原因。
    • 影响:对于后续维护者来说,难以快速定位到具体的代码变更。
    • 建议:在提交信息中增加具体的代码变更位置和变更的原因,以便更好地理解和维护代码。

    评分明细

    1. 功能实现的正确性与健壮性:35分
    2. 安全性与潜在风险:25分
    3. 是否符合最佳实践:15分
    4. 性能与资源利用效率:4分
    5. Commits信息的清晰性与准确性:4分

    总分

    总分:83分


    通过以上审查,代码整体上进行了有效的重构和优化,提高了性能和可维护性,但仍有一些细节需要注意和改进。希望这些反馈能够帮助提升代码质量。

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