Commit e46a3b53 by 范富荣

feat:新增产品自动创建定时任务

1 parent 07559279
......@@ -39,4 +39,8 @@ public class ServiceItemsExtendCreatedDTO implements Serializable {
@ApiModelProperty(notes = "规格名称列表", required = true)
private List<ServiceItemsSpecificationDTO> specificationNameList;
/**
* 是否迁移SKU分类
*/
private boolean skuCategoryMigration;
}
package cn.com.glsx.scrm.equity.model;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.*;
/**
* 自动创建商品映射表
* 存放商品信息及新旧服务编码/配置id的映射关系
*/
@Data
@Table(name = "auto_create_goods_mapping")
public class AutoCreateGoodsMapping implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键
*/
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
/**
* spu_id
*/
@Column(name = "spu_id")
private String spuId;
/**
* 旧服务编码 (service_items.service_code)
*/
@Column(name = "old_service_code")
private String oldServiceCode;
/**
* 新服务编码 (创建后回填)
*/
@Column(name = "new_service_code")
private String newServiceCode;
/**
* sku_id
*/
@Column(name = "sku_id")
private String skuId;
/**
* 旧配置id (extend_item_specification_config.id)
*/
@Column(name = "old_config_id")
private Integer oldConfigId;
/**
* 新配置id (创建后回填)
*/
@Column(name = "new_config_id")
private Integer newConfigId;
/**
* 删除标识(D:已删除;N:未删除)
*/
@Column(name = "deleted_flag")
private String deletedFlag;
/**
* 处理状态(0:待处理;1:已处理;2:处理失败)
*/
@Column(name = "process_status")
private Integer processStatus;
/**
* 失败原因
*/
@Column(name = "fail_reason")
private String failReason;
/**
* 创建人
*/
@Column(name = "created_by")
private String createdBy;
/**
* 创建时间
*/
@Column(name = "created_date")
private Date createdDate;
/**
* 修改人
*/
@Column(name = "updated_by")
private String updatedBy;
/**
* 修改时间
*/
@Column(name = "updated_date")
private Date updatedDate;
}
......@@ -217,7 +217,7 @@
<dependency>
<groupId>cn.com.glsx.dj</groupId>
<artifactId>rpc-dj-smartcarlife-api</artifactId>
<version>5.8.1-SNAPSHOT</version>
<version>5.8.4-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.oreframework.boot</groupId>
......
package cn.com.glsx.scrm.equity.job;
import cn.com.glsx.scrm.equity.service.AutoCreateGoodsMappingService;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import lombok.extern.slf4j.Slf4j;
import org.oreframework.boot.autoconfigure.elasticjob.annotation.ElasticJobConf;
import org.springframework.beans.factory.annotation.Autowired;
/**
* 自动创建商品定时任务
* 读取auto_create_goods_mapping表中待处理的映射记录,
* 根据旧服务编码+旧配置id查询已有信息,生成新的服务编码和配置id,保存映射关系
*/
@ElasticJobConf(
name = "AutoCreateGoodsJob",
overwrite = true,
description = "自动创建商品定时任务",
shardingItemParameters = "0=stock",
misfire = false,
cron = "0 0 2 * * ?"
)
@Slf4j
public class AutoCreateGoodsJob implements SimpleJob {
@Autowired
private AutoCreateGoodsMappingService autoCreateGoodsMappingService;
@Override
public void execute(ShardingContext shardingContext) {
log.info("开始执行自动创建商品定时任务");
try {
autoCreateGoodsMappingService.processAutoCreateGoods();
} catch (Exception e) {
log.error("自动创建商品定时任务执行异常: {}", e.getMessage(), e);
}
log.info("结束自动创建商品定时任务");
}
}
package cn.com.glsx.scrm.equity.mapper;
import cn.com.glsx.scrm.equity.model.AutoCreateGoodsMapping;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.oreframework.datasource.mybatis.mapper.OreMapper;
import java.util.List;
/**
* 自动创建商品映射Mapper
*/
@Mapper
public interface AutoCreateGoodsMappingMapper extends OreMapper<AutoCreateGoodsMapping> {
/**
* 查询待处理的映射记录
* @return 待处理记录列表
*/
List<AutoCreateGoodsMapping> listPendingRecords();
/**
* 查询指定旧服务编码下待处理的配置映射记录
* @param oldServiceCode 旧服务编码
* @return 配置映射记录列表
*/
List<AutoCreateGoodsMapping> listPendingByOldServiceCode(@Param("oldServiceCode") String oldServiceCode);
/**
* 更新映射记录的新服务编码和新配置id
* @param mapping 映射记录
* @return 更新条数
*/
int updateNewCodeAndConfigId(AutoCreateGoodsMapping mapping);
}
......@@ -97,6 +97,7 @@ public class ExtendItemSpecificationConfigService {
specificationConfig.setCreatedDate(date);
insertList.add(specificationConfig);
} else {//更新
specificationConfig.setServiceCode(serviceCode);
specificationConfig.setUpdatedBy(createdBy);
specificationConfig.setUpdatedDate(date);
updateList.add(specificationConfig);
......@@ -113,22 +114,24 @@ public class ExtendItemSpecificationConfigService {
seriesConfigMap = listSeriesConfigMap(oldIdList);
}
if (CollectionUtils.isNotEmpty(updateList)) {
if (CollectionUtils.isEmpty(oldList)) throw new RpcServiceException(DefaultErrorEnum.DATA_INVALID, "规格记录id不存在,更新失败");
//奖oldList以主键id为key,转map
Map<Integer, ExtendItemSpecificationConfig> oldMap = oldList.stream().collect(Collectors.toMap(ExtendItemSpecificationConfig::getId, a -> a, (k1, k2) -> k1));
//查询字段名称映射集合
List<ItemsGradeModifyFieldDescDTO> fieldDescList = extendItemSpecificationConfigMapper.listAllFieldDesc();
Map<String, ItemsGradeModifyFieldDescDTO> filedDescMap = fieldDescList.stream().collect(Collectors.toMap(ItemsGradeModifyFieldDescDTO::getField, a -> a, (k1, k2) -> k1));
for (ExtendItemSpecificationConfigDTO specificationConfig : updateList) {
if (!oldMap.containsKey(specificationConfig.getId())) {
throw new RpcServiceException(DefaultErrorEnum.DATA_INVALID, "规格记录id[" + specificationConfig.getId() + "]不存在,更新失败");
if (!serviceItemsExtendCreatedDTO.isSkuCategoryMigration()) {//非迁移SKU分类,需要对比更新
if (CollectionUtils.isEmpty(oldList)) throw new RpcServiceException(DefaultErrorEnum.DATA_INVALID, "规格记录id不存在,更新失败");
//奖oldList以主键id为key,转map
Map<Integer, ExtendItemSpecificationConfig> oldMap = oldList.stream().collect(Collectors.toMap(ExtendItemSpecificationConfig::getId, a -> a, (k1, k2) -> k1));
//查询字段名称映射集合
List<ItemsGradeModifyFieldDescDTO> fieldDescList = extendItemSpecificationConfigMapper.listAllFieldDesc();
Map<String, ItemsGradeModifyFieldDescDTO> filedDescMap = fieldDescList.stream().collect(Collectors.toMap(ItemsGradeModifyFieldDescDTO::getField, a -> a, (k1, k2) -> k1));
for (ExtendItemSpecificationConfigDTO specificationConfig : updateList) {
if (!oldMap.containsKey(specificationConfig.getId())) {
throw new RpcServiceException(DefaultErrorEnum.DATA_INVALID, "规格记录id[" + specificationConfig.getId() + "]不存在,更新失败");
}
ExtendItemSpecificationConfig oldConfig = oldMap.get(specificationConfig.getId());
//对比是否更新
ExtendItemSpecificationConfig newConfig = new ExtendItemSpecificationConfig();
BeanUtils.copyProperties(specificationConfig, newConfig);
ItemSpecificationConfigModifyRecordDTO recordDTO = handlerSpecificationConfigModifyRecord(oldConfig, newConfig, filedDescMap, specificationConfig.getSeriesConfigList(), seriesConfigMap);
if (recordDTO != null) recordDTOList.add(recordDTO);
}
ExtendItemSpecificationConfig oldConfig = oldMap.get(specificationConfig.getId());
//对比是否更新
ExtendItemSpecificationConfig newConfig = new ExtendItemSpecificationConfig();
BeanUtils.copyProperties(specificationConfig, newConfig);
ItemSpecificationConfigModifyRecordDTO recordDTO = handlerSpecificationConfigModifyRecord(oldConfig, newConfig, filedDescMap, specificationConfig.getSeriesConfigList(), seriesConfigMap);
if (recordDTO != null) recordDTOList.add(recordDTO);
}
//批量更新
extendItemSpecificationConfigMapper.batchUpdate(updateList);
......@@ -304,6 +307,7 @@ public class ExtendItemSpecificationConfigService {
}
param.setGoodsSpecificationNameList(goodsSpecificationNameList);
param.setServiceCode(serviceCode);
param.setSkuCategoryMigration(serviceItemsExtendCreatedDTO.isSkuCategoryMigration());
log.info("同步延保规格信息到嘀加,参数[{}]", JSON.toJSONString(param));
RpcResponse<ProductManagerAddOrUpdateDTO> response = productManagerRemote.syncScrmProduct(param);
if (response.hasError()) {
......@@ -466,4 +470,46 @@ public class ExtendItemSpecificationConfigService {
return extendItemSpecificationConfigMapper.listItemSpecificationConfigByServiceCodeList(codeList);
}
/**
* 根据id列表批量软删除规格配置
* @param idList 配置id列表
* @param updatedBy 修改人
*/
public void batchDeleteByIds(List<Integer> idList, String updatedBy) {
if (CollectionUtils.isEmpty(idList)) {
return;
}
Date date = new Date();
List<ExtendItemSpecificationConfig> deleteList = new ArrayList<>();
for (Integer id : idList) {
ExtendItemSpecificationConfig config = new ExtendItemSpecificationConfig();
config.setId(id);
config.setDeletedFlag(DeleteFlagEnum.D.getValue());
config.setUpdatedBy(updatedBy);
config.setUpdatedDate(date);
deleteList.add(config);
}
extendItemSpecificationConfigMapper.batchDelete(deleteList);
}
/**
* 根据配置id列表批量软删除车型配置
* @param configIdList 配置id列表(itemSpecificationId)
* @param updatedBy 修改人
*/
public void batchDeleteVehicleSeriesByConfigIds(List<Integer> configIdList, String updatedBy) {
if (CollectionUtils.isEmpty(configIdList)) {
return;
}
Date date = new Date();
Example example = new Example(ItemsVehicleSeriesConfig.class);
example.createCriteria().andIn("itemSpecificationId", configIdList)
.andEqualTo("deletedFlag", DeleteFlagEnum.N.getValue());
ItemsVehicleSeriesConfig update = new ItemsVehicleSeriesConfig();
update.setDeletedFlag(DeleteFlagEnum.D.getValue());
update.setUpdatedBy(updatedBy);
update.setUpdatedDate(date);
itemsVehicleSeriesConfigMapper.updateByExampleSelective(update, example);
}
}
......@@ -473,4 +473,26 @@ public class ServiceItemsService {
.andEqualTo("pushFlag", ItemsPushFlagEnum.TURN_OFF.getValue());
return serviceItemsMapper.selectByExample(example);
}
/**
* 获取下一个延保服务编码(预计算,用于自动创建商品场景)
* @return 下一个延保服务编码
*/
public String getNextExtendServiceCode() {
int serviceCodeNum = 0;
ServiceItems serviceItems = serviceItemsMapper.getExtendMaxAttribute();
if (serviceItems != null && StringUtils.isNotEmpty(serviceItems.getServiceCode())) {
serviceCodeNum = Integer.parseInt(serviceItems.getServiceCode().replace(EXTEND_SERVICE_CODE_PREFIX, ""));
}
return String.format("%s%04d", EXTEND_SERVICE_CODE_PREFIX, serviceCodeNum + 1);
}
/**
* 通用查询单条记录
* @param example 查询条件
* @return 服务项目
*/
public ServiceItems selectOneByExample(Example example) {
return serviceItemsMapper.selectOneByExample(example);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.com.glsx.scrm.equity.mapper.AutoCreateGoodsMappingMapper">
<resultMap id="BaseResultMap" type="cn.com.glsx.scrm.equity.model.AutoCreateGoodsMapping">
<id column="id" property="id"/>
<result column="spu_id" property="spuId"/>
<result column="old_service_code" property="oldServiceCode"/>
<result column="new_service_code" property="newServiceCode"/>
<result column="sku_id" property="skuId"/>
<result column="old_config_id" property="oldConfigId"/>
<result column="new_config_id" property="newConfigId"/>
<result column="deleted_flag" property="deletedFlag"/>
<result column="process_status" property="processStatus"/>
<result column="fail_reason" property="failReason"/>
<result column="created_by" property="createdBy"/>
<result column="created_date" property="createdDate"/>
<result column="updated_by" property="updatedBy"/>
<result column="updated_date" property="updatedDate"/>
</resultMap>
<sql id="Base_Column_List">
id, spu_id, old_service_code, new_service_code, sku_id, old_config_id, new_config_id,
deleted_flag, process_status, fail_reason, created_by, created_date, updated_by, updated_date
</sql>
<!-- 查询待处理的映射记录(按旧服务编码去重,用于分组处理) -->
<select id="listPendingRecords" resultMap="BaseResultMap">
SELECT DISTINCT old_service_code
FROM auto_create_goods_mapping
WHERE deleted_flag = 'N'
AND process_status = 0
ORDER BY id ASC
</select>
<!-- 查询指定旧服务编码下待处理的配置映射记录 -->
<select id="listPendingByOldServiceCode" resultMap="BaseResultMap">
SELECT <include refid="Base_Column_List"/>
FROM auto_create_goods_mapping
WHERE deleted_flag = 'N'
AND process_status = 0
AND old_service_code = #{oldServiceCode}
ORDER BY id ASC
</select>
<!-- 更新映射记录的新服务编码和新配置id -->
<update id="updateNewCodeAndConfigId">
UPDATE auto_create_goods_mapping
SET new_service_code = #{newServiceCode},
process_status = #{processStatus},
fail_reason = #{failReason},
updated_by = #{updatedBy},
updated_date = #{updatedDate}
WHERE id = #{id}
</update>
</mapper>
......@@ -50,6 +50,7 @@
<foreach collection="list" item="item" open="" close="" separator=";">
update extend_item_specification_config
<set>
service_code = #{item.serviceCode},
specification_data = #{item.specificationData},
specification_name = #{item.specificationName},
specification_type = #{item.specificationType},
......
package cn.com.glsx.scrm.equity.job;
import cn.com.glsx.scrm.equity.service.AutoCreateGoodsMappingService;
import cn.com.glsx.scrm.equity.service.BaseServiceTest;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
public class AutoCreateGoodsMappingServiceJobTest extends BaseServiceTest {
@Autowired
private AutoCreateGoodsMappingService autoCreateGoodsMappingService;
@Test
public void test() {
autoCreateGoodsMappingService.processAutoCreateGoods();
}
}
  • @wangxw1
    commented
    Owner

    一、关键问题与优化建议,如果必要,给出代码示例(仅限 Top 3)

    1. 功能正确性:SQL 语法错误与 ResultMap 映射不匹配

    • 问题描述:在 AutoCreateGoodsMappingMapper.xml 的 listPendingRecords 方法中,SQL 语句为 SELECT DISTINCT old_service_code ... ORDER BY id ASC。在 SQL 标准以及严格模式的数据库(如 MySQL、PostgreSQL)中,当使用 SELECT DISTINCT 时,ORDER BY 的字段必须出现在 SELECT 列表中,否则会抛出语法错误。此外,查询仅返回单列,却使用了包含所有字段的 BaseResultMap 进行映射。
    • 影响分析:定时任务执行到该查询时,极大概率会直接抛出 SQL 语法异常,导致任务完全阻断无法运行。
    • 优化建议:修改返回类型为 String,并使用 GROUP BY 替代 DISTINCT 以兼容排序需求。 xml <!-- Mapper XML 建议修改为 --> <select id="listPendingRecords" resultType="java.lang.String"> SELECT old_service_code FROM auto_create_goods_mapping WHERE deleted_flag = 'N' AND process_status = 0 GROUP BY old_service_code ORDER BY MIN(id) ASC </select> 同时同步修改 Java 层 Mapper 接口及 Service 调用的接收类型为 List<String>。

    2. 健壮性:预计算服务编码存在严重并发与一致性风险,且缺乏事务控制

    • 问题描述:
      1. processServiceCodeGroup 方法通过 getNextExtendServiceCode 提前查询并计算出 newServiceCode,然后调用 insertOrUpdateExtend,并假设其内部生成的编码与提前计算的完全一致。
      2. 核心数据处理方法 processServiceCodeGroup 涉及多次写操作(插入服务、更新映射表),但未添加 @Transactional 事务控制。
      3. AutoCreateGoodsJob 配置了 ElasticJob,但 execute 中未根据分片项(shardingContext)过滤数据,多实例部署时会全量并发执行。
    • 影响分析:多实例并发执行时,预计算的编码极易被其他线程/实例抢占,导致 newServiceCode 与实际插入的编码不一致,进而使后续查询 newConfigs 失败抛出异常。由于缺乏事务控制,异常发生后已插入的服务项目数据不会回滚,产生脏数据,且外层将其状态标记为失败,下次重试会继续引发数据错乱。
    • 优化建议:
      1. 废弃预计算编码逻辑。改造 insertOrUpdateExtend 方法,使其在创建成功后将生成的新编码通过 DTO 回填,或直接返回新编码。
      2. 为 processServiceCodeGroup 方法添加 @Transactional(rollbackFor = Exception.class) 注解。
      3. 在 listPendingRecords 查询中加入 ElasticJob 的分片参数过滤,避免多实例争抢同一批数据。

    3. 安全性与潜在风险:Dubbo 服务提供者 Remote 接口已有请求参数变更

    • 问题描述:在 rpc-scrm-equity-api 包下的 ServiceItemsExtendCreatedDTO 中新增了基本类型字段 private boolean skuCategoryMigration;。
    • 影响分析:根据工程安全规范,Dubbo 服务提供者 Remote 接口中的已有请求参数变更视为危险实现。直接在已有 DTO 中增加字段,当消费者与提供者版本发布存在时间差时,可能引发反序列化异常;且新增的 boolean 默认值为 false,可能意外改变旧版本消费者的业务逻辑走向。
    • 优化建议: 评估该字段增加的兼容性影响。如果必须增加,需确保消费者端同步更新,并建议使用包装类型 Boolean 以防范默认值带来的逻辑歧义。在接口升级的最佳实践中,建议通过新增版本号(version)或提供新的接口方法来避免直接修改已被广泛调用的已有 DTO。

    二、评分明细

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

      • 扣分项:XML 中 SELECT DISTINCT 结合未查询列的 ORDER BY 会导致直接的 SQL 语法错误;预计算自增主键/编码存在极大的并发不一致风险;核心写入链路缺少事务控制。
    2. 安全性与潜在风险(20/30分):

      • 扣分项:在 API 包中直接修改已有 DTO,触发了“Dubbo 服务提供者 Remote 接口已有请求参数变更视为危险实现”的重要规则,存在兼容性隐患。
    3. 最佳实践与可维护性(15/20分):

      • 扣分项:AutoCreateGoodsMappingService 中存在大段被注释掉的无用代码(软删除逻辑),应直接删除以保持代码整洁;代码结构整体尚可,但职责划分可进一步解耦。
    4. 性能与资源利用(3/5分):

      • 扣分项:在 for 循环中单条执行 autoCreateGoodsMappingMapper.updateNewCodeAndConfigId,当映射记录较多时会导致频繁的数据库网络 I/O,建议采用 MyBatis 的批量更新(<foreach>)。
    5. 提交信息质量(4/5分):

      • 评分理由:提交信息 "feat:新增产品自动创建定时任务" 格式符合规范且说明了主要意图,但若能简要补充涉及的影响范围(如修改了哪些核心 DTO)会更有追溯价值。

    总分:67分

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