Commit a0f47d65 by 周立明

feat: 添加利润率计算校验与审核流程优化

1. 新增利润率未完成计算统计Mapper方法与远程接口
2. 补充审核状态枚举值,新增审核提交中与失败状态
3. 校验审核前利润率是否全部计算完成
4. 调整审核流程状态变更与异步处理逻辑
5. 优化非太阳膜商品字段清空逻辑
1 parent 67bb91be
......@@ -81,8 +81,10 @@ public class GoodsListingEnum {
DRAFT((byte) 0, "草稿"),
PENDING((byte) 1, "待审核"),
APPROVED((byte) 2, "已审核"),
REJECTED((byte) 3, "驳回");
REJECTED((byte) 3, "驳回"),
// PROFIT_RATE_CALCULATING((byte) 4, "利润率计算中"),
REVIEWING((byte) 5, "审核提交中"),
REVIEW_FAIL((byte) 6, "审核提交失败");
private final Byte value;
private final String name;
......
......@@ -40,4 +40,8 @@ public interface GoodsListingProductRemote {
@ApiMethod("删除上架产品")
@ApiParam(name = "record", notes = "产品详情", dataType = ApiParam.DataTypeEnum.OBJECT, required = true)
RpcResponse<Boolean> delete(@NotNull GoodsListingProductBaseDTO record);
@ApiMethod("利润率是否全部计算完成")
@ApiParam(name = "businessCode", notes = "单据编号", dataType = ApiParam.DataTypeEnum.STRING, required = true)
RpcResponse<Boolean> profitRateHasCalFinish(@NotBlank String businessCode);
}
......@@ -16,4 +16,6 @@ public interface GoodsListingProductBaseMapper extends OreMapper<GoodsListingPro
GoodsListingProductBaseDTO getDetailById(@Param("id") Integer id);
List<GoodsListingProductBaseDTO> list(GoodsListingProductBaseDTO condition);
int countProfitRateNotCalFinish(GoodsListingProductBaseDTO condition);
}
\ No newline at end of file
......@@ -87,4 +87,14 @@ public class GoodsListingProductRemoteImpl implements GoodsListingProductRemote
}
}
@Override
public RpcResponse<Boolean> profitRateHasCalFinish(@NotBlank String businessCode) {
try {
return RpcResponse.success(goodsListingProductBaseService.profitRateHasCalFinish(businessCode));
} catch(RpcServiceException e) {
log.error(e.getMessage(),e);
return RpcResponse.error(e);
}
}
}
......@@ -302,9 +302,11 @@ public class GoodsListingApprovalService {
RpcAssert.assertNotNull(oldRecord, DefaultErrorEnum.DATA_NOT_EXIST,"操作数据不存在请刷新页面后重试");
RpcAssert.assertIsTrue(Objects.equals(oldRecord.getSystemStatus(),SystemStatus.PENDING.getValue()),
DefaultErrorEnum.SERVER_ERROR, "仅待审核状态可以审核");
goodsListingProductBaseService.validConfirmStep(oldRecord);
final Date now = new Date();
goodsListingApprovalMapper.updateByPrimaryKeySelective(GoodsListingApproval.builder()
.id(oldRecord.getId()).systemStatus(SystemStatus.APPROVED.getValue())
.id(oldRecord.getId()).systemStatus(SystemStatus.REVIEWING.getValue())
.updatedBy(record.getUpdatedBy()).updatedDate(now)
.build());
......@@ -313,10 +315,26 @@ public class GoodsListingApprovalService {
.operatorType(LogOperatorType.APPROVE.getValue())
.updatedBy(record.getUpdatedBy()).updatedDate(now)
.build());
log.info("商品上架审核start,businessCode:{}",record.getBusinessCode());
long l = System.currentTimeMillis();
thiz.publishApprovedListingData(record.getBusinessCode(), record.getUpdatedBy());
log.info("商品上架审核end,businessCode:{} consuming:{} ms",record.getBusinessCode(),System.currentTimeMillis() - l);
// 事务提交后
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
@Override
public void afterCommit() {
taskExecutor.execute(() -> {
try {
log.info("商品上架审核start,businessCode:{}",record.getBusinessCode());
long l = System.currentTimeMillis();
thiz.publishApprovedListingData(record.getBusinessCode(), record.getUpdatedBy());
log.info("商品上架审核end,businessCode:{} consuming:{} ms",record.getBusinessCode(),System.currentTimeMillis() - l);
}catch(Exception e) {
log.error(e.getMessage(),e);
goodsListingApprovalMapper.updateByPrimaryKeySelective(GoodsListingApproval.builder()
.id(oldRecord.getId()).systemStatus(SystemStatus.REVIEW_FAIL.getValue())
.updatedBy(record.getUpdatedBy()).updatedDate(now)
.build());
}
});
}
});
return true;
}catch (RpcServiceException e) {
throw e;
......@@ -336,7 +354,11 @@ public class GoodsListingApprovalService {
GoodsListingApproval oldRecord = thiz.getByValidUpdate(record.getBusinessCode());
List<GoodsListingProductBaseDTO> products = goodsListingProductBaseService.listByBusinessCode(record.getBusinessCode());
if (CollectionUtils.isEmpty(products)) {
throw new RpcServiceException(DefaultErrorEnum.SERVICE_ERROR, "产品信息为空,businessCode:" + record.getBusinessCode());
throw new RpcServiceException(DefaultErrorEnum.SERVER_ERROR, "产品信息为空,businessCode:" + record.getBusinessCode());
}
boolean hasNotFinish = products.stream().anyMatch(o -> !Objects.equals(o.getProfitRateCalFinish() ,StatusEnum.YES.getValue()));
if (hasNotFinish) {
throw new RpcServiceException(DefaultErrorEnum.SERVER_ERROR, "利润率未计算完成");
}
List<String> nonProfitProducts = products.stream().filter(o -> o.getProfitRate() == null)
.map(o -> {
......@@ -377,21 +399,23 @@ public class GoodsListingApprovalService {
publishApprovedSettleRules(context);
publishApprovedReconciliationRules(context);
updateMerchantRuleIds(context);
goodsListingApprovalMapper.updateByPrimaryKeySelective(GoodsListingApproval.builder()
.id(context.approval.getId()).systemStatus(SystemStatus.APPROVED.getValue())
.updatedBy(updatedBy).updatedDate(new Date())
.build());
// 事务提交后
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
@Override
public void afterCommit() {
if(CollectionUtils.isNotEmpty(context.details)){
taskExecutor.execute(() -> {
context.details.forEach(item ->{
MerchantGoodsInfoDTO merchantGoodsInfo = MerchantGoodsInfoDTO.builder()
.updatedBy(updatedBy)
.merchantGoodsCodeList(Arrays.asList(item.getMerchantGoodsCode()))
.build();
RpcResponse<Boolean> res = merchantGoodsInfoRemote.onShelfHandler(merchantGoodsInfo);
log.info("上架ID:{}处理完成,处理结果:{}",item.getMerchantGoodsCode(),res);
});
});
context.details.forEach(item ->{
MerchantGoodsInfoDTO merchantGoodsInfo = MerchantGoodsInfoDTO.builder()
.updatedBy(updatedBy)
.merchantGoodsCodeList(Arrays.asList(item.getMerchantGoodsCode()))
.build();
RpcResponse<Boolean> res = merchantGoodsInfoRemote.onShelfHandler(merchantGoodsInfo);
log.info("上架ID:{}处理完成,处理结果:{}",item.getMerchantGoodsCode(),res);
});
}
}
});
......@@ -1923,7 +1947,13 @@ public class GoodsListingApprovalService {
case RECONCILIATION_CONFIG:
goodsListingReconciliationRuleService.validConfirmStep(goodsListingApproval);
nextStep = ConfirmStep.PROFIT_RATE;
goodsListingRemote.updateCreateBusinessProductProfit(goodsListingApproval.getBusinessCode());
// 事务提交后
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
@Override
public void afterCommit() {
goodsListingRemote.updateCreateBusinessProductProfit(goodsListingApproval.getBusinessCode());
}
});
break;
default:
throw new RpcServiceException(DefaultErrorEnum.SERVER_ERROR,"当前页面不能进行下一步操作");
......
......@@ -77,6 +77,19 @@ public class GoodsListingProductBaseService {
throw new RpcServiceException(DefaultErrorEnum.SERVICE_ERROR, e.getMessage());
}
}
//利润率是否全部计算完成
public boolean profitRateHasCalFinish(String businessCode) {
RpcAssert.assertNotEmpty(businessCode, DefaultErrorEnum.DATA_NULL, "businessCode不能为空");
try{
int count = goodsListingProductBaseMapper.countProfitRateNotCalFinish(GoodsListingProductBaseDTO.builder()
.businessCode(businessCode)
.build());
return count == 0;
}catch (Exception e){
log.error(e.getMessage(), e);
throw new RpcServiceException(DefaultErrorEnum.SERVICE_ERROR);
}
}
public List<GoodsListingProductBase> listBase(String businessCode) {
RpcAssert.assertNotEmpty(businessCode, DefaultErrorEnum.DATA_NULL, "businessCode不能为空");
......@@ -349,6 +362,13 @@ public class GoodsListingProductBaseService {
o.setGiftCost(null);
}else {
o.setThirdPartyCost(null);
//是否太阳膜商品
List<Integer> solarFilmGoodsTypeList = CommonUtil.convert2Integer(OrePropertyConfigurer.getString("smartcarlife.goodsType.solarFilm.list","1").split(","));
boolean isSolarFilmGoods = solarFilmGoodsTypeList.contains(upgradeGoods.getGoodsInfo().getGoodsType());
if(!isSolarFilmGoods) {
o.setRecoveryCost(null);
o.setGiftCost(null);
}
}
});
record.setUpdatedDate(new Date());
......
......@@ -114,7 +114,14 @@
<if test="id != null">
and glpb.id = #{id}
</if>
<if test="profitRateCalFinish != null and profitRateCalFinish !=''">
and profit_rate_cal_finish = #{profitRateCalFinish}
</if>
</where>
</sql>
<select id="countProfitRateNotCalFinish" parameterType="cn.com.glsx.dj.goods.listing.dto.GoodsListingProductBaseDTO" resultType="java.lang.Integer">
select count(0) from dj_car_life_goods_listing_product_base
where deleted_flag='N' and business_code = #{businessCode} and (profit_rate_cal_finish is null or profit_rate_cal_finish !='Y')
</select>
</mapper>
\ No newline at end of file
  • @wangxw1
    commented
    Master

    这是一份针对您提交代码的代码审查报告。代码整体结构清晰,引入分布式锁和优化事务提交后的处理逻辑方向是正确的,但在性能细节和异步一致性处理上存在几个需要重点关注的问题。

    (注:已严格核查重要规则,未发现MyBatis子查询违规,亦未发现Dubbo已有请求参数变更违规)

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

    1. 性能瓶颈:在循环内部进行配置解析与类型转换(重要性:高)

    • 问题描述:在 GoodsListingProductBaseService.java 的 listBase 逻辑中(第362行附近),判断是否为太阳膜商品时,读取系统配置 OrePropertyConfigurer.getString、执行字符串 split 以及 CommonUtil.convert2Integer 等高开销操作被放置在了 upgradeGoods.getDetails().forEach 循环体内部。
    • 影响分析:如果 details 列表数据量较大,每次遍历都会重复执行磁盘/缓存读取、字符串切割和列表装载,这会产生大量的临时对象,增加 GC 压力,并造成明显的 CPU 性能浪费。
    • 优化建议:将配置读取和解析逻辑提取到循环外部执行一次即可。 ```java // 优化示例 // 1. 将高开销操作提取到循环外部 List solarFilmGoodsTypeList = CommonUtil.convert2Integer( OrePropertyConfigurer.getString("smartcarlife.goodsType.solarFilm.list","1").split(",") ); boolean isSolarFilmGoods = solarFilmGoodsTypeList.contains(upgradeGoods.getGoodsInfo().getGoodsType());

    upgradeGoods.getDetails().forEach(o -> { if (o.getIsUpgrade() == StatusEnum.YES.getValue()) { o.setRecoveryCost(null); o.setGiftCost(null); } else { o.setThirdPartyCost(null); // 2. 内部直接使用外部判断好的布尔值 if(!isSolarFilmGoods) { o.setRecoveryCost(null); o.setGiftCost(null); } } });

    
    #### 2. 性能与稳定性风险:事务提交后同步执行批量 RPC 调用(重要性:高)
    - **问题描述**:在 `GoodsListingApprovalService.java` 的 `submitReview` 方法中(第408行),移除了原有的 `taskExecutor.execute` 异步处理,直接在 `TransactionSynchronizationAdapter.afterCommit()` 中使用 `forEach` 循环同步调用远程 Dubbo 接口 `merchantGoodsInfoRemote.onShelfHandler`。
    - **影响分析**:`afterCommit` 钩子虽然在数据库事务提交后执行,但**它仍然运行在当前请求的 Tomcat/Dubbo 业务线程上**。同步进行批量 RPC 调用会严重阻塞当前线程,导致 `submitReview` 接口响应时间大幅增加,极端情况下可能引发请求超时或线程池耗尽。
    - **优化建议**:恢复异步执行机制。如果对数据一致性要求极高,建议改用发送 MQ 消息的方式,由消费端去调用上架接口;如果允许最终一致性,请将其放回线程池中执行。
      ```java
      // 优化示例:恢复线程池异步执行
      TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
          @Override
          public void afterCommit() {
              if(CollectionUtils.isNotEmpty(context.details)){
                  // 必须使用线程池异步执行,避免阻塞主线程
                  taskExecutor.execute(() -> {
                      context.details.forEach(item -> {
                          // ... RPC 调用逻辑
                      });
                  });
              }
          }
      });
    

    (注:同文件 updateConfirmStep 方法中的 goodsListingRemote.updateCreateBusinessProductProfit 也存在相同问题,建议一并异步化)

    3. 健壮性风险:内存异步任务导致的状态机“僵尸状态”(重要性:中)

    • 问题描述:在 GoodsListingApprovalService.java 的 review 方法中(第321行),状态被更新为 REVIEWING(审核中),随后在 afterCommit 中开启异步线程处理业务。如果异步线程抛出异常,会捕获并更新状态为 REVIEW_FAIL。
    • 影响分析:虽然考虑了异常回调,但如果应用在事务刚刚提交但异步线程还未执行或执行中途发生 JVM 宕机/重启,这条记录的状态将永远停留在 REVIEWING,形成“僵尸数据”,用户无法继续操作。
    • 优化建议: 内存异步更新状态不够可靠。推荐方案:
      1. 引入定时任务(Job),定期扫描长时间处于 REVIEWING 状态的单据进行重试或告警。
      2. (更佳实践)使用可靠消息队列(如 RocketMQ 事务消息),将状态流转与后续业务解耦。

    二、评分明细

    • 功能实现的正确性与健壮性 (35/40分) 理由:核心业务逻辑(如利润率校验、分布式锁防并发)实现正确,符合业务诉求;MyBatis 和 Dubbo 规范严格遵守。扣分点在于异步状态机的异常中断未考虑宕机场景(问题3)。
    • 安全性与潜在风险 (30/30分) 理由:无 SQL 注入及越权等安全漏洞。引入 GlsxDistributeLockable 分布式锁有效规避了并发操作带来的数据错乱风险。
    • 最佳实践与可维护性 (16/20分) 理由:代码结构清晰,异常处理逻辑(先捕获 RpcServiceException 再捕获 Exception)符合规范。扣分点:BeanConfig 中的锁超时时间 1800000 被硬编码,建议抽取到配置文件中;部分异常枚举 SERVER_ERROR 和 SERVICE_ERROR 混用。
    • 性能与资源利用 (1/5分) 理由:存在两处明显的性能隐患。一是循环内解析配置(问题1),二是将原本的异步 RPC 调用改为了同步阻塞调用(问题2),这在高并发下会对系统吞吐量造成较大打击。
    • 提交信息质量 (5/5分) 理由:Commit message 格式规范,分点清晰地描述了修改动机和具体内容,具有极高的可追溯性。

    总分:87分

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