Commit 76b7419b by 崔彦峰

refactor(goods): 重构商品列表提交服务中的依赖注入和虚拟库存验证逻辑

- 将远程服务依赖从具体类改为统一的包导入
- 新增MerchantPackageGoodsInfoRemote用于虚拟库存检查
- 注释掉包相关商品索引集合的收集逻辑
- 移除销售占比强校验的注释说明
- 添加虚拟库存验证方法validateVirtualInventoryStock
- 在两个关键位置调用虚拟库存验证
- 重构收益计算逻辑,使用人员成本率替代复杂计算
- 添加解析升级商品ID的辅助方法
1 parent 5436f5c3
......@@ -18,17 +18,14 @@ import cn.com.glsx.dj.smartcarlife.dto.goods.UpgradeGoodsAreaDTO;
import cn.com.glsx.dj.smartcarlife.dto.merchant.MerchantDetailBatchQueryDTO;
import cn.com.glsx.dj.smartcarlife.dto.merchant.MerchantDetailResponseDTO;
import cn.com.glsx.dj.smartcarlife.dto.merchant.MerchantInfoDTO;
import cn.com.glsx.dj.smartcarlife.dto.merchant.ProductDetailDTO;
import cn.com.glsx.dj.smartcarlife.dto.stock.StockCheckDTO;
import cn.com.glsx.dj.smartcarlife.enums.*;
import cn.com.glsx.dj.smartcarlife.enums.CarLifeEnum.DivisionType;
import cn.com.glsx.dj.smartcarlife.enums.CarLifeEnum.PositionEnum;
import cn.com.glsx.dj.smartcarlife.enums.createBusinessApprove.MerchantDivideTypeEnum;
import cn.com.glsx.dj.smartcarlife.enums.vd.OperationModeEnum;
import cn.com.glsx.dj.smartcarlife.model.YqMerchantServiceDetails;
import cn.com.glsx.dj.smartcarlife.remote.MerchantSettleDistributeRuleRemote;
import cn.com.glsx.dj.smartcarlife.remote.MerchantStoreInfoRemote;
import cn.com.glsx.dj.smartcarlife.remote.PaymentChannelRemote;
import cn.com.glsx.dj.smartcarlife.remote.UpgradeGoodsRemote;
import cn.com.glsx.dj.smartcarlife.remote.*;
import cn.com.glsx.dj.smartcarlife.util.FileUtils;
import cn.com.glsx.dj.smartcarlife.vo.excel.ExcelImportProgressVo;
import cn.com.glsx.framework.core.beans.rpc.RpcPagination;
......@@ -115,6 +112,8 @@ public class GoodsListingSubmitService {
private MerchantSettleDistributeRuleRemote merchantSettleDistributeRuleRemote;
@Autowired
private MerchantStoreInfoRemote merchantStoreInfoRemote;
@Autowired
private MerchantPackageGoodsInfoRemote merchantPackageGoodsInfoRemote;
public String save(GoodsListingSubmitDTO submitDTO) {
validateSubmitRequest(submitDTO);
......@@ -776,7 +775,7 @@ public class GoodsListingSubmitService {
}
List<List<Integer>> packageGoodsIndexList = globalContext.getPackageGoodsIndexList();
Set<Integer> packageRelatedGoodsIndexSet = collectPackageRelatedGoodsIndexSet(packageGoodsIndexList);
// Set<Integer> packageRelatedGoodsIndexSet = collectPackageRelatedGoodsIndexSet(packageGoodsIndexList);
Map<Integer, Integer> baseLeaderIndexMap = buildBaseLeaderIndexMap(list, packageGoodsIndexList);
Map<Integer, UpgradeGoodsDTO> legalGoodsIndexMap = new LinkedHashMap<>();
......@@ -842,7 +841,6 @@ public class GoodsListingSubmitService {
if (parseSettlementType(settlementTypeText) == null) {
setLineError(errorList, "结算方式不合法", i);
}
// 销售占比不再做强校验,保留字段但不拦截提交。
if (parseInventoryType(row.getInventoryMode()) == null) {
setLineError(errorList, "库存模式不合法", i);
}
......@@ -880,6 +878,7 @@ public class GoodsListingSubmitService {
}
validatePackageRules(submitDTO, list, legalGoodsIndexMap, errorList);
validateVirtualInventoryStock(submitDTO, legalGoodsIndexMap);
globalContext.setLegalGoodsIndexMap(legalGoodsIndexMap);
......@@ -1023,6 +1022,7 @@ public class GoodsListingSubmitService {
}
validatePackageRules(submitDTO, list, legalGoodsIndexMap, errorList);
validateVirtualInventoryStock(submitDTO, legalGoodsIndexMap);
globalContext.setLegalGoodsIndexMap(legalGoodsIndexMap);
......@@ -1634,6 +1634,113 @@ public class GoodsListingSubmitService {
}
}
private void validateVirtualInventoryStock(GoodsListingSubmitDTO submitDTO,
Map<Integer, UpgradeGoodsDTO> legalGoodsIndexMap) {
if (submitDTO == null || submitDTO.getGlobalContext() == null || MapUtil.isEmpty(legalGoodsIndexMap)) {
return;
}
List<CreateBusinessApproveMerchantDTO> merchantList = Optional.ofNullable(submitDTO.getMerchantList()).orElse(new ArrayList<>());
if (CollectionUtils.isEmpty(merchantList)) {
return;
}
List<CreateBusinessApproveAllImportVo> list = submitDTO.getGlobalContext().getList();
if (CollectionUtils.isEmpty(list)) {
return;
}
List<Integer> virtualGoodsIdList = new ArrayList<>();
Map<Integer, List<Integer>> goodsRowIndexMap = new LinkedHashMap<>();
for (Map.Entry<Integer, UpgradeGoodsDTO> entry : legalGoodsIndexMap.entrySet()) {
Integer rowIndex = entry.getKey();
if (rowIndex == null || rowIndex < 0 || rowIndex >= list.size()) {
continue;
}
CreateBusinessApproveAllImportVo row = list.get(rowIndex);
Byte inventoryType = parseInventoryType(row == null ? null : row.getInventoryMode());
if (!Objects.equals(inventoryType, (byte) 1)) {
continue;
}
Integer upgradeGoodsId = resolveUpgradeGoodsId(entry.getValue(), row);
if (upgradeGoodsId == null) {
continue;
}
goodsRowIndexMap.computeIfAbsent(upgradeGoodsId, key -> new ArrayList<>()).add(rowIndex);
if (!virtualGoodsIdList.contains(upgradeGoodsId)) {
virtualGoodsIdList.add(upgradeGoodsId);
}
}
if (CollectionUtils.isEmpty(virtualGoodsIdList)) {
return;
}
Set<Integer> merchantIdSet = merchantList.stream()
.map(CreateBusinessApproveMerchantDTO::getMerchantId)
.filter(Objects::nonNull)
.collect(Collectors.toCollection(LinkedHashSet::new));
if (CollectionUtils.isEmpty(merchantIdSet)) {
return;
}
List<StockCheckDTO> requestList = merchantIdSet.stream().map(merchantId -> {
StockCheckDTO dto = new StockCheckDTO();
dto.setMerchantId(merchantId);
dto.setUpgradeGoodsIdList(new ArrayList<>(virtualGoodsIdList));
return dto;
}).collect(Collectors.toList());
RpcResponse<List<StockCheckDTO>> response;
try {
response = merchantPackageGoodsInfoRemote.batchCheckStock(requestList);
} catch (Exception e) {
log.error("批量校验虚拟库存失败, merchantIds={}, upgradeGoodsIds={}, error={}",
merchantIdSet, virtualGoodsIdList, e.getMessage(), e);
throw new RpcServiceException(DefaultErrorEnum.SERVICE_ERROR, "校验虚拟库存失败");
}
if (response == null || !response.hasResult()) {
throw new RpcServiceException(DefaultErrorEnum.SERVICE_ERROR, "校验虚拟库存失败");
}
List<StockCheckDTO> stockCheckList = Optional.ofNullable(response.getResult()).orElse(Collections.emptyList());
if (CollectionUtils.isEmpty(stockCheckList)) {
return;
}
Set<Integer> errorRowIndexSet = new HashSet<>();
for (StockCheckDTO stockCheckDTO : stockCheckList) {
if (stockCheckDTO == null || CollectionUtils.isEmpty(stockCheckDTO.getUpgradeGoodsIdList())) {
continue;
}
for (Integer upgradeGoodsId : stockCheckDTO.getUpgradeGoodsIdList()) {
List<Integer> rowIndexList = goodsRowIndexMap.get(upgradeGoodsId);
if (CollectionUtils.isEmpty(rowIndexList)) {
continue;
}
for (Integer rowIndex : rowIndexList) {
if (rowIndex != null && errorRowIndexSet.add(rowIndex)) {
setLineError(submitDTO.getGlobalContext().getErrorList(), "不能设置为虚拟库存", rowIndex);
}
}
}
}
}
private Integer resolveUpgradeGoodsId(UpgradeGoodsDTO upgradeGoodsDTO, CreateBusinessApproveAllImportVo row) {
Integer upgradeGoodsId = Optional.ofNullable(upgradeGoodsDTO).map(UpgradeGoodsDTO::getUpgradeGoodsId).orElse(null);
if (upgradeGoodsId != null) {
return upgradeGoodsId;
}
upgradeGoodsId = Optional.ofNullable(upgradeGoodsDTO).map(UpgradeGoodsDTO::getId).orElse(null);
if (upgradeGoodsId != null) {
return upgradeGoodsId;
}
return parseInteger(row == null ? null : row.getUpgradeCommodityCode());
}
private void validatePartner2MerchantInfoWhenSelected(GoodsListingSubmitDTO submitDTO,
List<CreateBusinessApproveAllImportVo> list) {
if (CollectionUtils.isEmpty(list) || !hasPartner2SettleTarget(submitDTO, list)) {
......@@ -2912,7 +3019,7 @@ public class GoodsListingSubmitService {
Integer merchantId = merchantIter.next();
count++;
MerchantDetailResponseDTO data = merchantInfoDTOMap.get(merchantId);
BigDecimal estimatedRevenueTotal = BigDecimal.ZERO;
/*BigDecimal estimatedRevenueTotal = BigDecimal.ZERO;
if(CollectionUtils.isNotEmpty(data.getProductDetails())){
estimatedRevenueTotal = data.getProductDetails().stream()
.map(ProductDetailDTO::getEstimatedRevenue)
......@@ -2927,7 +3034,11 @@ public class GoodsListingSubmitService {
totalValue = totalValue == null ? BigDecimal.ZERO:totalValue;
BigDecimal value = data.getMerchantInfo().getPersonnelCost().multiply(CommonConstants.ONEHUNDRED_BIGDECIMAL)
.divide(estimatedRevenueTotal,2, BigDecimal.ROUND_HALF_UP);
totalValue = totalValue.add(value);
totalValue = totalValue.add(value);*/
if (data.getMerchantInfo().getPersonnelCostRate() != null) {
totalValue = totalValue == null ? BigDecimal.ZERO:totalValue;
totalValue = totalValue.add(data.getMerchantInfo().getPersonnelCostRate());
}
}
if(totalValue != null) {
return totalValue.divide(BigDecimal.valueOf(count),2,BigDecimal.ROUND_HALF_UP).min(CommonConstants.ONEHUNDRED_BIGDECIMAL);
......
  • @wangxw1
    commented
    Master

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

    1. 性能与资源利用:循环内使用 List.contains 导致 O(N²) 性能隐患

    • 问题描述:在 validateVirtualInventoryStock 方法中,使用 virtualGoodsIdList.contains(upgradeGoodsId) 来判断是否已存在该商品 ID。virtualGoodsIdList 是一个 ArrayList。
    • 影响分析:此方法用于批量校验逻辑(如 Excel 导入)。在循环中对 ArrayList 进行 contains 判断的时间复杂度为 O(N²)。当导入的商品数据量较大时,会导致 CPU 消耗急剧增加,产生明显的性能瓶颈。
    • 优化建议:建议使用 HashSet 或 LinkedHashSet 来收集商品 ID,利用哈希表 O(1) 的查询特性进行去重,最后再转换为 ArrayList 以供 RPC 调用。 java // 优化示例 Set<Integer> virtualGoodsIdSet = new LinkedHashSet<>(); // ... 循环内 virtualGoodsIdSet.add(upgradeGoodsId); // ... 循环外 List<Integer> virtualGoodsIdList = new ArrayList<>(virtualGoodsIdSet);

    2. 功能健壮性:潜在的 NullPointerException (NPE) 风险

    • 问题描述:在替换收益计算逻辑时,直接调用了 data.getMerchantInfo().getPersonnelCostRate()。
    • 影响分析:如果 merchantInfoDTOMap 中未能匹配到对应的 merchantId(即 data 为 null),或者该商户详情中 merchantInfo 对象为空,将直接触发 NullPointerException,导致整个提交流程异常中断。虽然原代码也可能存在此隐患,但重构时应一并修复。
    • 优化建议:在获取深层级属性前,增加防御性判空校验。 java // 优化示例 if (data != null && data.getMerchantInfo() != null && data.getMerchantInfo().getPersonnelCostRate() != null) { totalValue = totalValue == null ? BigDecimal.ZERO : totalValue; totalValue = totalValue.add(data.getMerchantInfo().getPersonnelCostRate()); }

    3. 最佳实践与可维护性:僵尸代码残留与通配符导入

    • 问题描述:
      1. 代码中将之前复杂的 estimatedRevenueTotal 收益计算逻辑以及 packageRelatedGoodsIndexSet 变量直接注释掉(使用 /* ... */ 和 //),而非直接删除。
      2. 导入包部分将明确的类导入替换为了通配符导入 import cn.com.glsx.dj.smartcarlife.remote.*;。
    • 影响分析:保留大段注释掉的“僵尸代码”违反了 Clean Code 原则,会严重干扰后续开发者的阅读和代码维护;通配符导入(*)容易引发类名冲突,且隐藏了类之间的实际依赖关系,不符合主流 Java 工程规范。
    • 优化建议:直接删除无用的注释代码,代码的历史版本应交由 Git 进行管理;将通配符导入还原为具体的类导入(如 import cn.com.glsx.dj.smartcarlife.remote.MerchantPackageGoodsInfoRemote;)。

    二、评分明细

    • 功能实现的正确性与健壮性(35/40分):整体业务逻辑与虚拟库存的验证流程实现正确,能够处理正常的业务诉求。扣分点在于深层级对象调用时缺乏必要的 NPE 防御(如上述问题 2),以及 RPC 响应判断 !response.hasResult() 在某些框架下若返回空列表可能产生误判(建议结合 isSuccess() 判断)。
    • 安全性与潜在风险(30/30分):未发现 SQL 注入、XSS、越权及敏感信息泄露等安全隐患。新增的 RPC 调用未改变原有提供者接口参数,符合安全预期。
    • 最佳实践与可维护性(15/20分):方法拆分合理,validateVirtualInventoryStock 的引入提高了代码的模块化程度。扣分点在于残留了大段的注释代码未清理,以及使用了通配符导入。
    • 性能与资源利用(3/5分):RPC 批量调用设计合理,避免了循环内发起网络请求。扣分点在于循环内使用了 ArrayList.contains 进行去重,在批量处理场景下存在性能隐患。
    • 提交信息质量(5/5分):Commit 信息非常清晰且规范,使用了 refactor 前缀,并以列表形式准确详细地描述了所有变更点,可追溯性极佳。

    总分:88分

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