Commit f68af19e by 林永健

feat(pe-analysis): 重构生态系数计算逻辑

- 添加 StringUtils.isBlank 验证替代 null 检查,增强 DataReportMonthlySnapshotJob 和 DataReportWeeklySnapshotJob 的参数处理
- 新增 EcoCoefficientRuleMapper 接口用于生态系数规则数据访问
- 引入 EcoCoefficientService 服务实现统一的生态系数计算规则管理
- 移除 GoodsCategorySummaryResponse 中的硬编码计算方法,改为调用服务层统一处理
- 更新业务场景分析服务中生态系数计算方式,使用新的服务层接口进行动态计算
- 实现生态系数规则的内存缓存机制,支持按指标编码和数值范围匹配系数
- 添加规则重载功能和日志记录,便于维护和调试生态系数配置
1 parent 24e9d0e1
...@@ -151,158 +151,4 @@ public class GoodsCategorySummaryResponse implements Serializable { ...@@ -151,158 +151,4 @@ public class GoodsCategorySummaryResponse implements Serializable {
@ApiModelProperty(notes = "精品附件-生态系数") @ApiModelProperty(notes = "精品附件-生态系数")
private BigDecimal accessoriesEcoCoefficient; private BigDecimal accessoriesEcoCoefficient;
/**
* 计算生态系数的通用方法
*
* @param penetrationRate 渗透率
* @param thresholds 阈值数组,格式为 [threshold1, coefficient1, threshold2, coefficient2, ...]
* @param defaultCoefficient 默认系数(当渗透率小于最小阈值时)
* @return 计算得到的生态系数
*/
private BigDecimal computeEcoCoefficient(BigDecimal penetrationRate, BigDecimal[] thresholds, BigDecimal defaultCoefficient) {
if (penetrationRate == null) {
return null;
}
// 检查渗透率是否大于等于最大阈值
for (int i = 0; i < thresholds.length; i += 2) {
if (penetrationRate.compareTo(thresholds[i]) >= 0) {
return thresholds[i + 1]; // 返回对应的系数
}
}
// 如果渗透率小于所有阈值,返回默认系数
return defaultCoefficient;
}
/**
* 计算整车延保-生态系数
*
* 按照渗透率,匹配对应的生态系数,详细匹配规则如下:
*/
public void computeVehicleWarrantyEcoCoefficient() {
if (this.vehicleWarrantyPenetrationRate == null) {
return;
}
BigDecimal[] thresholds = {
new BigDecimal("60"), new BigDecimal("1.2"), // x>=0.6:1.2
new BigDecimal("50"), new BigDecimal("1.0"), // 0.5<=x<0.6:1.0
new BigDecimal("45"), new BigDecimal("0.8"), // 0.45<=x<0.5:0.8
new BigDecimal("40"), new BigDecimal("0.6") // 0.4<=x<0.45:0.6
// x<0.4:0
};
this.vehicleWarrantyEcoCoefficient = computeEcoCoefficient(this.vehicleWarrantyPenetrationRate, thresholds, BigDecimal.ZERO);
}
/**
* 计算安心包-生态系数
*/
public void computeSafetyPackageEcoCoefficient() {
if (this.safetyPackagePenetrationRate == null) {
return;
}
BigDecimal[] thresholds = {
new BigDecimal("22"), new BigDecimal("1.2"),
new BigDecimal("17"), new BigDecimal("1.0"),
new BigDecimal("12"), new BigDecimal("0.8"),
new BigDecimal("7"), new BigDecimal("0.6")
};
this.safetyPackageEcoCoefficient = computeEcoCoefficient(this.safetyPackagePenetrationRate, thresholds, BigDecimal.ZERO);
}
/**
* 计算电池延保-生态系数
*/
public void computeBatteryWarrantyEcoCoefficient() {
if (this.batteryWarrantyPenetrationRate == null) {
return;
}
BigDecimal[] thresholds = {
new BigDecimal("16"), new BigDecimal("1.2"),
new BigDecimal("13"), new BigDecimal("1.0"),
new BigDecimal("10"), new BigDecimal("0.8"),
new BigDecimal("7"), new BigDecimal("0.6")
};
this.batteryWarrantyEcoCoefficient = computeEcoCoefficient(this.batteryWarrantyPenetrationRate, thresholds, BigDecimal.ZERO);
}
/**
* 计算轮胎延保-生态系数
*/
public void computeTireWarrantyEcoCoefficient() {
if (this.tireWarrantyPenetrationRate == null) {
return;
}
BigDecimal[] thresholds = {
new BigDecimal("16"), new BigDecimal("1.2"),
new BigDecimal("13"), new BigDecimal("1.0"),
new BigDecimal("10"), new BigDecimal("0.8"),
new BigDecimal("7"), new BigDecimal("0.6")
};
this.tireWarrantyEcoCoefficient = computeEcoCoefficient(this.tireWarrantyPenetrationRate, thresholds, BigDecimal.ZERO);
}
/**
* 计算车窗膜-生态系数
*/
public void computeWindowFilmEcoCoefficient() {
if (this.windowFilmPerCarOutput == null) {
return;
}
BigDecimal[] thresholds = {
new BigDecimal("600"), new BigDecimal("1.2"),
new BigDecimal("500"), new BigDecimal("1.0"),
new BigDecimal("400"), new BigDecimal("0.8"),
new BigDecimal("300"), new BigDecimal("0.6")
};
this.windowFilmEcoCoefficient = computeEcoCoefficient(this.windowFilmPerCarOutput, thresholds, BigDecimal.ZERO);
}
/**
* 计算车身膜-生态系数
*/
public void computeCarBodyFilmEcoCoefficient() {
if (this.carBodyFilmPerCarOutput == null) {
return;
}
BigDecimal[] thresholds = {
new BigDecimal("1200"), new BigDecimal("1.2"),
new BigDecimal("1000"), new BigDecimal("1.0"),
new BigDecimal("700"), new BigDecimal("0.8"),
new BigDecimal("400"), new BigDecimal("0.6")
};
this.carBodyFilmEcoCoefficient = computeEcoCoefficient(this.carBodyFilmPerCarOutput, thresholds, BigDecimal.ZERO);
}
/**
* 计算精品附件-生态系数
*/
public void computeAccessoriesEcoCoefficient() {
if (this.accessoriesPerCarOutput == null) {
return;
}
BigDecimal[] thresholds = {
new BigDecimal("3800"), new BigDecimal("1.2"),
new BigDecimal("3600"), new BigDecimal("1.0"),
new BigDecimal("3400"), new BigDecimal("0.8"),
new BigDecimal("3200"), new BigDecimal("0.6")
};
this.accessoriesEcoCoefficient = computeEcoCoefficient(this.accessoriesPerCarOutput, thresholds, BigDecimal.ZERO);
}
} }
\ No newline at end of file \ No newline at end of file
...@@ -6,6 +6,7 @@ import cn.hutool.core.date.DateUtil; ...@@ -6,6 +6,7 @@ import cn.hutool.core.date.DateUtil;
import com.dangdang.ddframe.job.api.ShardingContext; import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob; import com.dangdang.ddframe.job.api.simple.SimpleJob;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.oreframework.boot.autoconfigure.elasticjob.annotation.ElasticJobConf; import org.oreframework.boot.autoconfigure.elasticjob.annotation.ElasticJobConf;
import org.springframework.core.env.Environment; import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
...@@ -76,7 +77,7 @@ public class DataReportMonthlySnapshotJob implements SimpleJob { ...@@ -76,7 +77,7 @@ public class DataReportMonthlySnapshotJob implements SimpleJob {
* 格式为YYYYMmm(如2026M03),其中mm为两位数的月份 * 格式为YYYYMmm(如2026M03),其中mm为两位数的月份
*/ */
private void buildLastMonthPeriodKey(DataReportGenerateReq req, ShardingContext shardingContext) { private void buildLastMonthPeriodKey(DataReportGenerateReq req, ShardingContext shardingContext) {
Date date = shardingContext != null && shardingContext.getJobParameter() != null Date date = shardingContext != null && StringUtils.isNotBlank(shardingContext.getJobParameter())
? DateUtil.parseDate(shardingContext.getJobParameter()) ? DateUtil.parseDate(shardingContext.getJobParameter())
: DateUtil.lastMonth(); : DateUtil.lastMonth();
......
...@@ -6,6 +6,7 @@ import cn.hutool.core.date.DateUtil; ...@@ -6,6 +6,7 @@ import cn.hutool.core.date.DateUtil;
import com.dangdang.ddframe.job.api.ShardingContext; import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob; import com.dangdang.ddframe.job.api.simple.SimpleJob;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.oreframework.boot.autoconfigure.elasticjob.annotation.ElasticJobConf; import org.oreframework.boot.autoconfigure.elasticjob.annotation.ElasticJobConf;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
...@@ -60,7 +61,7 @@ public class DataReportWeeklySnapshotJob implements SimpleJob { ...@@ -60,7 +61,7 @@ public class DataReportWeeklySnapshotJob implements SimpleJob {
* 使用中国周计算标准(周一为一周的开始),格式为YYYYWww(如2026W12) * 使用中国周计算标准(周一为一周的开始),格式为YYYYWww(如2026W12)
*/ */
private void buildLastWeekPeriodKey(DataReportGenerateReq req, ShardingContext shardingContext) { private void buildLastWeekPeriodKey(DataReportGenerateReq req, ShardingContext shardingContext) {
Date date = shardingContext != null && shardingContext.getJobParameter() != null Date date = shardingContext != null && StringUtils.isNotBlank(shardingContext.getJobParameter())
? DateUtil.parseDate(shardingContext.getJobParameter()) ? DateUtil.parseDate(shardingContext.getJobParameter())
: DateUtil.lastWeek(); : DateUtil.lastWeek();
......
package cn.com.glsx.dj.peanalysis.mapper;
import cn.com.glsx.dj.mindworkplate.model.EcoCoefficientRule;
import org.apache.ibatis.annotations.Mapper;
import org.oreframework.datasource.mybatis.mapper.OreMapper;
/**
* Mapper for eco coefficient rules.
*/
@Mapper
public interface EcoCoefficientRuleMapper extends OreMapper<EcoCoefficientRule> {
}
\ No newline at end of file \ No newline at end of file
...@@ -126,6 +126,9 @@ public class BusinessSceneAnalysisService { ...@@ -126,6 +126,9 @@ public class BusinessSceneAnalysisService {
@Resource @Resource
private MonitoringRemote monitoringRemote; private MonitoringRemote monitoringRemote;
@Resource
private EcoCoefficientService ecoCoefficientService;
/** /**
* 总产值、目标产值、达成率 * 总产值、目标产值、达成率
...@@ -2005,6 +2008,9 @@ public class BusinessSceneAnalysisService { ...@@ -2005,6 +2008,9 @@ public class BusinessSceneAnalysisService {
// //
// } // }
/**
* 处理品类分析指标,并在指标赋值时直接按规则计算生态系数。
*/
public void handlerBusinessData(String code, DataBusinessDTO data, GoodsCategorySummaryResponse res) { public void handlerBusinessData(String code, DataBusinessDTO data, GoodsCategorySummaryResponse res) {
switch (code) { switch (code) {
// 新车交付数 // 新车交付数
...@@ -2018,7 +2024,7 @@ public class BusinessSceneAnalysisService { ...@@ -2018,7 +2024,7 @@ public class BusinessSceneAnalysisService {
case DataStatsConstants.ITEM_CODE_A067: // 整车延保-渗透率 case DataStatsConstants.ITEM_CODE_A067: // 整车延保-渗透率
case DataStatsConstants.ITEM_CODE_A0100: // 整车延保-渗透率 case DataStatsConstants.ITEM_CODE_A0100: // 整车延保-渗透率
res.setVehicleWarrantyPenetrationRate(MetricsValueUtils.toPercentage(data.getItemValue())); res.setVehicleWarrantyPenetrationRate(MetricsValueUtils.toPercentage(data.getItemValue()));
res.computeVehicleWarrantyEcoCoefficient(); // 整车延保-生态系数 res.setVehicleWarrantyEcoCoefficient(ecoCoefficientService.getEcoCoefficient(code, data.getItemValue())); // 整车延保-生态系数
break; break;
case DataStatsConstants.ITEM_CODE_A099: // 整车延保-转化率 case DataStatsConstants.ITEM_CODE_A099: // 整车延保-转化率
res.setVehicleWarrantyConversionRate(MetricsValueUtils.toPercentage(data.getItemValue())); res.setVehicleWarrantyConversionRate(MetricsValueUtils.toPercentage(data.getItemValue()));
...@@ -2030,7 +2036,7 @@ public class BusinessSceneAnalysisService { ...@@ -2030,7 +2036,7 @@ public class BusinessSceneAnalysisService {
case DataStatsConstants.ITEM_CODE_A092: // 安心包-渗透率 case DataStatsConstants.ITEM_CODE_A092: // 安心包-渗透率
case DataStatsConstants.ITEM_CODE_A0101: // 安心包-渗透率 case DataStatsConstants.ITEM_CODE_A0101: // 安心包-渗透率
res.setSafetyPackagePenetrationRate(MetricsValueUtils.toPercentage(data.getItemValue())); res.setSafetyPackagePenetrationRate(MetricsValueUtils.toPercentage(data.getItemValue()));
res.computeSafetyPackageEcoCoefficient(); // 安心包-生态系数 res.setSafetyPackageEcoCoefficient(ecoCoefficientService.getEcoCoefficient(code, data.getItemValue())); // 安心包-生态系数
break; break;
case DataStatsConstants.ITEM_CODE_A089: // 安心包-转化率 case DataStatsConstants.ITEM_CODE_A089: // 安心包-转化率
res.setSafetyPackageConversionRate(MetricsValueUtils.toPercentage(data.getItemValue())); res.setSafetyPackageConversionRate(MetricsValueUtils.toPercentage(data.getItemValue()));
...@@ -2042,7 +2048,7 @@ public class BusinessSceneAnalysisService { ...@@ -2042,7 +2048,7 @@ public class BusinessSceneAnalysisService {
case DataStatsConstants.ITEM_CODE_A094: // 电池延保-渗透率 case DataStatsConstants.ITEM_CODE_A094: // 电池延保-渗透率
case DataStatsConstants.ITEM_CODE_A0103: // 电池延保-渗透率 case DataStatsConstants.ITEM_CODE_A0103: // 电池延保-渗透率
res.setBatteryWarrantyPenetrationRate(MetricsValueUtils.toPercentage(data.getItemValue())); res.setBatteryWarrantyPenetrationRate(MetricsValueUtils.toPercentage(data.getItemValue()));
res.computeBatteryWarrantyEcoCoefficient(); // 电池延保-生态系数 res.setBatteryWarrantyEcoCoefficient(ecoCoefficientService.getEcoCoefficient(code, data.getItemValue())); // 电池延保-生态系数
break; break;
case DataStatsConstants.ITEM_CODE_A091: // 电池延保-转化率 case DataStatsConstants.ITEM_CODE_A091: // 电池延保-转化率
res.setBatteryWarrantyConversionRate(MetricsValueUtils.toPercentage(data.getItemValue())); res.setBatteryWarrantyConversionRate(MetricsValueUtils.toPercentage(data.getItemValue()));
...@@ -2054,7 +2060,7 @@ public class BusinessSceneAnalysisService { ...@@ -2054,7 +2060,7 @@ public class BusinessSceneAnalysisService {
case DataStatsConstants.ITEM_CODE_A093: // 轮胎延保-渗透率 case DataStatsConstants.ITEM_CODE_A093: // 轮胎延保-渗透率
case DataStatsConstants.ITEM_CODE_A0102: // 轮胎延保-渗透率 case DataStatsConstants.ITEM_CODE_A0102: // 轮胎延保-渗透率
res.setTireWarrantyPenetrationRate(MetricsValueUtils.toPercentage(data.getItemValue())); res.setTireWarrantyPenetrationRate(MetricsValueUtils.toPercentage(data.getItemValue()));
// res.computeTireWarrantyEcoCoefficient(); // 轮胎无需计算生态系数 // res.setTireWarrantyEcoCoefficient(ecoCoefficientService.getEcoCoefficient(code, data.getItemValue())); // 轮胎无需计算生态系数
break; break;
case DataStatsConstants.ITEM_CODE_A090: // 轮胎延保-转化率 case DataStatsConstants.ITEM_CODE_A090: // 轮胎延保-转化率
res.setTireWarrantyConversionRate(MetricsValueUtils.toPercentage(data.getItemValue())); res.setTireWarrantyConversionRate(MetricsValueUtils.toPercentage(data.getItemValue()));
...@@ -2145,12 +2151,15 @@ public class BusinessSceneAnalysisService { ...@@ -2145,12 +2151,15 @@ public class BusinessSceneAnalysisService {
// 计算单车采购产值 // 计算单车采购产值
// BigDecimal rate = aggregateType.equals("staffIds") ? BigDecimal.ONE : BigDecimal.valueOf(0.35); // BigDecimal rate = aggregateType.equals("staffIds") ? BigDecimal.ONE : BigDecimal.valueOf(0.35);
res.setCarBodyFilmPerCarOutput(computeSingleVehiclePurchaseOutput(res.getCarBodyFilmPerCarOutput(), res.getNewCarDeliveryCount(), BigDecimal.ONE)); BigDecimal carBodyFilmPerCarOutput = computeSingleVehiclePurchaseOutput(res.getCarBodyFilmPerCarOutput(), res.getNewCarDeliveryCount(), BigDecimal.ONE);
res.setAccessoriesPerCarOutput(computeSingleVehiclePurchaseOutput(res.getAccessoriesPerCarOutput(), res.getNewCarDeliveryCount(), BigDecimal.ONE)); BigDecimal accessoriesPerCarOutput = computeSingleVehiclePurchaseOutput(res.getAccessoriesPerCarOutput(), res.getNewCarDeliveryCount(), BigDecimal.ONE);
res.setWindowFilmPerCarOutput(computeSingleVehiclePurchaseOutput(res.getWindowFilmPerCarOutput(), res.getNewCarDeliveryCount(), BigDecimal.valueOf(0.35))); BigDecimal windowFilmPerCarOutput = computeSingleVehiclePurchaseOutput(res.getWindowFilmPerCarOutput(), res.getNewCarDeliveryCount(), BigDecimal.valueOf(0.35));
res.computeWindowFilmEcoCoefficient(); // 车窗膜-生态系数 res.setCarBodyFilmPerCarOutput(carBodyFilmPerCarOutput);
res.computeCarBodyFilmEcoCoefficient(); // 车身膜-生态系数 res.setAccessoriesPerCarOutput(accessoriesPerCarOutput);
res.computeAccessoriesEcoCoefficient(); // 精品附件-生态系数 res.setWindowFilmPerCarOutput(windowFilmPerCarOutput);
res.setWindowFilmEcoCoefficient(ecoCoefficientService.getEcoCoefficient(DataStatsConstants.ITEM_CODE_A0107, windowFilmPerCarOutput)); // 车窗膜-生态系数
res.setCarBodyFilmEcoCoefficient(ecoCoefficientService.getEcoCoefficient(DataStatsConstants.ITEM_CODE_A0112, carBodyFilmPerCarOutput)); // 车身膜-生态系数
res.setAccessoriesEcoCoefficient(ecoCoefficientService.getEcoCoefficient(DataStatsConstants.ITEM_CODE_A0117, accessoriesPerCarOutput)); // 精品附件-生态系数
// 查询兜底目标(非轻改场景) // 查询兜底目标(非轻改场景)
if (req.getBizs() == 2) { if (req.getBizs() == 2) {
......
package cn.com.glsx.dj.peanalysis.service;
import cn.com.glsx.dj.mindworkplate.model.EcoCoefficientRule;
import cn.com.glsx.dj.peanalysis.mapper.EcoCoefficientRuleMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
/**
* 指标生态系数规则服务。
* <p>
* 负责加载 eco_coefficient_rule 中已启用的规则,并按指标编码、指标值匹配生态系数。
*/
@Slf4j
@Service
public class EcoCoefficientService implements ApplicationListener<ApplicationReadyEvent> {
@Resource
private EcoCoefficientRuleMapper ecoCoefficientRuleMapper;
/**
* 内存缓存,key 为指标编码,value 为该指标下按顺序排好的规则列表。
*/
private final Map<String, List<EcoCoefficientRule>> ruleCache = new ConcurrentHashMap<>();
/**
* 应用启动完成后加载已启用的生态系数规则。
*/
@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
reloadRules();
log.info("指标生态系数规则服务初始化完成");
}
/**
* 重新加载已启用的生态系数规则。
*/
public void reloadRules() {
Example example = new Example(EcoCoefficientRule.class);
example.createCriteria().andEqualTo("enabled", Boolean.TRUE);
List<EcoCoefficientRule> rules = ecoCoefficientRuleMapper.selectByExample(example);
Map<String, List<EcoCoefficientRule>> groupedRules = (rules == null ? Collections.<EcoCoefficientRule>emptyList() : rules)
.stream()
.filter(rule -> StringUtils.isNotBlank(rule.getIndicatorCode()))
.filter(rule -> rule.getCoefficient() != null)
.collect(Collectors.groupingBy(
EcoCoefficientRule::getIndicatorCode,
Collectors.collectingAndThen(Collectors.toList(), this::sortRules)
));
ruleCache.clear();
ruleCache.putAll(groupedRules);
log.info("指标生态系数规则加载完成,规则数:{},指标数:{}",
rules == null ? 0 : rules.size(), groupedRules.size());
}
/**
* 根据指标编码和指标值获取生态系数。
* <p>
* 渗透率类指标请传原始值(0~1),单车产值类指标请传最终换算后的值。
*
* @param indicatorCode 指标编码
* @param metricValue 指标值
* @return 命中时返回生态系数,未命中返回 null
*/
public BigDecimal getEcoCoefficient(String indicatorCode, BigDecimal metricValue) {
if (StringUtils.isBlank(indicatorCode) || metricValue == null) {
return null;
}
List<EcoCoefficientRule> rules = ruleCache.get(indicatorCode);
if (CollectionUtils.isEmpty(rules)) {
log.info("未找到生态系数规则,indicatorCode:{}", indicatorCode);
return null;
}
BigDecimal coefficient = matchRules(rules, metricValue);
if (coefficient != null) {
return coefficient;
}
log.warn("生态系数规则未命中,indicatorCode:{},metricValue:{}", indicatorCode, metricValue);
return null;
}
/**
* 在单个指标规则列表中匹配生态系数。
*/
private BigDecimal matchRules(List<EcoCoefficientRule> rules, BigDecimal metricValue) {
if (metricValue == null) {
return null;
}
for (EcoCoefficientRule rule : rules) {
BigDecimal minValue = rule.getMinPenetration() == null ? BigDecimal.ZERO : rule.getMinPenetration();
BigDecimal maxValue = rule.getMaxPenetration();
boolean match = metricValue.compareTo(minValue) >= 0
&& (maxValue == null || metricValue.compareTo(maxValue) < 0);
if (match) {
log.info("生态系数规则命中,indicatorCode:{},metricValue:{},range:[{}~{}],coefficient:{}",
rule.getIndicatorCode(), metricValue, minValue, maxValue, rule.getCoefficient());
return rule.getCoefficient();
}
}
return null;
}
/**
* 按排序字段和区间下限排序,保证规则匹配顺序稳定。
*/
private List<EcoCoefficientRule> sortRules(List<EcoCoefficientRule> rules) {
return rules.stream()
.sorted(Comparator
.comparing(EcoCoefficientRule::getSortOrder, Comparator.nullsLast(Integer::compareTo))
.thenComparing(EcoCoefficientRule::getMinPenetration, Comparator.nullsFirst(BigDecimal::compareTo)))
.collect(Collectors.toList());
}
}
\ No newline at end of file \ No newline at end of file
  • @wangxw1
    commented
    Master

    一、关键问题与优化建议(Top 3)

    1. 行为变更与潜在的空指针异常(功能正确性)

    • 问题描述:在原 GoodsCategorySummaryResponse 中,计算生态系数未命中阈值时,默认返回的是 BigDecimal.ZERO(例如 computeEcoCoefficient(..., BigDecimal.ZERO))。而在重构后的 EcoCoefficientService.getEcoCoefficient 方法中,如果未命中规则或找不到指标,返回的是 null。
    • 影响分析:这改变了原有的业务逻辑兜底行为。如果下游逻辑(如数值计算、序列化或前端展示)依赖该字段为非空或 0,这种隐式的 null 返回可能会引发 NullPointerException 或数据展示异常。
    • 优化建议:建议在 EcoCoefficientService 中提供默认值兜底,或在 BusinessSceneAnalysisService 调用时进行空值处理,保持与原逻辑一致。 java // 建议在 EcoCoefficientService.getEcoCoefficient 末尾修改为: log.warn("生态系数规则未命中,indicatorCode:{},metricValue:{}", indicatorCode, metricValue); return BigDecimal.ZERO; // 保持与原逻辑一致的默认值

    2. 缓存刷新存在并发安全隐患(稳定性)

    • 问题描述:在 EcoCoefficientService.reloadRules() 方法中,更新内存缓存的代码为 ruleCache.clear(); ruleCache.putAll(groupedRules);。
    • 影响分析:ConcurrentHashMap 虽然本身是线程安全的,但 clear() 和 putAll() 是两个独立的操作,并不具备原子性。如果在 clear() 之后、putAll() 之前有业务请求调用 getEcoCoefficient,会读取到空缓存,导致正常业务匹配失败(返回 null 或默认值)。
    • 优化建议:建议直接替换 Map 的引用,而不是清空再添加。 ```java // 1. 将 ruleCache 声明为 volatile private volatile Map> ruleCache = Collections.emptyMap();

    // 2. 在 reloadRules 中直接替换引用 this.ruleCache = groupedRules;

    
    **3. 高频调用方法中的日志泛滥风险(性能与最佳实践)**
    - **问题描述**:在 `EcoCoefficientService.matchRules()` 方法中,每次规则命中都会打印一条 `log.info` 级别的日志。
    - **影响分析**:该方法属于底层的数据处理逻辑,在批量处理或高并发计算场景下(如定时任务生成报表时),会产生极其庞大的日志量,造成不必要的磁盘 I/O 开销,甚至可能引发性能瓶颈。
    - **优化建议**:将该处的日志级别由 `info` 降级为 `debug`,仅在排查问题时开启。
      ```java
      if (match) {
          log.debug("生态系数规则命中,indicatorCode:{}...", rule.getIndicatorCode()); // 改为 debug
          return rule.getCoefficient();
      }
    

    二、评分明细

    • 功能实现的正确性与健壮性(35/40分): 核心重构逻辑清晰,去除了硬编码,使用了策略化的配置读取。扣分点在于重构过程中忽略了原有的 BigDecimal.ZERO 兜底逻辑,变更为返回 null,存在一定的业务正确性隐患。未发现违反“MyBatis子查询”和“Dubbo接口参数变更”的强制规则。

    • 安全性与潜在风险(30/30分): 代码未引入外部输入直接拼接 SQL、未暴露敏感信息,整体安全性良好,无明显安全漏洞。

    • 最佳实践与可维护性(16/20分): 将领域逻辑从 DTO 剥离到专属 Service 是非常好的工程实践,极大提升了代码的可维护性。扣分点在于缓存更新的非原子性操作(并发读写问题)。

    • 性能与资源利用(4/5分): 使用了内存缓存避免频繁查库,性能设计合理。扣分点在于高频计算循环中的 log.info 可能会造成日志泛滥。

    • 提交信息质量(5/5分): Commit message 格式规范,清晰地描述了重构的目的、具体修改点(如引入 Service、移除硬编码、增加缓存等),非常易于追溯。

    总分:90分

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