Commit eb85c36d by chenxi

5.8.6版本,商品上架后同步新增采购上架待审核记录

1 parent 0939bb4a
...@@ -17,6 +17,7 @@ import cn.com.glsx.dj.smartcarlife.model.*; ...@@ -17,6 +17,7 @@ import cn.com.glsx.dj.smartcarlife.model.*;
import cn.com.glsx.dj.smartcarlife.response.goods.PackageGoodsResponse; import cn.com.glsx.dj.smartcarlife.response.goods.PackageGoodsResponse;
import cn.com.glsx.dj.smartcarlife.service.*; import cn.com.glsx.dj.smartcarlife.service.*;
import cn.com.glsx.dj.smartcarlife.service.createBusiness.CreateBusinessProductService; import cn.com.glsx.dj.smartcarlife.service.createBusiness.CreateBusinessProductService;
import cn.com.glsx.dj.smartcarlife.service.purchaseGoods.PurchaseGoodsInfoService;
import cn.com.glsx.dj.smartcarlife.service.scene.SceneService; import cn.com.glsx.dj.smartcarlife.service.scene.SceneService;
import cn.com.glsx.dj.smartcarlife.service.stock.MerchantGoodsStockMonthReportService; import cn.com.glsx.dj.smartcarlife.service.stock.MerchantGoodsStockMonthReportService;
import cn.com.glsx.dj.smartcarlife.util.CommonUtil; import cn.com.glsx.dj.smartcarlife.util.CommonUtil;
...@@ -88,6 +89,9 @@ public class MerchantGoodsInfoService { ...@@ -88,6 +89,9 @@ public class MerchantGoodsInfoService {
private YqMerchantConfigService yqMerchantConfigService; private YqMerchantConfigService yqMerchantConfigService;
@Autowired @Autowired
private UpgradeGoodsService upgradeGoodsService; private UpgradeGoodsService upgradeGoodsService;
@Lazy
@Autowired
private PurchaseGoodsInfoService purchaseGoodsInfoService;
@Autowired @Autowired
private UpgradeGoodsServiceItemsRelationService upgradeGoodsServiceItemsRelationService; private UpgradeGoodsServiceItemsRelationService upgradeGoodsServiceItemsRelationService;
@Autowired @Autowired
...@@ -1083,6 +1087,13 @@ public class MerchantGoodsInfoService { ...@@ -1083,6 +1087,13 @@ public class MerchantGoodsInfoService {
.build(); .build();
upgradeGoodsService.changeShelfStatus(upgradeGoodsDTO); upgradeGoodsService.changeShelfStatus(upgradeGoodsDTO);
// 商品上架自动同步生成采购上架记录(待审核),失败不影响主流程
try {
purchaseGoodsInfoService.autoSyncFromMerchantGoods(merchantGoodsInfo, record.getUpdatedBy());
} catch (Exception e) {
log.error("autoSyncFromMerchantGoods invoke failed, merchantGoodsId={}", item, e);
}
pushGoodsManager.sendGoods(merchantGoodsInfo, record.getUpdatedBy()); pushGoodsManager.sendGoods(merchantGoodsInfo, record.getUpdatedBy());
//如果该商品是上架状态与场景是2.0的 自动开通场景 //如果该商品是上架状态与场景是2.0的 自动开通场景
if(SceneTypeEnum.SCENE1_0.getValue() == merchantGoodsInfo.getSceneType()) { if(SceneTypeEnum.SCENE1_0.getValue() == merchantGoodsInfo.getSceneType()) {
......
package cn.com.glsx.dj.smartcarlife.service.purchaseGoods; package cn.com.glsx.dj.smartcarlife.service.purchaseGoods;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.text.MessageFormat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Date; import java.util.Date;
import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.Objects; import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import cn.com.glsx.dj.smartcarlife.dto.goods.MerchantGoodsInfoDTO;
import cn.com.glsx.dj.smartcarlife.enums.CarLifeEnum; import cn.com.glsx.dj.smartcarlife.enums.CarLifeEnum;
import cn.com.glsx.dj.smartcarlife.model.SceneMerchantRefNew;
import cn.com.glsx.dj.smartcarlife.model.UpgradeGoods; import cn.com.glsx.dj.smartcarlife.model.UpgradeGoods;
import cn.com.glsx.dj.smartcarlife.model.UpgradeGoodsArea; import cn.com.glsx.dj.smartcarlife.model.UpgradeGoodsArea;
import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.CollectionUtils;
...@@ -25,12 +31,16 @@ import com.github.pagehelper.Page; ...@@ -25,12 +31,16 @@ import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageHelper;
import cn.com.glsx.dj.smartcarlife.dto.UpgradeGoodsDTO; import cn.com.glsx.dj.smartcarlife.dto.UpgradeGoodsDTO;
import cn.com.glsx.dj.smartcarlife.dto.goods.MerchantGoodsRefDTO;
import cn.com.glsx.dj.smartcarlife.dto.purchageGoods.PurchaseGoodsInfoDTO; import cn.com.glsx.dj.smartcarlife.dto.purchageGoods.PurchaseGoodsInfoDTO;
import cn.com.glsx.dj.smartcarlife.enums.CarLifeEnum.MerchantGoodsStatus; import cn.com.glsx.dj.smartcarlife.enums.CarLifeEnum.MerchantGoodsStatus;
import cn.com.glsx.dj.smartcarlife.enums.purchaseGoods.PurchaseGoodsLogType; import cn.com.glsx.dj.smartcarlife.enums.purchaseGoods.PurchaseGoodsLogType;
import cn.com.glsx.dj.smartcarlife.enums.purchaseGoods.PurchaseGoodsSuitCarType;
import cn.com.glsx.dj.smartcarlife.enums.ProductCostTypeEnum; import cn.com.glsx.dj.smartcarlife.enums.ProductCostTypeEnum;
import cn.com.glsx.dj.smartcarlife.mapper.GoodsInfoMapper; import cn.com.glsx.dj.smartcarlife.mapper.GoodsInfoMapper;
import cn.com.glsx.dj.smartcarlife.mapper.PurchaseGoodsInfoMapper; import cn.com.glsx.dj.smartcarlife.mapper.PurchaseGoodsInfoMapper;
import cn.com.glsx.dj.smartcarlife.mapper.SceneMerchantRefNewMapper;
import cn.com.glsx.dj.smartcarlife.mapper.UpgradeGoodsAreaMapper;
import cn.com.glsx.dj.smartcarlife.mapper.UpgradeGoodsMapper; import cn.com.glsx.dj.smartcarlife.mapper.UpgradeGoodsMapper;
import cn.com.glsx.dj.smartcarlife.model.GoodsInfo; import cn.com.glsx.dj.smartcarlife.model.GoodsInfo;
import cn.com.glsx.dj.smartcarlife.model.MerchantPurchaseGoodsRef; import cn.com.glsx.dj.smartcarlife.model.MerchantPurchaseGoodsRef;
...@@ -75,6 +85,10 @@ public class PurchaseGoodsInfoService { ...@@ -75,6 +85,10 @@ public class PurchaseGoodsInfoService {
private MerchantGoodsInfoService merchantGoodsInfoService; private MerchantGoodsInfoService merchantGoodsInfoService;
@Autowired @Autowired
private GoodsInfoMapper goodsInfoMapper; private GoodsInfoMapper goodsInfoMapper;
@Autowired
private SceneMerchantRefNewMapper sceneMerchantRefNewMapper;
@Autowired
private UpgradeGoodsAreaMapper upgradeGoodsAreaMapper;
public String createPurchaseGoodsCode(){ public String createPurchaseGoodsCode(){
return "PG" + DateUtils.formatDate(new Date(), "yyyyMMddHHmmssSSS") + RandomUtils.nextInt(1000, 10000); return "PG" + DateUtils.formatDate(new Date(), "yyyyMMddHHmmssSSS") + RandomUtils.nextInt(1000, 10000);
...@@ -181,6 +195,138 @@ public class PurchaseGoodsInfoService { ...@@ -181,6 +195,138 @@ public class PurchaseGoodsInfoService {
} }
} }
/**
* 商品上架审核通过后,自动同步生成采购上架记录(待审核)
* 幂等:SKU+园区店唯一,已有记录的园区店剔除后为空则不生成
* 失败只记日志,不阻断商品审核主流程
*/
@GlsxDistributeLockable(name = "'PurchaseGoodsInfoService_' + #merchantGoodsInfo.upgradeGoodsId",
timeoutException = RpcServiceException.class)
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = RpcServiceException.class)
public void autoSyncFromMerchantGoods(MerchantGoodsInfoDTO merchantGoodsInfo, String updatedBy) {
try {
// 0. 基础校验:套餐子商品不同步;SKU 缺失不同步
if (merchantGoodsInfo == null || merchantGoodsInfo.getId() == null
|| merchantGoodsInfo.getUpgradeGoodsId() == null
|| StringUtils.isNotBlank(merchantGoodsInfo.getPackageCode())) {
return;
}
Integer upgradeGoodsId = merchantGoodsInfo.getUpgradeGoodsId();
// 1. 4S 店 -> 园区店(scene=1, sub_merchant_type in (6,8), status=1, deleted=N),内存过滤 base_scene_code='100101',按 sub_merchant_id 去重
List<Integer> shopMerchantIds = merchantGoodsInfo.getMerchantGoodsRefList() == null ? new ArrayList<>()
: merchantGoodsInfo.getMerchantGoodsRefList().stream()
.map(MerchantGoodsRefDTO::getMerchantId).filter(Objects::nonNull).distinct()
.collect(Collectors.toList());
if (CollectionUtils.isEmpty(shopMerchantIds)) {
return;
}
List<SceneMerchantRefNew> yqRefs = sceneMerchantRefNewMapper
.listByShopIdListAndScene(shopMerchantIds, 1);
if (CollectionUtils.isEmpty(yqRefs)) {
return;
}
Map<Integer, SceneMerchantRefNew> parkStoreMap = yqRefs.stream()
.filter(r -> "100101".equals(r.getBaseSceneCode()) && r.getSubMerchantId() != null)
.collect(Collectors.toMap(SceneMerchantRefNew::getSubMerchantId, r -> r, (a, b) -> a));
if (parkStoreMap.isEmpty()) {
return;
}
// 2. SKU 信息 + 类目校验 + 运营成本
UpgradeGoods upgradeGoods = upgradeGoodsMapper.selectByPrimaryKey(upgradeGoodsId);
if (upgradeGoods == null || upgradeGoods.getOperationCost() == null
|| !matchesPurchaseCategory(upgradeGoods)) {
log.info("autoSyncFromMerchantGoods skip, upgradeGoodsId={}, cost/category not qualified", upgradeGoodsId);
return;
}
// 3. 唯一性剔除:该 SKU 已有采购记录(任意状态,未删除)挂的园区店不再生成
Set<Integer> existParkIds = new HashSet<>();
Example pgExample = new Example(PurchaseGoodsInfo.class);
pgExample.createCriteria().andEqualTo("deletedFlag", DeletedFlagEnum.N.name())
.andEqualTo("upgradeGoodsId", upgradeGoodsId);
List<PurchaseGoodsInfo> existList = purchaseGoodsInfoMapper.selectByExample(pgExample);
if (CollectionUtils.isNotEmpty(existList)) {
List<MerchantPurchaseGoodsRef> existRefs = merchantPurchaseGoodsRefService
.listByPurchaseGoodsIds(existList.stream()
.map(PurchaseGoodsInfo::getId).collect(Collectors.toList()));
existRefs.forEach(r -> existParkIds.add(r.getMerchantId()));
}
// 4. 区域校验剔除:产品适用区域不覆盖的园区店跳过
Example areaExample = new Example(UpgradeGoodsArea.class);
areaExample.createCriteria().andEqualTo("deletedFlag", DeletedFlagEnum.N.name())
.andEqualTo("upgradeGoodsId", upgradeGoodsId);
List<UpgradeGoodsArea> areas = upgradeGoodsAreaMapper.selectByExample(areaExample);
List<MerchantPurchaseGoodsRef> newRefs = new ArrayList<>();
for (Integer parkMerchantId : parkStoreMap.keySet()) {
if (existParkIds.contains(parkMerchantId)) {
continue;
}
if (!merchantGoodsInfoService.isProductAreaCoverMerchants(areas, Arrays.asList(parkMerchantId))) {
log.info("autoSyncFromMerchantGoods area not covered, upgradeGoodsId={}, parkMerchantId={}",
upgradeGoodsId, parkMerchantId);
continue;
}
SceneMerchantRefNew ref = parkStoreMap.get(parkMerchantId);
newRefs.add(MerchantPurchaseGoodsRef.builder()
.merchantId(ref.getSubMerchantId())
.merchantName(ref.getSubMerchantName())
.merchantType(ref.getSubMerchantType().byteValue())
.build());
}
if (newRefs.isEmpty()) {
return;
}
// 5. 生成采购上架记录(一条记录挂全部新命中园区店)
Date now = new Date();
PurchaseGoodsInfo record = PurchaseGoodsInfo.builder()
.purchaseGoodsCode(this.createPurchaseGoodsCode())
.upgradeGoodsId(upgradeGoodsId)
.purchasePrice(upgradeGoods.getOperationCost())
.status(MerchantGoodsStatus.WAIT_AUDIT.getValue()) // 待审核
.shelfSource(CarLifeEnum.MerchantShelfSource.AUTO_SYNC.getValue()) // 新值5
.suitCarType(PurchaseGoodsSuitCarType.COMMON.getValue()) // 通用
.purchaseGoodsName(upgradeGoods.getUpgradeGoodsName())
.purchaseCostType(ProductCostTypeEnum.DEFAULT_IMPORT.getValue()) // 默认带入产品成本
.createdBy(updatedBy).createdDate(now)
.updatedBy(updatedBy).updatedDate(now)
.deletedFlag(DeletedFlagEnum.N.name())
.build();
purchaseGoodsInfoMapper.insertUseGeneratedKeys(record);
merchantPurchaseGoodsRefService.updateBatch(record.getId(), newRefs, updatedBy);
// 6. 操作日志:第一位用 merchant_goods_code(业务编号),不携带采购记录 ID 占位
String logContent = MessageFormat.format("通过商品上架ID {0},自动生成采购上架ID,操作人:{1}",
merchantGoodsInfo.getMerchantGoodsCode(), updatedBy);
purchaseGoodsLogService.insert(PurchaseGoodsLogType.AUTO_CREATE, record.getId(), updatedBy, logContent);
log.info("autoSyncFromMerchantGoods done, merchantGoodsId={}, purchaseGoodsId={}, parkStores={}",
merchantGoodsInfo.getId(), record.getId(), newRefs.size());
} catch (Exception e) {
// 单条失败不阻断商品审核主流程
log.error("autoSyncFromMerchantGoods failed, merchantGoodsId={}", merchantGoodsInfo.getId(), e);
}
}
/** 与手工创建同口径的类目校验(不抛异常,返回是否允许) */
private boolean matchesPurchaseCategory(UpgradeGoods upgradeGoods) {
if (StringUtils.isBlank(upgradeGoods.getGoodsCode())) {
return true;
}
GoodsInfo spu = new GoodsInfo();
spu.setGoodsCode(upgradeGoods.getGoodsCode());
spu.setDeletedFlag(DeletedFlagEnum.N.name());
spu = goodsInfoMapper.selectOne(spu);
if (spu == null) {
return true;
}
String categoryName = merchantGoodsInfoService.getCategoryName(spu);
return merchantGoodsInfoService.matchesCategoryKeyword(categoryName);
}
public PurchaseGoodsInfo getBaseById(Integer id) { public PurchaseGoodsInfo getBaseById(Integer id) {
RpcAssert.assertNotNull(id, DefaultErrorEnum.DATA_NULL,"id not be null"); RpcAssert.assertNotNull(id, DefaultErrorEnum.DATA_NULL,"id not be null");
try { try {
......
  • @wangxw1
    commented
    Master

    以下是对您提交代码的专业审查意见。代码整体逻辑清晰,但在事务控制和模块解耦方面存在几个需要重点关注的问题。

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

    1. 异常吞没导致 @Transactional 事务失效及脏数据风险(重要性:高)

    • 问题描述:在 PurchaseGoodsInfoService.autoSyncFromMerchantGoods 方法上添加了 @Transactional(rollbackFor = RpcServiceException.class) 注解,但整个方法体被 try { ... } catch (Exception e) { ... } 包裹,且在 catch 块中仅记录日志而未将异常重新抛出。
    • 影响分析:Spring 的声明式事务依赖于 AOP 捕获抛出的异常来触发回滚。由于异常在方法内部被吞没,如果方法执行中途(如 purchaseGoodsInfoMapper.insertUseGeneratedKeys 执行后,但在 merchantPurchaseGoodsRefService.updateBatch 执行前)发生异常,事务管理器会认为方法执行成功并提交事务,从而产生不完整的脏数据。
    • 优化建议:由于调用方 MerchantGoodsInfoService 已经使用了 try-catch 来保证“失败不影响主流程”,被调用方内部的 try-catch 是多余且有害的。建议移除方法内部的 try-catch,或在 catch 块中重新抛出异常。 java // 建议移除 try-catch,让异常自然抛出,由调用方捕获,或者: } catch (Exception e) { log.error("autoSyncFromMerchantGoods failed, merchantGoodsId={}", merchantGoodsInfo.getId(), e); // 必须抛出异常以触发事务回滚 throw new RpcServiceException("自动同步采购上架记录失败", e); }

    2. 分布式锁 SpEL 表达式存在空指针风险(重要性:中)

    • 问题描述:@GlsxDistributeLockable(name = "'PurchaseGoodsInfoService_' + #merchantGoodsInfo.upgradeGoodsId"...) 中使用了参数的属性作为锁的 Key。虽然方法内部第 14 行做了 merchantGoodsInfo == null 的校验,但 AOP 拦截器的 SpEL 解析发生在方法进入之前。
    • 影响分析:如果传入的 merchantGoodsInfo 为 null,SpEL 解析时会直接抛出 NullPointerException 或 SpelEvaluationException,导致阻断主流程,且内部的容错校验无法发挥作用。
    • 优化建议:在 SpEL 表达式中使用安全导航操作符(Safe Navigation Operator ?.),防止空指针异常。 java @GlsxDistributeLockable(name = "'PurchaseGoodsInfoService_' + #merchantGoodsInfo?.upgradeGoodsId", timeoutException = RpcServiceException.class)

    3. 循环依赖与模块强耦合(重要性:中)

    • 问题描述:MerchantGoodsInfoService 通过 @Lazy 注入了 PurchaseGoodsInfoService,而 PurchaseGoodsInfoService 又注入了 MerchantGoodsInfoService,形成了双向循环依赖。
    • 影响分析:虽然 @Lazy 暂时解决了 Spring 启动时的循环依赖报错,但这属于架构设计上的“坏味道”(Code Smell),说明两个服务之间耦合过重,不利于后续的维护、单元测试和模块拆分。
    • 优化建议:鉴于业务需求是“商品上架自动同步...失败不影响主流程”,这属于典型的事件驱动场景。建议使用 Spring 的 @TransactionalEventListener(或者 MQ)来解耦。
      • MerchantGoodsInfoService 发布事件:applicationContext.publishEvent(new GoodsOnShelfEvent(merchantGoodsInfo));
      • PurchaseGoodsInfoService 监听事件并异步处理,彻底消除循环依赖,且能保证在主事务提交后再执行同步。

    二、评分明细

    • 功能实现的正确性与健壮性(30/40分)
      • 扣分原因:事务控制中吞没异常导致回滚失效,是较严重的数据一致性隐患(-10分)。
      • 亮点:业务逻辑考虑了幂等性(SKU+园区店唯一剔除)、区域校验以及异常不阻断主流程,边界条件处理较好。
    • 安全性与潜在风险(30/30分)
      • 理由:未发现 SQL 注入、越权等安全漏洞。MyBatis 的 Example 使用规范,且未违反“禁止使用子查询”的规则。
    • 最佳实践与可维护性(15/20分)
      • 扣分原因:使用了 @Lazy 解决循环依赖,模块间耦合度较高;SpEL 表达式存在潜在的 NPE 风险(-5分)。
      • 亮点:代码注释清晰,变量命名规范,Stream API 使用熟练。
    • 性能与资源利用(5/5分)
      • 理由:在循环外预先查询数据(如 upgradeGoodsAreaMapper.selectByExample),并在内存中进行匹配过滤,有效避免了 N+1 数据库查询问题,性能意识良好。
    • 提交信息质量(5/5分)
      • 理由:Commit 信息(5.8.6版本,商品上架后同步新增采购上架待审核记录 (by chenxi))包含了版本号、业务动作和操作人,清晰可追溯。

    总分:85分

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