Commit 2bdb4def by 林冲

Merge branch 'v5.8.1' into 'master'

上线合并

See merge request !5
2 parents a06654b1 17364fb8
Showing 21 changed files with 676 additions and 129 deletions
...@@ -7,7 +7,7 @@ ...@@ -7,7 +7,7 @@
</parent> </parent>
<groupId>cn.com.glsx.scrm</groupId> <groupId>cn.com.glsx.scrm</groupId>
<artifactId>rpc-scrm-equity-api</artifactId> <artifactId>rpc-scrm-equity-api</artifactId>
<version>5.8.0-SNAPSHOT</version> <version>5.8.1-SNAPSHOT</version>
<name>rpc-scrm-equity-api</name> <name>rpc-scrm-equity-api</name>
<properties> <properties>
<deploy.scanPackage>cn.com.glsx.scrm.equity.remote</deploy.scanPackage> <deploy.scanPackage>cn.com.glsx.scrm.equity.remote</deploy.scanPackage>
...@@ -48,7 +48,7 @@ ...@@ -48,7 +48,7 @@
<dependency> <dependency>
<groupId>cn.com.glsx.scrm</groupId> <groupId>cn.com.glsx.scrm</groupId>
<artifactId>rpc-scrm-equity-api</artifactId> <artifactId>rpc-scrm-equity-api</artifactId>
<version>5.8.0-SNAPSHOT</version> <version>5.8.1-SNAPSHOT</version>
</dependency> </dependency>
</dependencies> </dependencies>
</plugin> </plugin>
......
package cn.com.glsx.scrm.equity.dto.service;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.ToString;
import java.io.Serializable;
/**
* 退单校验请求参数
*/
@Data
@ToString
public class ChargeBackCheckDTO implements Serializable {
/**
* 车架号
*/
@ApiModelProperty(name = "vin", notes = "车架号", required = true)
private String vin;
/**
* 请求来源,对应 ChargeBackSourceEnum 的值
*/
@ApiModelProperty(name = "source", notes = "请求来源:1-嘀加智慧门店,2-scrm运营版,3-生意助手员工版", required = true)
private Integer source;
/**
* 登录账号手机号,用于超管判断
*/
private String loginAccount;
}
package cn.com.glsx.scrm.equity.dto.service;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.ToString;
import java.io.Serializable;
/**
* 退单校验结果
*/
@Data
@ToString
public class ChargeBackCheckResultDTO implements Serializable {
/**
* 是否允许退单
*/
@ApiModelProperty(name = "allowChargeBack", notes = "是否允许退单,true-是,false-否")
private Boolean allowChargeBack;
/**
* 不允许时的提示信息
*/
@ApiModelProperty(name = "message", notes = "不允许时的提示信息")
private String message;
public static ChargeBackCheckResultDTO success() {
ChargeBackCheckResultDTO result = new ChargeBackCheckResultDTO();
result.setAllowChargeBack(true);
return result;
}
public static ChargeBackCheckResultDTO fail(String message) {
ChargeBackCheckResultDTO result = new ChargeBackCheckResultDTO();
result.setAllowChargeBack(false);
result.setMessage(message);
return result;
}
}
...@@ -87,4 +87,9 @@ public class QueryServicePackageOrderRequestDTO implements Serializable { ...@@ -87,4 +87,9 @@ public class QueryServicePackageOrderRequestDTO implements Serializable {
private List<String> spuNameList; private List<String> spuNameList;
/**
* 订单类型(1:正常订单,2:打折策略,3:买赠策略,4:冲量活动,5:组合付款,6:内部结算)
*/
private Integer orderType;
} }
...@@ -185,6 +185,12 @@ public class ServiceEquityOrderDTO implements Serializable { ...@@ -185,6 +185,12 @@ public class ServiceEquityOrderDTO implements Serializable {
private String rearTireUrl; private String rearTireUrl;
/** /**
* 订单类型(1:正常订单,2:打折策略,3:买赠策略,4:冲量活动,5:组合付款,6:内部结算)
*/
@ApiModelProperty(name = "orderType", notes = "订单类型(1:正常订单,2:打折策略,3:买赠策略,4:冲量活动,5:组合付款,6:内部结算)")
private Integer orderType;
/**
* 数据来源 * 数据来源
*/ */
private String dataSource; private String dataSource;
......
package cn.com.glsx.scrm.equity.enums;
/**
* 退单校验请求来源枚举
*/
public enum ChargeBackSourceEnum {
DJ_SMART_STORE(1, "嘀加智慧门店"),
SCRM_OSS(2, "scrm运营版"),
BUSINESS_ASSISTANT(3, "生意助手员工版");
private Integer value;
private String displayName;
ChargeBackSourceEnum(Integer value, String displayName) {
this.value = value;
this.displayName = displayName;
}
public Integer getValue() {
return value;
}
public String getDisplayName() {
return displayName;
}
public static ChargeBackSourceEnum get(Integer value) {
for (ChargeBackSourceEnum e : values()) {
if (e.getValue().equals(value)) {
return e;
}
}
return null;
}
}
package cn.com.glsx.scrm.equity.enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* @Author pangst
* @Version 1.0
* @Description: 订单类型:1:正常订单,2:打折策略,3:买赠策略,4:冲量活动,5:组合付款,6:内部结算
* @Date 2026/1/8
*/
@Getter
@AllArgsConstructor
public enum DjOrderTypeEnum {
//订单类型:1:正常订单,2:打折策略,3:买赠策略,4:冲量活动,5:组合付款,6-内部结算
NORMAL(1, "正常订单"),
DISCOUNT(2, "打折策略"),
BUY_GIFT(3, "买赠策略"),
VOLUME_ACTIVITY(4, "冲量活动"),
COMBINATION_PAYMENT(5, "组合付款"),
INTERNAL_SETTLEMENT(6, "内部结算");
private Integer code;
private String msg;
public static DjOrderTypeEnum getByValue(Integer value){
if (value != null) {
for (DjOrderTypeEnum temp : DjOrderTypeEnum.values()) {
if (temp.getCode() == value.intValue()) {
return temp;
}
}
}
return null;
}
}
...@@ -33,6 +33,12 @@ public class ServiceEquityOrder implements Serializable { ...@@ -33,6 +33,12 @@ public class ServiceEquityOrder implements Serializable {
private String contractNo; private String contractNo;
/** /**
* 订单类型(1:正常订单,2:打折策略,3:买赠策略,4:冲量活动,5:组合付款,6:内部结算)
*/
@Column(name = "order_type")
private Integer orderType;
/**
* 主合同号 * 主合同号
*/ */
@Column(name = "main_contract_no") @Column(name = "main_contract_no")
...@@ -527,6 +533,14 @@ public class ServiceEquityOrder implements Serializable { ...@@ -527,6 +533,14 @@ public class ServiceEquityOrder implements Serializable {
this.contractNo = contractNo == null ? null : contractNo.trim(); this.contractNo = contractNo == null ? null : contractNo.trim();
} }
public Integer getOrderType() {
return orderType;
}
public void setOrderType(Integer orderType) {
this.orderType = orderType;
}
public void setMainContractNo(String mainContractNo) { public void setMainContractNo(String mainContractNo) {
this.mainContractNo = mainContractNo; this.mainContractNo = mainContractNo;
} }
......
...@@ -152,4 +152,9 @@ public interface ChannelServiceEquityOrderRemote { ...@@ -152,4 +152,9 @@ public interface ChannelServiceEquityOrderRemote {
@ApiResponse("影响条数") @ApiResponse("影响条数")
RpcResponse<Integer> updateVehicleVinFromDJ(VdEquityVehicleDTO vdEquityVehicleDTO); RpcResponse<Integer> updateVehicleVinFromDJ(VdEquityVehicleDTO vdEquityVehicleDTO);
@ApiMethod("校验合同是否允许退单")
@ApiParams({@ApiParam(name = "chargeBackCheckDTO", notes = "退单校验参数", dataType = ApiParam.DataTypeEnum.OBJECT, required = true)})
@ApiResponse("校验结果")
RpcResponse<ChargeBackCheckResultDTO> checkChargeBackAllowed(ChargeBackCheckDTO chargeBackCheckDTO);
} }
...@@ -14,7 +14,7 @@ ...@@ -14,7 +14,7 @@
<dependency> <dependency>
<groupId>cn.com.glsx.scrm</groupId> <groupId>cn.com.glsx.scrm</groupId>
<artifactId>rpc-scrm-equity-api</artifactId> <artifactId>rpc-scrm-equity-api</artifactId>
<version>5.8.0-SNAPSHOT</version> <version>5.8.1-SNAPSHOT</version>
<exclusions> <exclusions>
<exclusion> <exclusion>
<artifactId>bcprov-jdk15on</artifactId> <artifactId>bcprov-jdk15on</artifactId>
...@@ -217,7 +217,7 @@ ...@@ -217,7 +217,7 @@
<dependency> <dependency>
<groupId>cn.com.glsx.dj</groupId> <groupId>cn.com.glsx.dj</groupId>
<artifactId>rpc-dj-smartcarlife-api</artifactId> <artifactId>rpc-dj-smartcarlife-api</artifactId>
<version>5.8.0-SNAPSHOT</version> <version>5.8.1-SNAPSHOT</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.oreframework.boot</groupId> <groupId>org.oreframework.boot</groupId>
......
...@@ -13,7 +13,7 @@ import org.springframework.beans.factory.annotation.Autowired; ...@@ -13,7 +13,7 @@ import org.springframework.beans.factory.annotation.Autowired;
/** /**
* @author hedong * @author hedong
*/ */
@ElasticJobConf(name = "EquityDayReportJob", cron = "0 30 22 * * ? ", description = "产值统计日报重算任务", overwrite = true) @ElasticJobConf(name = "EquityDayReportJob", cron = "0 30 2 * * ? ", description = "产值统计日报重算任务", overwrite = true)
public class EquityDayReportJob implements SimpleJob { public class EquityDayReportJob implements SimpleJob {
private static final Logger LOGGER = LoggerFactory.getLogger(EquityDayReportJob.class); private static final Logger LOGGER = LoggerFactory.getLogger(EquityDayReportJob.class);
@Autowired @Autowired
......
...@@ -73,4 +73,6 @@ public interface ServiceEquityClaimsMapper extends OreMapper<ServiceEquityClaims ...@@ -73,4 +73,6 @@ public interface ServiceEquityClaimsMapper extends OreMapper<ServiceEquityClaims
List<MiniServiceEquityClaimsResponseDTO> listClaimsRecordByContractNo(@Param("contractNo") String contractNo); List<MiniServiceEquityClaimsResponseDTO> listClaimsRecordByContractNo(@Param("contractNo") String contractNo);
MiniServiceEquityClaimsResponseDTO getClaimsRecordDetail(@Param("writeOffCode") Integer writeOffCode); MiniServiceEquityClaimsResponseDTO getClaimsRecordDetail(@Param("writeOffCode") Integer writeOffCode);
int countByVin(@Param("vin") String vin);
} }
...@@ -274,4 +274,14 @@ public class ChannelServiceEquityOrderRemoteImpl implements ChannelServiceEquity ...@@ -274,4 +274,14 @@ public class ChannelServiceEquityOrderRemoteImpl implements ChannelServiceEquity
return RpcResponse.error(DefaultErrorEnum.DATABASE_ERROR, e.getMessage()); return RpcResponse.error(DefaultErrorEnum.DATABASE_ERROR, e.getMessage());
} }
} }
@Override
public RpcResponse<ChargeBackCheckResultDTO> checkChargeBackAllowed(ChargeBackCheckDTO chargeBackCheckDTO) {
try {
return RpcResponse.success(channelServiceEquityOrderService.checkChargeBackAllowed(chargeBackCheckDTO));
} catch (RpcServiceException e) {
log.error("checkChargeBackAllowed error:{}", e);
return RpcResponse.error(e);
}
}
} }
...@@ -15,6 +15,7 @@ import cn.com.glsx.scrm.equity.dto.service.*; ...@@ -15,6 +15,7 @@ import cn.com.glsx.scrm.equity.dto.service.*;
import cn.com.glsx.scrm.equity.dto.vd.VdEquityVehicleDTO; import cn.com.glsx.scrm.equity.dto.vd.VdEquityVehicleDTO;
import cn.com.glsx.scrm.equity.enums.*; import cn.com.glsx.scrm.equity.enums.*;
import cn.com.glsx.scrm.equity.manager.DeviceCheckManager; import cn.com.glsx.scrm.equity.manager.DeviceCheckManager;
import cn.com.glsx.scrm.equity.mapper.ServiceEquityClaimsMapper;
import cn.com.glsx.scrm.equity.mapper.ServiceEquityOrderMapper; import cn.com.glsx.scrm.equity.mapper.ServiceEquityOrderMapper;
import cn.com.glsx.scrm.equity.mapper.ServiceItemsAttachmentMapper; import cn.com.glsx.scrm.equity.mapper.ServiceItemsAttachmentMapper;
import cn.com.glsx.scrm.equity.model.*; import cn.com.glsx.scrm.equity.model.*;
...@@ -100,6 +101,8 @@ public class ChannelServiceEquityOrderService { ...@@ -100,6 +101,8 @@ public class ChannelServiceEquityOrderService {
private ExtendItemSpecificationConfigSnapshotService extendItemSpecificationConfigSnapshotService; private ExtendItemSpecificationConfigSnapshotService extendItemSpecificationConfigSnapshotService;
@Autowired @Autowired
private OrderPackageVehicleSeriesConfigSnapshotService orderPackageVehicleSeriesConfigSnapshotService; private OrderPackageVehicleSeriesConfigSnapshotService orderPackageVehicleSeriesConfigSnapshotService;
@Resource
private ServiceEquityClaimsMapper serviceEquityClaimsMapper;
/** /**
* 渠道权益提单草稿 * 渠道权益提单草稿
...@@ -311,6 +314,10 @@ public class ChannelServiceEquityOrderService { ...@@ -311,6 +314,10 @@ public class ChannelServiceEquityOrderService {
serviceEquityOrder.setBuyCarType(BuyCarTypeEnum.LOAN.getValue()); serviceEquityOrder.setBuyCarType(BuyCarTypeEnum.LOAN.getValue());
} }
if (old == null) { if (old == null) {
//设置默认订单类型
if (serviceEquityOrder.getOrderType() == null) {
serviceEquityOrder.setOrderType(DjOrderTypeEnum.NORMAL.getCode());
}
serviceEquityOrder.setCreatedBy(serviceEquityOrder.getUpdatedBy()); serviceEquityOrder.setCreatedBy(serviceEquityOrder.getUpdatedBy());
serviceEquityOrder.setCreatedDate(now); serviceEquityOrder.setCreatedDate(now);
serviceEquityOrder.setDataPerfection(ServicePerfectionEnum.NOT_COMPLETE.getValue()); serviceEquityOrder.setDataPerfection(ServicePerfectionEnum.NOT_COMPLETE.getValue());
...@@ -1198,4 +1205,38 @@ public class ChannelServiceEquityOrderService { ...@@ -1198,4 +1205,38 @@ public class ChannelServiceEquityOrderService {
return vehicleService.updateVinByContractNoList(vdEquityVehicleDTO.getContractNoList(), return vehicleService.updateVinByContractNoList(vdEquityVehicleDTO.getContractNoList(),
vdEquityVehicleDTO.getVin(), vdEquityVehicleDTO.getUpdatedBy()); vdEquityVehicleDTO.getVin(), vdEquityVehicleDTO.getUpdatedBy());
} }
/**
* 校验合同是否允许退单
*
* @param dto 退单校验参数
* @return 校验结果
*/
public ChargeBackCheckResultDTO checkChargeBackAllowed(ChargeBackCheckDTO dto) {
RpcAssert.assertNotEmpty(dto.getVin(), ServiceEquityErrorEnum.SERVICE_EQUITY_DEFAULT_ERROR, "车架号不能为空");
RpcAssert.assertNotNull(dto.getSource(), ServiceEquityErrorEnum.SERVICE_EQUITY_DEFAULT_ERROR, "请求来源不能为空");
// SCRM运营版超管账号跳过校验
if (ChargeBackSourceEnum.SCRM_OSS.getValue().equals(dto.getSource())) {
String superAdminPhones = env.getProperty(
"scrm.service.equity.charge.back.super.admin.phones",
"15007612682,15019903579,13333970369,13632814608,18476788882");
if (StringUtils.isNotBlank(dto.getLoginAccount())
&& Arrays.asList(superAdminPhones.split(",")).contains(dto.getLoginAccount().trim())) {
log.info("超管账号[{}]跳过退单核赔校验", dto.getLoginAccount());
return ChargeBackCheckResultDTO.success();
}
}
// 通过车架号查询核赔记录
int claimsCount = serviceEquityClaimsMapper.countByVin(dto.getVin());
if (claimsCount > 0) {
String notice = env.getProperty(
"scrm.service.equity.charge.back.claims.notice",
"由于您的车辆有理赔案件处理当中,请先联系权益服务官18938907441进行处理");
return ChargeBackCheckResultDTO.fail(notice);
}
return ChargeBackCheckResultDTO.success();
}
} }
...@@ -576,6 +576,9 @@ public class ServiceEquityOrderService { ...@@ -576,6 +576,9 @@ public class ServiceEquityOrderService {
serviceEquityOrder.setInsuranceType(ServiceEquityInsuranceType.get(serviceEquityOrder.getInsuranceType()).getValue()); serviceEquityOrder.setInsuranceType(ServiceEquityInsuranceType.get(serviceEquityOrder.getInsuranceType()).getValue());
} }
if (old == null) { if (old == null) {
if (serviceEquityOrder.getOrderType() == null) {
serviceEquityOrder.setOrderType(DjOrderTypeEnum.NORMAL.getCode());
}
serviceEquityOrder.setCreatedBy(serviceEquityOrder.getUpdatedBy()); serviceEquityOrder.setCreatedBy(serviceEquityOrder.getUpdatedBy());
serviceEquityOrder.setCreatedDate(now); serviceEquityOrder.setCreatedDate(now);
serviceEquityOrder.setDataPerfection(ServicePerfectionEnum.NOT_COMPLETE.getValue()); serviceEquityOrder.setDataPerfection(ServicePerfectionEnum.NOT_COMPLETE.getValue());
......
...@@ -386,6 +386,9 @@ public class ServiceEquitySyncDataFromDjService { ...@@ -386,6 +386,9 @@ public class ServiceEquitySyncDataFromDjService {
//新增或更新售前服务订单 //新增或更新售前服务订单
ServiceEquityOrder oldServiceEquityOrder = serviceEquityOrderService.getByContractNo(contractNo); ServiceEquityOrder oldServiceEquityOrder = serviceEquityOrderService.getByContractNo(contractNo);
if (oldServiceEquityOrder == null) { if (oldServiceEquityOrder == null) {
if (serviceEquityOrder.getOrderType() == null) {
serviceEquityOrder.setOrderType(DjOrderTypeEnum.NORMAL.getCode());
}
serviceEquityOrderMapper.insertUseGeneratedKeys(serviceEquityOrder); serviceEquityOrderMapper.insertUseGeneratedKeys(serviceEquityOrder);
} else { } else {
serviceEquityOrder.setId(oldServiceEquityOrder.getId()); serviceEquityOrder.setId(oldServiceEquityOrder.getId());
......
...@@ -35,7 +35,7 @@ import com.github.pagehelper.PageHelper; ...@@ -35,7 +35,7 @@ import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.oreframework.distribute.lock.annotation.GlsxDistributeLockable; import cn.com.glsx.scrm.equity.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy; import org.springframework.context.annotation.Lazy;
import org.springframework.core.env.Environment; import org.springframework.core.env.Environment;
...@@ -98,6 +98,13 @@ public class ServiceMerchantConfigService { ...@@ -98,6 +98,13 @@ public class ServiceMerchantConfigService {
@Autowired @Autowired
private TaskExecutor taskExecutor; private TaskExecutor taskExecutor;
@Autowired
private RedisUtil redisUtil;
@Autowired
@Lazy
private ServiceMerchantConfigService self;
public RpcPagination<ServiceMerchantConfig> getPaginationList(RpcPagination<ServiceMerchantConfigDTO> rpcPagination) { public RpcPagination<ServiceMerchantConfig> getPaginationList(RpcPagination<ServiceMerchantConfigDTO> rpcPagination) {
try { try {
Page<ServiceMerchantConfig> page = PageHelper.startPage(rpcPagination.getPageNum(), rpcPagination.getPageSize()); Page<ServiceMerchantConfig> page = PageHelper.startPage(rpcPagination.getPageNum(), rpcPagination.getPageSize());
...@@ -257,49 +264,20 @@ public class ServiceMerchantConfigService { ...@@ -257,49 +264,20 @@ public class ServiceMerchantConfigService {
* @param request * @param request
* @return * @return
*/ */
@GlsxDistributeLockable(name = "ServiceMerchantConfigService.addMerchantConfigWithGood", timeoutException = RpcServiceException.class, time = 120)
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = {RpcServiceException.class})
public Boolean addMerchantConfigWithGood(EquityMerchantConfigDTO request) { public Boolean addMerchantConfigWithGood(EquityMerchantConfigDTO request) {
try { try {
log.info("同步商品套餐信息参数[{}]", JSON.toJSONString(request)); log.info("同步商品套餐信息参数[{}]", JSON.toJSONString(request));
checkGoodParams(request); checkGoodParams(request);
//1.封装套餐数据,保存套餐,建立关联关系
List<ServicePackage> servicePackageList = servicePackageService.createPackageWithGood(request); // 阶段1: 商品级锁 — 创建套餐
//2.封装门店配置数据 List<ServicePackage> servicePackageList = createPackageWithGoodLocked(request);
List<Integer> merchantIds = request.getMerchantIds();
Example merchantConfigExample = new Example(ServiceMerchantConfig.class); // 阶段2: 商户级锁 — 门店配置CRUD + 门店-套餐关联
merchantConfigExample.createCriteria().andEqualTo("deletedFlag", DeleteFlagEnum.N.getValue()) batchInsertMerchantConfigAndRelations(request, servicePackageList);
.andIn("merchantId", merchantIds);
List<ServiceMerchantConfig> oldMerchantConfigList = serviceMerchantConfigMapper.selectByExample(merchantConfigExample); // 阶段3: 无锁幂等操作
if (CollectionUtils.isNotEmpty(oldMerchantConfigList)) {
List<Integer> oldMerchantList = oldMerchantConfigList.stream().map(x -> x.getMerchantId()).collect(Collectors.toList());
//存在旧数据, 新旧分离, 将 已开通状态,二维码地址不空的商户筛选出来,无需重新构建
List<Integer> ignoreMerchantList = oldMerchantConfigList.stream().filter(x -> {
return MerchantPakcageConfigStatusEnum.OPEN.getValue().equals(x.getOpenFlag()) && StringUtils.isNotBlank(x.getQrcodeUrl());
}).map(x -> x.getMerchantId()).collect(Collectors.toList());
if (CollectionUtils.isNotEmpty(ignoreMerchantList)) {
//筛选需要删除的商户id
List<Integer> deleteMerchantList = oldMerchantList.stream().filter(x -> !ignoreMerchantList.contains(x)).collect(Collectors.toList());
//删除商户配置
deleteMerchantConfig(deleteMerchantList);
//筛选最终需要重新构建的商户id
List<Integer> renewList = merchantIds.stream().filter(x -> !ignoreMerchantList.contains(x)).collect(Collectors.toList());
batchInsertMerchantConfig(renewList, request);
} else {
//全部需要重新构建
deleteMerchantConfig(oldMerchantList);
batchInsertMerchantConfig(merchantIds, request);
}
} else {//全部需要重新构建
batchInsertMerchantConfig(merchantIds, request);
}
//门店-套餐关联关系,不要瞎删,会影响到历史数据
serviceMerchantPackageConfigService.batchInsertConfig(request, servicePackageList);
//保存升级商品-基础sku产品关联关系
skuPackageRelationService.saveSkuPackageRelation(request); skuPackageRelationService.saveSkuPackageRelation(request);
//处理合同模板配置
serviceContractTemplateConfigService.handlerContractTemplate(request, servicePackageList); serviceContractTemplateConfigService.handlerContractTemplate(request, servicePackageList);
//更新订单任务商品上架状态
taskExecutor.execute(() -> { taskExecutor.execute(() -> {
updateOrderTaskGoodsShelfStatus(request); updateOrderTaskGoodsShelfStatus(request);
}); });
...@@ -313,6 +291,180 @@ public class ServiceMerchantConfigService { ...@@ -313,6 +291,180 @@ public class ServiceMerchantConfigService {
} }
} }
/**
* 商品级锁保护 — 按goodId升序加锁后创建套餐,防止并发重复插入
*/
private List<ServicePackage> createPackageWithGoodLocked(EquityMerchantConfigDTO request) {
List<Integer> sortedGoodIds = request.getPackageConfigList().stream()
.map(EquityPackageConfigDTO::getGoodId)
.distinct().sorted().collect(Collectors.toList());
List<String> acquiredLocks = new ArrayList<>();
try {
for (Integer goodId : sortedGoodIds) {
String lockKey = "addMerchantConfigWithGood:package:" + goodId;
if (!redisUtil.lockSpin(lockKey, 30000, 100)) {
throw new RpcServiceException(DefaultErrorEnum.SERVER_ERROR, "商品[" + goodId + "]正在同步中,请稍后重试");
}
acquiredLocks.add(lockKey);
}
return servicePackageService.createPackageWithGood(request);
} finally {
for (String lockKey : acquiredLocks) {
redisUtil.deleteLock(lockKey);
}
}
}
/**
* 商户级锁 — 预查询商户信息(锁外),再逐商户加锁,锁内通过事务执行配置删除、插入及门店-套餐关联写入
*/
private void batchInsertMerchantConfigAndRelations(
EquityMerchantConfigDTO request, List<ServicePackage> servicePackageList) {
List<Integer> merchantIds = request.getMerchantIds();
if (CollectionUtils.isEmpty(merchantIds)) {
return;
}
List<Integer> sortedMerchantIds = merchantIds.stream().sorted().collect(Collectors.toList());
// 锁外预查询商户信息(RPC,慢IO)
String merchantNoStr = StringUtils.join(sortedMerchantIds, ",");
FindMerchantListRequest merchantParam = new FindMerchantListRequest();
merchantParam.setMerchantNoStr(merchantNoStr);
RpcResponse<List<MerchantRopResponse>> merchantListRes = merchantRemote.findMerchantList(merchantParam);
if (merchantListRes.isFailed()) {
log.error("同步商品套餐,查询商户信息异常[{}]", merchantListRes.getMessage());
throw new RpcServiceException(merchantListRes.getError(), merchantListRes.getMessage());
}
List<MerchantRopResponse> merchantList = merchantListRes.getResult();
if (CollectionUtils.isEmpty(merchantList)) {
log.info("同步商品套餐,未查询到商户信息,商户号列表[{}]", JSON.toJSONString(merchantNoStr));
throw new RpcServiceException(DefaultErrorEnum.DATA_NULL, "商户数据为空!");
}
Map<String, MerchantRopResponse> merchantMap = merchantList.stream()
.collect(Collectors.toMap(MerchantRopResponse::getMerchantNo, vo -> vo, (v1, v2) -> v2));
// key:goodId -> packageConfig
Map<Integer, EquityPackageConfigDTO> goodIdPackageMap = request.getPackageConfigList().stream()
.collect(Collectors.toMap(EquityPackageConfigDTO::getGoodId, vo -> vo, (v1, v2) -> v2));
for (Integer merchantId : sortedMerchantIds) {
String lockKey = "addMerchantConfigWithGood:merchant:" + merchantId;
try {
if (!redisUtil.lockSpin(lockKey, 30000, 100)) {
throw new RpcServiceException(DefaultErrorEnum.SERVER_ERROR, "门店[" + merchantId + "]正在同步中,请稍后重试");
}
// 锁内执行事务,确保锁覆盖事务提交
self.doMerchantConfigInTransaction(merchantId, merchantMap, goodIdPackageMap, servicePackageList, request);
} finally {
redisUtil.deleteLock(lockKey);
}
}
}
/**
* 单商户事务操作:门店配置删旧建新 + 门店-套餐关联写入
* 必须通过代理对象调用以确保事务生效
*/
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
public void doMerchantConfigInTransaction(
Integer merchantId,
Map<String, MerchantRopResponse> merchantMap,
Map<Integer, EquityPackageConfigDTO> goodIdPackageMap,
List<ServicePackage> servicePackageList,
EquityMerchantConfigDTO request) {
String createdBy = request.getCreatedBy();
Date createdDate = request.getCreatedDate();
// 1. 处理门店配置:查询旧配置,已开通+有二维码的跳过,否则删旧建新
Example merchantConfigExample = new Example(ServiceMerchantConfig.class);
merchantConfigExample.createCriteria().andEqualTo("deletedFlag", DeleteFlagEnum.N.getValue())
.andEqualTo("merchantId", merchantId);
List<ServiceMerchantConfig> oldConfigList = serviceMerchantConfigMapper.selectByExample(merchantConfigExample);
ServiceMerchantConfig oldConfig = CollectionUtils.isNotEmpty(oldConfigList) ? oldConfigList.get(0) : null;
boolean needRebuild = true;
if (oldConfig != null
&& MerchantPakcageConfigStatusEnum.OPEN.getValue().equals(oldConfig.getOpenFlag())
&& StringUtils.isNotBlank(oldConfig.getQrcodeUrl())) {
needRebuild = false;
}
if (needRebuild) {
// 删除旧配置
if (oldConfig != null) {
Example deleteExample = new Example(ServiceMerchantConfig.class);
deleteExample.createCriteria().andEqualTo("merchantId", merchantId);
serviceMerchantConfigMapper.deleteByExample(deleteExample);
}
// 插入新配置
MerchantRopResponse merchantResponse = merchantMap.get(String.valueOf(merchantId));
if (merchantResponse == null) {
log.info("商品套餐同步,该商户号[{}]查询不到商户信息", merchantId);
throw new RpcServiceException(DefaultErrorEnum.DATA_NOT_EXIST, "未查询到商户信息");
}
ServiceMerchantConfig merchantConfigDTO = new ServiceMerchantConfig();
merchantConfigDTO.setMerchantId(merchantId);
merchantConfigDTO.setMerchantName(merchantResponse.getMerchantName());
merchantConfigDTO.setServiceHotline(merchantResponse.getMerchantLegalPersonPhone());
merchantConfigDTO.setSap(merchantResponse.getSapCode());
merchantConfigDTO.setChannelType(merchantResponse.getChannelType());
merchantConfigDTO.setQrcodeStatus(0);
merchantConfigDTO.setCodeType(1);
merchantConfigDTO.setCheckPosition(0);
merchantConfigDTO.setOpenCostPrice(0);
merchantConfigDTO.setOpenFlag(MerchantPakcageConfigStatusEnum.OPEN.getValue());
merchantConfigDTO.setOpenDate(createdDate);
merchantConfigDTO.setCreatedBy(createdBy);
merchantConfigDTO.setCreatedDate(createdDate);
merchantConfigDTO.setUpdatedDate(createdDate);
merchantConfigDTO.setUpdatedBy(createdBy);
merchantConfigDTO.setDeletedFlag(DeleteFlagEnum.N.getValue());
merchantConfigDTO.setSaleMode(MerchantSaleModeEnum.MODE_1.getMode());
merchantConfigDTO.setContractSubjectType(1);
merchantConfigDTO.setContractSubjectName(env.getProperty("equity.contract.print.salemode1.serviceSubject"));
merchantConfigDTO.setContractLogoUrl(env.getProperty("equity.contract.print.salemode1.logoUrl"));
merchantConfigDTO.setContractSealUrl(env.getProperty("equity.contract.print.salemode1.url"));
List<ServiceMerchantConfig> configList = new ArrayList<>();
configList.add(merchantConfigDTO);
serviceMerchantConfigMapper.insertList(configList);
}
// 2. 处理门店-套餐关联:为该商户写入关联记录
List<ServiceMerchantPackageConfig> onList = new ArrayList<>();
List<ServiceMerchantPackageConfig> offList = new ArrayList<>();
for (ServicePackage servicePackage : servicePackageList) {
ServiceMerchantPackageConfig config = new ServiceMerchantPackageConfig();
config.setCreatedBy(createdBy);
config.setCreatedDate(createdDate);
config.setUpdatedBy(createdBy);
config.setUpdatedDate(createdDate);
config.setDeletedFlag(DeleteFlagEnum.N.getValue());
config.setMerchantId(merchantId);
config.setPackageCode(servicePackage.getPackageCode());
config.setServicePeriod(servicePackage.getServicePeriod());
EquityPackageConfigDTO packageConfigDTO = goodIdPackageMap.get(servicePackage.getGoodId());
if (packageConfigDTO != null) {
config.setShelfStatus(packageConfigDTO.getShelfStatus());
if (packageConfigDTO.getCardFlag() == 1) {
config.setCardName("card");
}
if (PackageShelfStatus.ON_SHELF.getValue().equals(packageConfigDTO.getShelfStatus())) {
onList.add(config);
} else {
offList.add(config);
}
}
}
if (CollectionUtils.isNotEmpty(onList)) {
serviceMerchantPackageConfigMapper.insertList(onList);
}
if (CollectionUtils.isNotEmpty(offList)) {
serviceMerchantPackageConfigMapper.batchUpdateConfig(offList);
}
}
public void updateOrderTaskGoodsShelfStatus(EquityMerchantConfigDTO request) { public void updateOrderTaskGoodsShelfStatus(EquityMerchantConfigDTO request) {
log.info("商品套餐同步,开始批量更新订单任务商品上架状态"); log.info("商品套餐同步,开始批量更新订单任务商品上架状态");
List<EquityMerchantInfo> merchantList = request.getMerchantList(); List<EquityMerchantInfo> merchantList = request.getMerchantList();
...@@ -396,75 +548,6 @@ public class ServiceMerchantConfigService { ...@@ -396,75 +548,6 @@ public class ServiceMerchantConfigService {
} }
/** /**
* 批量添加商户配置
*
* @param merchantIds
* @param request
*/
private void batchInsertMerchantConfig(List<Integer> merchantIds, EquityMerchantConfigDTO request) {
if (CollectionUtils.isNotEmpty(merchantIds)) {
String createdBy = request.getCreatedBy();
Date createdDate = request.getCreatedDate();
List<ServiceMerchantConfig> configList = new ArrayList<>();
//批量查询商户信息
String merchantNoStr = StringUtils.join(merchantIds, ",");
FindMerchantListRequest merchantParam = new FindMerchantListRequest();
merchantParam.setMerchantNoStr(merchantNoStr);
RpcResponse<List<MerchantRopResponse>> merchantListRes = merchantRemote.findMerchantList(merchantParam);
if (merchantListRes.isFailed()) {
log.error("同步商品套餐,查询商户信息异常[{}]", merchantListRes.getMessage());
throw new RpcServiceException(merchantListRes.getError(), merchantListRes.getMessage());
}
List<MerchantRopResponse> merchantList = merchantListRes.getResult();
if (CollectionUtils.isEmpty(merchantList)) {
log.info("同步商品套餐,未查询到商户信息,商户号列表[{}}", JSON.toJSONString(merchantNoStr));
throw new RpcServiceException(DefaultErrorEnum.DATA_NULL, "商户数据为空!");
}
Map<String, MerchantRopResponse> merchantMap = merchantList.stream().collect(Collectors.toMap(MerchantRopResponse::getMerchantNo, vo -> vo, (v1, v2) -> v2));
//封装套餐,门店配置数据
merchantIds.stream().forEach(merchantId -> {
MerchantRopResponse merchantResponse = merchantMap.get(String.valueOf(merchantId));
if (merchantResponse != null) {
ServiceMerchantConfig merchantConfigDTO = new ServiceMerchantConfig();
merchantConfigDTO.setMerchantId(merchantId);
merchantConfigDTO.setMerchantName(merchantResponse.getMerchantName());
merchantConfigDTO.setServiceHotline(merchantResponse.getMerchantLegalPersonPhone());
merchantConfigDTO.setSap(merchantResponse.getSapCode());
merchantConfigDTO.setChannelType(merchantResponse.getChannelType());
//设置qrcode状态为未完成,由定时器生成二维码
merchantConfigDTO.setQrcodeStatus(0);
// merchantConfigDTO.setQrcodeUrl(createMerchantQrCode(merchantResponse.getResult().getSapCode(),
// merchantResponse.getResult().getChannelType(), merchantId));
merchantConfigDTO.setCodeType(1);
merchantConfigDTO.setCheckPosition(0);
merchantConfigDTO.setOpenCostPrice(0);
merchantConfigDTO.setOpenFlag(MerchantPakcageConfigStatusEnum.OPEN.getValue());
merchantConfigDTO.setOpenDate(createdDate);
merchantConfigDTO.setCreatedBy(createdBy);
merchantConfigDTO.setCreatedDate(createdDate);
merchantConfigDTO.setUpdatedDate(createdDate);
merchantConfigDTO.setUpdatedBy(createdBy);
merchantConfigDTO.setDeletedFlag(DeleteFlagEnum.N.getValue());
merchantConfigDTO.setSaleMode(MerchantSaleModeEnum.MODE_1.getMode());
//其他类型
merchantConfigDTO.setContractSubjectType(1);
merchantConfigDTO.setContractSubjectName(env.getProperty("equity.contract.print.salemode1.serviceSubject"));
merchantConfigDTO.setContractLogoUrl(env.getProperty("equity.contract.print.salemode1.logoUrl"));
merchantConfigDTO.setContractSealUrl(env.getProperty("equity.contract.print.salemode1.url"));
configList.add(merchantConfigDTO);
} else {
log.info("商品套餐同步,该商户号[{}]查询不到商户信息", merchantId);
throw new RpcServiceException(DefaultErrorEnum.DATA_NOT_EXIST, "未查询到商户信息");
}
});
//批量插入
if (CollectionUtils.isNotEmpty(configList)) {
serviceMerchantConfigMapper.insertList(configList);
}
}
}
/**
* 生成小程序链接二维码 * 生成小程序链接二维码
* *
* @param sap * @param sap
...@@ -512,19 +595,6 @@ public class ServiceMerchantConfigService { ...@@ -512,19 +595,6 @@ public class ServiceMerchantConfigService {
} }
/** /**
* 删除商户配置
*
* @param deleteMerchantList
*/
private void deleteMerchantConfig(List<Integer> deleteMerchantList) {
if (CollectionUtils.isNotEmpty(deleteMerchantList)) {
Example merchantConfigExample = new Example(ServiceMerchantConfig.class);
merchantConfigExample.createCriteria().andIn("merchantId", deleteMerchantList);
serviceMerchantConfigMapper.deleteByExample(merchantConfigExample);
}
}
/**
* 商户查询所有的权益名称 * 商户查询所有的权益名称
* *
* @param merchantId 商户号 * @param merchantId 商户号
......
...@@ -42,6 +42,7 @@ import org.springframework.beans.BeanUtils; ...@@ -42,6 +42,7 @@ import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment; import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example; import tk.mybatis.mapper.entity.Example;
...@@ -2366,6 +2367,7 @@ public class ServicePackageService { ...@@ -2366,6 +2367,7 @@ public class ServicePackageService {
* @param request * @param request
* @return * @return
*/ */
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
public List<ServicePackage> createPackageWithGood(EquityMerchantConfigDTO request) { public List<ServicePackage> createPackageWithGood(EquityMerchantConfigDTO request) {
List<EquityPackageConfigDTO> packageConfigList = request.getPackageConfigList(); List<EquityPackageConfigDTO> packageConfigList = request.getPackageConfigList();
// key: 商品id, value:套餐 // key: 商品id, value:套餐
......
...@@ -1012,4 +1012,12 @@ ...@@ -1012,4 +1012,12 @@
order by sec.created_date desc order by sec.created_date desc
</select> </select>
<select id="countByVin" resultType="int">
SELECT COUNT(1)
FROM service_equity_claims sec
INNER JOIN service_equity_vehicle sev ON sec.contract_no = sev.contract_no AND sev.deleted_flag = 'N'
WHERE sec.deleted_flag = 'N'
AND sev.vin = #{vin}
</select>
</mapper> </mapper>
\ No newline at end of file \ No newline at end of file
...@@ -7,6 +7,7 @@ ...@@ -7,6 +7,7 @@
--> -->
<id column="id" property="id" jdbcType="INTEGER" /> <id column="id" property="id" jdbcType="INTEGER" />
<result column="contract_no" property="contractNo" jdbcType="VARCHAR" /> <result column="contract_no" property="contractNo" jdbcType="VARCHAR" />
<result column="order_type" property="orderType" jdbcType="TINYINT" />
<result column="main_contract_no" property="mainContractNo" jdbcType="VARCHAR" /> <result column="main_contract_no" property="mainContractNo" jdbcType="VARCHAR" />
<result column="merchant_id" property="merchantId" jdbcType="INTEGER" /> <result column="merchant_id" property="merchantId" jdbcType="INTEGER" />
<result column="merchant_name" property="merchantName" jdbcType="VARCHAR" /> <result column="merchant_name" property="merchantName" jdbcType="VARCHAR" />
...@@ -180,7 +181,7 @@ ...@@ -180,7 +181,7 @@
<select id="getByContractNo" parameterType="string" resultMap="ListBaseResultMap"> <select id="getByContractNo" parameterType="string" resultMap="ListBaseResultMap">
SELECT SELECT
<!--订单信息--> <!--订单信息-->
seo.id, seo.contract_no, seo.merchant_id, seo.main_contract_no, seo.merchant_name ,seo.merchant_phone,seo.merchant_address, seo.customer_type, seo.customer_name, seo.card_type,seo.insurance_type, seo.id, seo.contract_no, seo.order_type, seo.merchant_id, seo.main_contract_no, seo.merchant_name ,seo.merchant_phone,seo.merchant_address, seo.customer_type, seo.customer_name, seo.card_type,seo.insurance_type,
seo.card_no, seo.customer_phone, seo.customer_address, seo.package_code, seo.suggested_selling_price, seo.card_seq_no,seo.buy_car_type,seo.compensation_name, seo.card_no, seo.customer_phone, seo.customer_address, seo.package_code, seo.suggested_selling_price, seo.card_seq_no,seo.buy_car_type,seo.compensation_name,
seo.actual_sales_price, seo.service_period, seo.effective_date, seo.expiration_date, seo.order_status,seo.audit_by,seo.audit_status,seo.actual_sales_person,actual_sales_person_id, seo.actual_sales_price, seo.service_period, seo.effective_date, seo.expiration_date, seo.order_status,seo.audit_by,seo.audit_status,seo.actual_sales_person,actual_sales_person_id,
seo.success_date,seo.data_perfection,seo.sn,seo.card_seq_no,seo.special_appoint_id,seo.created_by, seo.created_date, seo.updated_by, seo.updated_date,seo.cost_price, seo.success_date,seo.data_perfection,seo.sn,seo.card_seq_no,seo.special_appoint_id,seo.created_by, seo.created_date, seo.updated_by, seo.updated_date,seo.cost_price,
...@@ -209,7 +210,7 @@ ...@@ -209,7 +210,7 @@
<select id="listByPage" parameterType="cn.com.glsx.scrm.equity.dto.service.QueryServicePackageOrderRequestDTO" resultMap="ListBaseResultMap"> <select id="listByPage" parameterType="cn.com.glsx.scrm.equity.dto.service.QueryServicePackageOrderRequestDTO" resultMap="ListBaseResultMap">
SELECT SELECT
<!--订单信息--> <!--订单信息-->
seo.id, seo.contract_no, seo.merchant_id, seo.merchant_name,seo.merchant_phone,seo.merchant_address, seo.customer_type, seo.customer_name, seo.card_type, seo.id, seo.contract_no, seo.order_type, seo.merchant_id, seo.merchant_name,seo.merchant_phone,seo.merchant_address, seo.customer_type, seo.customer_name, seo.card_type,
seo.card_no, seo.customer_phone, seo.customer_address, seo.package_code, seo.suggested_selling_price, seo.card_seq_no,seo.buy_car_type,seo.compensation_name,seo.insurance_type, seo.card_no, seo.customer_phone, seo.customer_address, seo.package_code, seo.suggested_selling_price, seo.card_seq_no,seo.buy_car_type,seo.compensation_name,seo.insurance_type,
seo.actual_sales_price, seo.service_period, seo.effective_date, seo.expiration_date, seo.order_status,seo.audit_by,seo.audit_status,seo.actual_sales_person,seo.actual_sales_person_id, seo.actual_sales_price, seo.service_period, seo.effective_date, seo.expiration_date, seo.order_status,seo.audit_by,seo.audit_status,seo.actual_sales_person,seo.actual_sales_person_id,
seo.success_date,seo.data_perfection,seo.sn,seo.card_seq_no,seo.special_appoint_id,seo.created_by, seo.created_date, seo.updated_by, seo.updated_date,seo.cost_price,seo.erp_error_msg, seo.success_date,seo.data_perfection,seo.sn,seo.card_seq_no,seo.special_appoint_id,seo.created_by, seo.created_date, seo.updated_by, seo.updated_date,seo.cost_price,seo.erp_error_msg,
...@@ -227,6 +228,9 @@ ...@@ -227,6 +228,9 @@
LEFT JOIN service_package sp FORCE INDEX(idx_package_code) ON seo.package_code = sp.package_code LEFT JOIN service_package sp FORCE INDEX(idx_package_code) ON seo.package_code = sp.package_code
LEFT JOIN service_merchant sm ON seo.merchant_id = sm.merchant_id LEFT JOIN service_merchant sm ON seo.merchant_id = sm.merchant_id
where seo.deleted_flag = 'N' where seo.deleted_flag = 'N'
<if test="orderType != null">
and seo.order_type = #{orderType}
</if>
<if test="orderStatus != null "> <if test="orderStatus != null ">
and seo.order_status = #{orderStatus} and seo.order_status = #{orderStatus}
</if> </if>
...@@ -323,7 +327,7 @@ ...@@ -323,7 +327,7 @@
<select id="listGLByPage" parameterType="cn.com.glsx.scrm.equity.dto.service.QueryServicePackageOrderRequestDTO" resultMap="ListBaseResultMap"> <select id="listGLByPage" parameterType="cn.com.glsx.scrm.equity.dto.service.QueryServicePackageOrderRequestDTO" resultMap="ListBaseResultMap">
SELECT SELECT
<!--订单信息--> <!--订单信息-->
seo.id, seo.contract_no, seo.merchant_id, seo.merchant_name,seo.merchant_phone,seo.merchant_address, seo.customer_type, seo.customer_name, seo.card_type, seo.id, seo.contract_no, seo.order_type, seo.merchant_id, seo.merchant_name,seo.merchant_phone,seo.merchant_address, seo.customer_type, seo.customer_name, seo.card_type,
seo.card_no, seo.customer_phone, seo.customer_address, seo.package_code, seo.suggested_selling_price, seo.card_seq_no,seo.buy_car_type,seo.compensation_name,seo.insurance_type, seo.card_no, seo.customer_phone, seo.customer_address, seo.package_code, seo.suggested_selling_price, seo.card_seq_no,seo.buy_car_type,seo.compensation_name,seo.insurance_type,
seo.actual_sales_price, seo.service_period, seo.effective_date, seo.expiration_date, seo.order_status,seo.audit_by,seo.audit_status,seo.actual_sales_person,seo.actual_sales_person_id, seo.actual_sales_price, seo.service_period, seo.effective_date, seo.expiration_date, seo.order_status,seo.audit_by,seo.audit_status,seo.actual_sales_person,seo.actual_sales_person_id,
seo.success_date,seo.data_perfection,seo.sn,seo.card_seq_no,seo.special_appoint_id,seo.created_by, seo.created_date, seo.updated_by, seo.updated_date,seo.cost_price,seo.erp_error_msg, seo.success_date,seo.data_perfection,seo.sn,seo.card_seq_no,seo.special_appoint_id,seo.created_by, seo.created_date, seo.updated_by, seo.updated_date,seo.cost_price,seo.erp_error_msg,
...@@ -341,6 +345,9 @@ ...@@ -341,6 +345,9 @@
LEFT JOIN service_package sp FORCE INDEX(idx_package_code) ON seo.package_code = sp.package_code LEFT JOIN service_package sp FORCE INDEX(idx_package_code) ON seo.package_code = sp.package_code
LEFT JOIN service_merchant sm ON seo.merchant_id = sm.merchant_id LEFT JOIN service_merchant sm ON seo.merchant_id = sm.merchant_id
where seo.deleted_flag = 'N' and (seo.data_source not in('dj','ym') or seo.data_source is null) where seo.deleted_flag = 'N' and (seo.data_source not in('dj','ym') or seo.data_source is null)
<if test="orderType != null">
and seo.order_type = #{orderType}
</if>
<if test="orderStatus != null "> <if test="orderStatus != null ">
and seo.order_status = #{orderStatus} and seo.order_status = #{orderStatus}
</if> </if>
...@@ -446,7 +453,7 @@ ...@@ -446,7 +453,7 @@
<select id="getServiceOrderByCardNo" parameterType="string" resultMap="ListBaseResultMap"> <select id="getServiceOrderByCardNo" parameterType="string" resultMap="ListBaseResultMap">
SELECT SELECT
<!--订单信息--> <!--订单信息-->
seo.id, seo.contract_no, seo.merchant_id, seo.merchant_name,seo.merchant_phone,seo.merchant_address, seo.customer_type, seo.customer_name, seo.card_type, seo.id, seo.contract_no, seo.order_type, seo.merchant_id, seo.merchant_name,seo.merchant_phone,seo.merchant_address, seo.customer_type, seo.customer_name, seo.card_type,
seo.card_no, seo.customer_phone, seo.customer_address, seo.package_code, seo.suggested_selling_price, seo.card_seq_no,seo.buy_car_type,seo.compensation_name,seo.insurance_type, seo.card_no, seo.customer_phone, seo.customer_address, seo.package_code, seo.suggested_selling_price, seo.card_seq_no,seo.buy_car_type,seo.compensation_name,seo.insurance_type,
seo.actual_sales_price, seo.service_period, seo.effective_date, seo.expiration_date, seo.order_status,seo.audit_by,seo.audit_status,seo.actual_sales_person,seo.actual_sales_person_id, seo.actual_sales_price, seo.service_period, seo.effective_date, seo.expiration_date, seo.order_status,seo.audit_by,seo.audit_status,seo.actual_sales_person,seo.actual_sales_person_id,
seo.success_date,seo.data_perfection,seo.sn,seo.card_seq_no,seo.audit_date,seo.has_print,seo.erp_print_msg,seo.erp_print_status,rollback_time,rollback_amount, seo.success_date,seo.data_perfection,seo.sn,seo.card_seq_no,seo.audit_date,seo.has_print,seo.erp_print_msg,seo.erp_print_status,rollback_time,rollback_amount,
......
package cn.com.glsx.scrm.equity.service.equity;
import cn.com.glsx.framework.core.exception.RpcServiceException;
import cn.com.glsx.scrm.equity.dto.service.ChargeBackCheckDTO;
import cn.com.glsx.scrm.equity.dto.service.ChargeBackCheckResultDTO;
import cn.com.glsx.scrm.equity.enums.ChargeBackSourceEnum;
import cn.com.glsx.scrm.equity.mapper.ServiceEquityClaimsMapper;
import cn.com.glsx.scrm.equity.service.ChannelServiceEquityOrderService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.core.env.Environment;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
/**
* checkChargeBackAllowed 方法单元测试
* 覆盖参数校验、超管跳过、核赔校验等分支
*/
@RunWith(MockitoJUnitRunner.class)
public class CheckChargeBackAllowedTest {
@InjectMocks
private ChannelServiceEquityOrderService service;
@Mock
private ServiceEquityClaimsMapper serviceEquityClaimsMapper;
@Mock
private Environment env;
private static final String TEST_VIN = "LVSHFFAN5KF123456";
private static final String SUPER_ADMIN_PHONE = "15007612682";
private static final String NORMAL_PHONE = "13800138000";
private static final String DEFAULT_SUPER_ADMIN_PHONES = "15007612682,15019903579,13333970369,13632814608,18476788882";
private static final String DEFAULT_CLAIMS_NOTICE = "由于您的车辆有理赔案件处理当中,请先联系权益服务官18938907441进行处理";
private ChargeBackCheckDTO buildDto(String vin, Integer source, String loginAccount) {
ChargeBackCheckDTO dto = new ChargeBackCheckDTO();
dto.setVin(vin);
dto.setSource(source);
dto.setLoginAccount(loginAccount);
return dto;
}
// ========== 参数校验 ==========
@Test(expected = RpcServiceException.class)
public void testVinIsNull_shouldThrowException() {
service.checkChargeBackAllowed(buildDto(null, ChargeBackSourceEnum.DJ_SMART_STORE.getValue(), null));
}
@Test(expected = RpcServiceException.class)
public void testVinIsEmpty_shouldThrowException() {
service.checkChargeBackAllowed(buildDto("", ChargeBackSourceEnum.DJ_SMART_STORE.getValue(), null));
}
@Test(expected = RpcServiceException.class)
public void testVinIsBlank_shouldThrowException() {
service.checkChargeBackAllowed(buildDto(" ", ChargeBackSourceEnum.DJ_SMART_STORE.getValue(), null));
}
@Test(expected = RpcServiceException.class)
public void testSourceIsNull_shouldThrowException() {
service.checkChargeBackAllowed(buildDto(TEST_VIN, null, null));
}
// ========== 超管账号跳过校验 ==========
@Test
public void testScrmOssSuperAdmin_shouldSkipAndReturnSuccess() {
when(env.getProperty("scrm.service.equity.charge.back.super.admin.phones",
"15007612682,15019903579,13333970369,13632814608,18476788882"))
.thenReturn(DEFAULT_SUPER_ADMIN_PHONES);
ChargeBackCheckResultDTO result = service.checkChargeBackAllowed(
buildDto(TEST_VIN, ChargeBackSourceEnum.SCRM_OSS.getValue(), SUPER_ADMIN_PHONE));
assertTrue(result.getAllowChargeBack());
assertNull(result.getMessage());
verifyZeroInteractions(serviceEquityClaimsMapper);
}
@Test
public void testScrmOssNonSuperAdmin_shouldContinueToClaimsCheck() {
when(env.getProperty("scrm.service.equity.charge.back.super.admin.phones",
"15007612682,15019903579,13333970369,13632814608,18476788882"))
.thenReturn(DEFAULT_SUPER_ADMIN_PHONES);
when(serviceEquityClaimsMapper.countByVin(TEST_VIN)).thenReturn(0);
ChargeBackCheckResultDTO result = service.checkChargeBackAllowed(
buildDto(TEST_VIN, ChargeBackSourceEnum.SCRM_OSS.getValue(), NORMAL_PHONE));
assertTrue(result.getAllowChargeBack());
verify(serviceEquityClaimsMapper).countByVin(TEST_VIN);
}
@Test
public void testScrmOssNullLoginAccount_shouldContinueToClaimsCheck() {
when(env.getProperty("scrm.service.equity.charge.back.super.admin.phones",
"15007612682,15019903579,13333970369,13632814608,18476788882"))
.thenReturn(DEFAULT_SUPER_ADMIN_PHONES);
when(serviceEquityClaimsMapper.countByVin(TEST_VIN)).thenReturn(0);
ChargeBackCheckResultDTO result = service.checkChargeBackAllowed(
buildDto(TEST_VIN, ChargeBackSourceEnum.SCRM_OSS.getValue(), null));
assertTrue(result.getAllowChargeBack());
verify(serviceEquityClaimsMapper).countByVin(TEST_VIN);
}
@Test
public void testScrmOssSuperAdminWithSpaces_shouldSkipAndReturnSuccess() {
when(env.getProperty("scrm.service.equity.charge.back.super.admin.phones",
"15007612682,15019903579,13333970369,13632814608,18476788882"))
.thenReturn(DEFAULT_SUPER_ADMIN_PHONES);
ChargeBackCheckResultDTO result = service.checkChargeBackAllowed(
buildDto(TEST_VIN, ChargeBackSourceEnum.SCRM_OSS.getValue(), " " + SUPER_ADMIN_PHONE + " "));
assertTrue(result.getAllowChargeBack());
assertNull(result.getMessage());
verifyZeroInteractions(serviceEquityClaimsMapper);
}
// ========== 非SCRM_OSS来源直接走核赔校验 ==========
@Test
public void testDjSmartStoreSource_shouldCheckClaims() {
when(serviceEquityClaimsMapper.countByVin(TEST_VIN)).thenReturn(0);
ChargeBackCheckResultDTO result = service.checkChargeBackAllowed(
buildDto(TEST_VIN, ChargeBackSourceEnum.DJ_SMART_STORE.getValue(), null));
assertTrue(result.getAllowChargeBack());
verify(serviceEquityClaimsMapper).countByVin(TEST_VIN);
}
@Test
public void testBusinessAssistantSource_shouldCheckClaims() {
when(serviceEquityClaimsMapper.countByVin(TEST_VIN)).thenReturn(0);
ChargeBackCheckResultDTO result = service.checkChargeBackAllowed(
buildDto(TEST_VIN, ChargeBackSourceEnum.BUSINESS_ASSISTANT.getValue(), null));
assertTrue(result.getAllowChargeBack());
verify(serviceEquityClaimsMapper).countByVin(TEST_VIN);
}
// ========== 核赔记录校验 ==========
@Test
public void testHasClaimsRecord_shouldReturnFailWithNotice() {
when(serviceEquityClaimsMapper.countByVin(TEST_VIN)).thenReturn(1);
when(env.getProperty("scrm.service.equity.charge.back.claims.notice",
"由于您的车辆有理赔案件处理当中,请先联系权益服务官18938907441进行处理"))
.thenReturn(DEFAULT_CLAIMS_NOTICE);
ChargeBackCheckResultDTO result = service.checkChargeBackAllowed(
buildDto(TEST_VIN, ChargeBackSourceEnum.DJ_SMART_STORE.getValue(), null));
assertFalse(result.getAllowChargeBack());
assertEquals(DEFAULT_CLAIMS_NOTICE, result.getMessage());
}
@Test
public void testHasMultipleClaimsRecords_shouldReturnFail() {
when(serviceEquityClaimsMapper.countByVin(TEST_VIN)).thenReturn(3);
when(env.getProperty("scrm.service.equity.charge.back.claims.notice",
"由于您的车辆有理赔案件处理当中,请先联系权益服务官18938907441进行处理"))
.thenReturn(DEFAULT_CLAIMS_NOTICE);
ChargeBackCheckResultDTO result = service.checkChargeBackAllowed(
buildDto(TEST_VIN, ChargeBackSourceEnum.BUSINESS_ASSISTANT.getValue(), NORMAL_PHONE));
assertFalse(result.getAllowChargeBack());
assertNotNull(result.getMessage());
}
@Test
public void testNoClaimsRecord_shouldReturnSuccess() {
when(serviceEquityClaimsMapper.countByVin(TEST_VIN)).thenReturn(0);
ChargeBackCheckResultDTO result = service.checkChargeBackAllowed(
buildDto(TEST_VIN, ChargeBackSourceEnum.DJ_SMART_STORE.getValue(), null));
assertTrue(result.getAllowChargeBack());
assertNull(result.getMessage());
}
// ========== 环境配置自定义 ==========
@Test
public void testCustomSuperAdminPhones_shouldUseConfigValue() {
String customPhones = "13900001111,13900002222";
when(env.getProperty("scrm.service.equity.charge.back.super.admin.phones",
"15007612682,15019903579,13333970369,13632814608,18476788882"))
.thenReturn(customPhones);
ChargeBackCheckResultDTO result = service.checkChargeBackAllowed(
buildDto(TEST_VIN, ChargeBackSourceEnum.SCRM_OSS.getValue(), "13900001111"));
assertTrue(result.getAllowChargeBack());
verifyZeroInteractions(serviceEquityClaimsMapper);
}
@Test
public void testCustomClaimsNotice_shouldUseConfigValue() {
String customNotice = "自定义提示信息";
when(serviceEquityClaimsMapper.countByVin(TEST_VIN)).thenReturn(2);
when(env.getProperty("scrm.service.equity.charge.back.claims.notice",
"由于您的车辆有理赔案件处理当中,请先联系权益服务官18938907441进行处理"))
.thenReturn(customNotice);
ChargeBackCheckResultDTO result = service.checkChargeBackAllowed(
buildDto(TEST_VIN, ChargeBackSourceEnum.DJ_SMART_STORE.getValue(), null));
assertFalse(result.getAllowChargeBack());
assertEquals(customNotice, result.getMessage());
}
}
  • @wangxw1
    commented
    Owner

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

    1. 大事务拆分导致的数据一致性与部分失败风险(功能正确性)

    • 问题描述:在 ServiceMerchantConfigService.addMerchantConfigWithGood 方法中,移除了原有的方法级大事务 @Transactional,将事务拆分为阶段1(商品级锁与事务)和阶段2(商户级锁与事务)。如果阶段2的 for 循环中某个商户处理抛出异常,或者阶段2执行完毕但在阶段3抛出异常,方法会直接中断。
    • 影响分析:由于前置的事务(如阶段1的套餐创建、阶段2中已成功处理的商户)已经提交且无法回滚,而后续的阶段3(SKU关系绑定、合同模板配置)未被执行,会导致系统产生“脏数据”或不完整数据(例如:套餐已创建但缺少合同模板或SKU关系),严重影响后续业务逻辑。
    • 优化建议: 如果为了避免大事务导致的性能问题和死锁而进行拆分,必须配合补偿机制或最终一致性方案。
      • 方案A:如果业务需要强一致性,建议将多步骤写入操作合并到一个事务服务中,或者恢复大事务。
      • 方案B:捕获阶段2和阶段3的异常,进行告警或记录到失败重试表中,通过定时任务进行补偿;或者在循环中捕获单商户异常,不阻断其他商户的处理。

    2. 分布式锁释放机制存在误删风险(安全性与潜在风险)

    • 问题描述:在 createPackageWithGoodLocked 和 batchInsertMerchantConfigAndRelations 方法的 finally 块中,直接调用了 redisUtil.deleteLock(lockKey) 来释放锁。
    • 影响分析:如果 deleteLock 内部仅仅是执行了 Redis 的 DEL 命令,当业务执行时间超过了锁的自动过期时间,锁会被 Redis 自动释放并可能被其他线程获取。此时,当前线程执行到 finally 块时,会把其他线程持有的锁给误删掉,从而导致并发控制完全失效。
    • 优化建议:检查并确保 RedisUtil 的锁实现是安全的。加锁时应生成并存入唯一标识(如 UUID 或 ThreadId),在释放锁时,必须使用 Lua 脚本进行原子操作(先比对 value 是否一致,一致才执行 DEL)。或者推荐直接使用成熟的 Redisson 客户端的 RLock。

    3. 内部方法调用触发事务的实现方式不够优雅(最佳实践)

    • 问题描述:在 ServiceMerchantConfigService 中,使用了 @Autowired @Lazy private ServiceMerchantConfigService self; 来注入自身,以便通过代理对象调用 doMerchantConfigInTransaction,从而使 @Transactional 生效。
    • 影响分析:虽然这是 Spring 官方支持的一种 Workaround,但它增加了类的自我耦合,降低了代码的可读性,且在某些复杂的 Spring 容器初始化场景下容易引发循环依赖问题。
    • 优化建议:遵循单一职责原则,建议将需要在独立事务中执行的逻辑(如 doMerchantConfigInTransaction)提取到一个专门的事务管理 Service 组件中(例如 MerchantConfigTxService);或者通过 ((ServiceMerchantConfigService) AopContext.currentProxy()).doMerchantConfigInTransaction(...) 的方式获取代理对象。

    二、评分明细

    • 功能实现的正确性与健壮性(30/40分) 理由:退单校验逻辑(包括超管免校验、核赔记录校验)实现清晰且带有完善的单元测试,值得肯定。但 addMerchantConfigWithGood 移除大事务后,缺乏对部分失败场景的补偿机制,存在明显的数据一致性风险,扣 10 分。

    • 安全性与潜在风险(25/30分) 理由:没有发现 SQL 注入、越权等常见的安全漏洞,参数校验也比较到位。但自定义的 Redis 分布式锁释放逻辑可能存在并发误删风险(取决于底层工具类的实现),扣 5 分。

    • 最佳实践与可维护性(16/20分) 理由:整体代码结构较为清晰,枚举类和 DTO 的使用符合规范。但使用 @Lazy 注入自身处理事务不够优雅;另外 sortedMerchantIds 在流处理时如果存在 null 元素,sorted() 会抛出 NPE,建议在流操作前进行 Objects::nonNull 过滤,扣 4 分。

    • 性能与资源利用(5/5分) 理由:将大事务拆分为细粒度事务,并将慢 IO(如 RPC 查询商户信息)移至锁和事务外部,有效减少了锁持有时间和数据库事务持有时长,是对性能的积极优化,得满分。

    • 提交信息质量(5/5分) 理由:Commit 记录(如“优化商品套餐同步逻辑”、“添加核赔车架号校验单元测试”等)清晰准确,能够很好地追溯代码变更的意图,得满分。

    总分:81分

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