Commit 080022e4 by 章家宝

fixbug:优惠券金额计算

1 parent 0f60137a
...@@ -64,7 +64,7 @@ public interface CouponAccountRepository extends BaseRepository<CouponAccount, L ...@@ -64,7 +64,7 @@ public interface CouponAccountRepository extends BaseRepository<CouponAccount, L
* @param now 当前时间 * @param now 当前时间
* @return 优惠券列表 * @return 优惠券列表
*/ */
@Query("SELECT c FROM CouponAccount c WHERE c.accountId = :accountId AND c.status = :status AND c.deleteFlag = :deleteFlag AND c.validEndTime > :now") @Query("SELECT c FROM CouponAccount c WHERE c.accountId = :accountId AND c.status = :status AND c.deleteFlag = :deleteFlag AND c.validStartTime <= :now AND c.validEndTime > :now")
List<CouponAccount> findAvailableCoupons( List<CouponAccount> findAvailableCoupons(
@Param("accountId") Integer accountId, @Param("accountId") Integer accountId,
@Param("status") Integer status, @Param("status") Integer status,
......
...@@ -44,48 +44,6 @@ public class CouponVerificationService { ...@@ -44,48 +44,6 @@ public class CouponVerificationService {
private final DailySequenceIdGenerator dailySequenceIdGenerator; private final DailySequenceIdGenerator dailySequenceIdGenerator;
/** /**
* 获取订单可用优惠券列表
*
* @param accountId 用户账户 ID
* @param orderId 订单 ID
* @param transactionAmount 订单成交价
* @return 可用优惠券列表(按最优排序)
*/
public List<CouponAvailableVO> getAvailableCouponsForOrder(Integer accountId, Integer orderId, BigDecimal transactionAmount) {
LocalDateTime now = LocalDateTime.now();
// 查询用户所有待使用的优惠券
List<CouponAccount> allCoupons = couponAccountRepository.findAvailableCoupons(
accountId, CouponUserStatusEnum.UNUSED.getCode(), DeleteFlag.NOT_DELETED.getCode(), now);
if (allCoupons.isEmpty()) {
return Collections.emptyList();
}
// 批量预加载:一次性查出 usage、template、tierRule,消除 N+1
Map<String, CouponOrderUsage> usageMap = loadUsageMap(allCoupons);
Map<Long, CouponTemplate> templateMap = loadTemplateMapForTiered(allCoupons);
Map<String, List<CouponTierRule>> tierRuleMap = loadTierRuleMap(templateMap);
// 过滤出当前订单可用的优惠券(抵扣金额仅计算一次,供过滤与 VO 共用)
return allCoupons.stream()
.map(coupon -> {
BigDecimal actualDeduction = calculateActualDeductionFromCache(
coupon, transactionAmount, templateMap, tierRuleMap);
if (!isCouponAvailableForOrderFromCache(coupon, transactionAmount, usageMap, actualDeduction)) {
return null;
}
return convertToAvailableVO(coupon, actualDeduction);
})
.filter(Objects::nonNull)
.sorted(Comparator
.comparing(CouponAvailableVO::getActualDeduction, Comparator.reverseOrder()) // 实际抵扣金额降序
.thenComparing(CouponAvailableVO::getValidEndTime) // 过期时间升序
)
.collect(Collectors.toList());
}
/**
* 批量预加载:优惠券订单使用记录 Map<couponId, usage> * 批量预加载:优惠券订单使用记录 Map<couponId, usage>
*/ */
private Map<String, CouponOrderUsage> loadUsageMap(List<CouponAccount> coupons) { private Map<String, CouponOrderUsage> loadUsageMap(List<CouponAccount> coupons) {
...@@ -136,127 +94,51 @@ public class CouponVerificationService { ...@@ -136,127 +94,51 @@ public class CouponVerificationService {
} }
/** /**
* 基于预加载 Map 计算优惠券实际抵扣金额(抵扣车款),无 DB 查询 * 计算优惠券实际抵扣金额
*/ *
private BigDecimal calculateActualDeductionFromCache(CouponAccount coupon, BigDecimal transactionAmount, * @param coupon 优惠券
Map<Long, CouponTemplate> templateMap, * @param orderPrice 订单金额(车款),用于门槛校验
Map<String, List<CouponTierRule>> tierRuleMap) { * @param targetAmount 目标抵扣金额(车款或佣金),用于限制最大抵扣金额
BigDecimal faceAmount = coupon.getFaceAmount(); * @param templateMap 模板缓存(可为空,非阶梯券不需要)
if (!CouponTypeEnum.TIERED_AMOUNT.getCode().equals(coupon.getCouponType())) { * @param tierRuleMap 阶梯规则缓存(可为空,非阶梯券不需要)
// 固定面额券:直接返回面额 * @return 实际抵扣金额(不超过目标抵扣金额)
return faceAmount;
}
// 阶梯券:从缓存 Map 取模板和阶梯规则
CouponTemplate template = templateMap.get(coupon.getTemplateId());
if (template == null) {
throw new BusinessCodeException(ErrorCodeEnum.DATA_NOT_EXISTS, "优惠券模板不存在");
}
List<CouponTierRule> tierRules = tierRuleMap.get(template.getTemplateId());
if (tierRules == null || tierRules.isEmpty()) {
log.warn("阶梯券未配置阶梯规则,使用面额:templateId={}", coupon.getTemplateId());
return faceAmount;
}
Optional<CouponTierRule> matchedTier = tierRules.stream()
.filter(rule -> transactionAmount.compareTo(rule.getThresholdAmount()) >= 0)
.max(Comparator.comparing(CouponTierRule::getThresholdAmount));
if (matchedTier.isPresent()) {
BigDecimal tierDeduction = matchedTier.get().getDeductionAmount();
return tierDeduction.compareTo(faceAmount) > 0 ? faceAmount : tierDeduction;
}
return BigDecimal.ZERO;
}
/**
* 基于预加载 Map + 已计算抵扣金额判断优惠券是否可用,无 DB 查询
*/
private boolean isCouponAvailableForOrderFromCache(CouponAccount coupon, BigDecimal transactionAmount,
Map<String, CouponOrderUsage> usageMap,
BigDecimal actualDeduction) {
// 1. 门槛金额
if (coupon.getThresholdAmount() != null &&
transactionAmount.compareTo(coupon.getThresholdAmount()) < 0) {
log.debug("优惠券不满足门槛:couponId={}, 门槛={}, 成交价={}",
coupon.getCouponId(), coupon.getThresholdAmount(), transactionAmount);
return false;
}
// 2. 已被其他订单使用(未退回)
CouponOrderUsage usage = usageMap.get(coupon.getCouponId());
if (usage != null && usage.getUsageStatus() == 1) {
log.debug("优惠券已被其他订单使用:couponId={}, orderId={}",
coupon.getCouponId(), usage.getOrderId());
return false;
}
// 3. 阶梯券需达到任一门槛
if (CouponTypeEnum.TIERED_AMOUNT.getCode().equals(coupon.getCouponType())
&& actualDeduction.compareTo(BigDecimal.ZERO) <= 0) {
log.debug("阶梯券未达到任何门槛:couponId={}, 成交价={}",
coupon.getCouponId(), transactionAmount);
return false;
}
return true;
}
/**
* 计算优惠券实际抵扣金额(用于抵扣车款)
*/ */
private BigDecimal calculateActualDeduction(CouponAccount coupon, BigDecimal transactionAmount) { private BigDecimal calculateActualDeduction(CouponAccount coupon, BigDecimal orderPrice,
BigDecimal targetAmount,
Map<Long, CouponTemplate> templateMap,
Map<String, List<CouponTierRule>> tierRuleMap) {
BigDecimal faceAmount = coupon.getFaceAmount(); BigDecimal faceAmount = coupon.getFaceAmount();
BigDecimal rawDeduction;
// 根据优惠券类型计算抵扣金额 if (!CouponTypeEnum.TIERED_AMOUNT.getCode().equals(coupon.getCouponType())) {
if (CouponTypeEnum.TIERED_AMOUNT.getCode().equals(coupon.getCouponType())) { // 固定面额券:直接使用面额
// 阶梯满减券:根据成交价和阶梯规则计算 rawDeduction = faceAmount;
return calculateTieredDeduction(coupon.getTemplateId(), transactionAmount, faceAmount);
} else { } else {
// 固定面额券:直接返回面额 // 阶梯券:从缓存 Map 取模板和阶梯规则,门槛校验只根据订单金额(orderPrice)
return faceAmount; CouponTemplate template = templateMap.get(coupon.getTemplateId());
} if (template == null) {
} throw new BusinessCodeException(ErrorCodeEnum.DATA_NOT_EXISTS, "优惠券模板不存在");
}
/** List<CouponTierRule> tierRules = tierRuleMap.get(template.getTemplateId());
* 计算阶梯满减券的抵扣金额 if (tierRules == null || tierRules.isEmpty()) {
* log.warn("阶梯券未配置阶梯规则,使用面额:templateId={}", coupon.getTemplateId());
* @param templateDbId 模板数据库 ID(Long 类型) rawDeduction = BigDecimal.ZERO;
* @param transactionAmount 订单成交价 } else {
* @param faceAmount 券面额(最高抵扣金额) // 阶梯门槛校验只根据订单金额(orderPrice),不管抵扣类型
* @return 实际抵扣金额 Optional<CouponTierRule> matchedTier = tierRules.stream()
*/ .filter(rule -> orderPrice.compareTo(rule.getThresholdAmount()) >= 0)
private BigDecimal calculateTieredDeduction(Long templateDbId, BigDecimal transactionAmount, BigDecimal faceAmount) { .max(Comparator.comparing(CouponTierRule::getThresholdAmount));
// 1. 查询模板获取 template_id(字符串) if (matchedTier.isPresent()) {
CouponTemplate template = couponTemplateRepository.findByIdAndDeleteFlag(templateDbId, DeleteFlag.NOT_DELETED.getCode()) BigDecimal tierDeduction = matchedTier.get().getDeductionAmount();
.orElseThrow(() -> new BusinessCodeException(ErrorCodeEnum.DATA_NOT_EXISTS, "优惠券模板不存在")); rawDeduction = tierDeduction.compareTo(faceAmount) > 0 ? faceAmount : tierDeduction;
} else {
// 2. 查询该模板的所有阶梯规则 rawDeduction = BigDecimal.ZERO;
List<CouponTierRule> tierRules = couponTierRuleRepository }
.findByTemplateIdAndDeleteFlag(template.getTemplateId(), DeleteFlag.NOT_DELETED.getCode());
if (tierRules == null || tierRules.isEmpty()) {
log.warn("阶梯券未配置阶梯规则,使用面额:templateId={}", templateDbId);
return faceAmount;
}
// 3. 按门槛金额降序排序,找到满足条件的最高阶梯
Optional<CouponTierRule> matchedTier = tierRules.stream()
.filter(rule -> transactionAmount.compareTo(rule.getThresholdAmount()) >= 0)
.max(Comparator.comparing(CouponTierRule::getThresholdAmount));
if (matchedTier.isPresent()) {
// 4. 获取该阶梯的抵扣金额
BigDecimal tierDeduction = matchedTier.get().getDeductionAmount();
// 5. 实际抵扣金额不能超过面额(最高抵扣金额)
if (tierDeduction.compareTo(faceAmount) > 0) {
return faceAmount;
} }
log.debug("阶梯券计算:成交价={}, 匹配阶梯门槛={}, 阶梯抵扣={}, 最终抵扣={}",
transactionAmount, matchedTier.get().getThresholdAmount(), tierDeduction, faceAmount);
return tierDeduction;
} else {
// 未达到任何阶梯门槛,返回 0
log.debug("阶梯券计算:成交价={} 未达到任何阶梯门槛", transactionAmount);
return BigDecimal.ZERO;
} }
// 限制抵扣金额不能超过目标抵扣金额(车款或佣金)
return rawDeduction.compareTo(targetAmount) > 0 ? targetAmount : rawDeduction;
} }
/** /**
...@@ -264,11 +146,7 @@ public class CouponVerificationService { ...@@ -264,11 +146,7 @@ public class CouponVerificationService {
* *
* @param accountId 用户账户 ID * @param accountId 用户账户 ID
* @param orderId 订单 ID * @param orderId 订单 ID
* @param orderCode 订单编号
* @param couponId 优惠券实例 ID * @param couponId 优惠券实例 ID
* @param transactionAmount 订单成交价
* @param vehicleId 车辆 ID
* @param vehicleInfo 车辆信息
* @return 实际抵扣金额 * @return 实际抵扣金额
*/ */
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
...@@ -292,8 +170,7 @@ public class CouponVerificationService { ...@@ -292,8 +170,7 @@ public class CouponVerificationService {
BigDecimal orderPrice = BigDecimal.valueOf(order.getOrderPrice()); BigDecimal orderPrice = BigDecimal.valueOf(order.getOrderPrice());
BigDecimal commissionPrice = BigDecimal.valueOf(order.getCommissionPrice()); BigDecimal commissionPrice = BigDecimal.valueOf(order.getCommissionPrice());
// 根据抵扣类型计算交易金额:车款抵扣用成交价,佣金抵扣用佣金 BigDecimal targetAmount = coupon.getDeductionType() != null && coupon.getDeductionType() == 1
BigDecimal transactionAmount = coupon.getDeductionType() != null && coupon.getDeductionType() == 1
? orderPrice : commissionPrice; ? orderPrice : commissionPrice;
// 获取车辆信息 // 获取车辆信息
...@@ -321,7 +198,7 @@ public class CouponVerificationService { ...@@ -321,7 +198,7 @@ public class CouponVerificationService {
.findByOrderIdAndDeleteFlag(orderId, DeleteFlag.NOT_DELETED.getCode()) .findByOrderIdAndDeleteFlag(orderId, DeleteFlag.NOT_DELETED.getCode())
.orElse(null); .orElse(null);
if (existingOrderUsage != null && existingOrderUsage.getUsageStatus() == 1) { if (existingOrderUsage != null && existingOrderUsage.getUsageStatus() == 1) {
throw new BusinessCodeException(ErrorCodeEnum.COMMON_ERROR, throw new BusinessCodeException(ErrorCodeEnum.COMMON_ERROR,
"该订单已使用优惠券,不可重复使用"); "该订单已使用优惠券,不可重复使用");
} }
...@@ -333,23 +210,18 @@ public class CouponVerificationService { ...@@ -333,23 +210,18 @@ public class CouponVerificationService {
throw new BusinessCodeException(ErrorCodeEnum.COMMON_ERROR, "优惠券已被其他订单使用"); throw new BusinessCodeException(ErrorCodeEnum.COMMON_ERROR, "优惠券已被其他订单使用");
} }
// 8. 校验使用门槛 // 8. 校验使用门槛(不管抵扣类型,只根据订单金额校验门槛)
if (coupon.getThresholdAmount() != null && if (coupon.getThresholdAmount() != null
transactionAmount.compareTo(coupon.getThresholdAmount()) < 0) { && orderPrice.compareTo(coupon.getThresholdAmount()) < 0) {
throw new BusinessCodeException(ErrorCodeEnum.COMMON_ERROR, throw new BusinessCodeException(ErrorCodeEnum.COMMON_ERROR,
"订单金额未达到优惠券使用门槛,门槛金额:" + coupon.getThresholdAmount() + "元"); "订单金额未达到优惠券使用门槛,门槛金额:" + coupon.getThresholdAmount() + "元");
} }
// 9. 计算实际抵扣金额 // 9. 计算实际抵扣金额
BigDecimal actualDeduction = calculateActualDeduction(coupon, transactionAmount); Map<Long, CouponTemplate> templateMap = loadTemplateMapForTiered(List.of(coupon));
Map<String, List<CouponTierRule>> tierRuleMap = loadTierRuleMap(templateMap);
// 10. 对于阶梯券,校验是否达到阶梯门槛 BigDecimal actualDeduction = calculateActualDeduction(
if (CouponTypeEnum.TIERED_AMOUNT.getCode().equals(coupon.getCouponType())) { coupon, orderPrice, targetAmount, templateMap, tierRuleMap);
if (actualDeduction.compareTo(BigDecimal.ZERO) <= 0) {
throw new BusinessCodeException(ErrorCodeEnum.COMMON_ERROR,
"订单金额未达到阶梯券使用门槛");
}
}
// 11. 更新优惠券状态为已核销 // 11. 更新优惠券状态为已核销
coupon.setStatus(CouponUserStatusEnum.VERIFIED.getCode()); coupon.setStatus(CouponUserStatusEnum.VERIFIED.getCode());
...@@ -388,7 +260,7 @@ public class CouponVerificationService { ...@@ -388,7 +260,7 @@ public class CouponVerificationService {
.orderCode(orderCode) .orderCode(orderCode)
.vehicleId(vehicleId) .vehicleId(vehicleId)
.vehicleInfo(vehicleInfo) .vehicleInfo(vehicleInfo)
.transactionAmount(transactionAmount) .transactionAmount(orderPrice)
.faceAmount(coupon.getFaceAmount()) .faceAmount(coupon.getFaceAmount())
.actualDeduction(actualDeduction) .actualDeduction(actualDeduction)
.isDowngraded(actualDeduction.compareTo(coupon.getFaceAmount()) < 0 ? 1 : 0) .isDowngraded(actualDeduction.compareTo(coupon.getFaceAmount()) < 0 ? 1 : 0)
...@@ -555,10 +427,12 @@ public class CouponVerificationService { ...@@ -555,10 +427,12 @@ public class CouponVerificationService {
// 转换为VO并判断可用性(actualDeduction 每张券只计算一次) // 转换为VO并判断可用性(actualDeduction 每张券只计算一次)
List<OrderCouponRespVO> couponVOList = allCoupons.stream() List<OrderCouponRespVO> couponVOList = allCoupons.stream()
.map(coupon -> { .map(coupon -> {
BigDecimal pickedAmount = coupon.getDeductionType() != null && coupon.getDeductionType() == 1 // 根据抵扣类型确定目标抵扣金额(限制最大抵扣金额)
BigDecimal targetAmount = coupon.getDeductionType() != null && coupon.getDeductionType() == 1
? orderPrice : commissionPrice; ? orderPrice : commissionPrice;
BigDecimal actualDeduction = calculateActualDeductionFromCache( // 计算实际抵扣金额:门槛校验用 orderPrice,最大抵扣限制用 targetAmount
coupon, pickedAmount, templateMap, tierRuleMap); BigDecimal actualDeduction = calculateActualDeduction(
coupon, orderPrice, targetAmount, templateMap, tierRuleMap);
String unavailableReason = checkCouponUnavailableReason( String unavailableReason = checkCouponUnavailableReason(
coupon, orderPrice, commissionPrice, now, usageMap, actualDeduction); coupon, orderPrice, commissionPrice, now, usageMap, actualDeduction);
return convertToOrderCouponVO(coupon, maxVehicleDeduction, maxCommissionDeduction, return convertToOrderCouponVO(coupon, maxVehicleDeduction, maxCommissionDeduction,
...@@ -678,7 +552,12 @@ public class CouponVerificationService { ...@@ -678,7 +552,12 @@ public class CouponVerificationService {
BigDecimal commissionPrice, LocalDateTime now, BigDecimal commissionPrice, LocalDateTime now,
Map<String, CouponOrderUsage> usageMap, Map<String, CouponOrderUsage> usageMap,
BigDecimal actualDeduction) { BigDecimal actualDeduction) {
// 1. 已过期 // 1. 未生效
if (now.isBefore(coupon.getValidStartTime())) {
return "优惠券未生效";
}
// 2. 已过期
if (now.isAfter(coupon.getValidEndTime())) { if (now.isAfter(coupon.getValidEndTime())) {
return "优惠券已过期"; return "优惠券已过期";
} }
...@@ -689,11 +568,9 @@ public class CouponVerificationService { ...@@ -689,11 +568,9 @@ public class CouponVerificationService {
return "优惠券已被使用"; return "优惠券已被使用";
} }
// 3. 根据抵扣类型检查门槛金额 // 3. 校验门槛金额(不管抵扣类型,只根据订单金额校验门槛)
BigDecimal transactionAmount = coupon.getDeductionType() != null && coupon.getDeductionType() == 1
? orderPrice : commissionPrice;
if (coupon.getThresholdAmount() != null && if (coupon.getThresholdAmount() != null &&
transactionAmount.compareTo(coupon.getThresholdAmount()) < 0) { orderPrice.compareTo(coupon.getThresholdAmount()) < 0) {
return "未达到使用门槛"; return "未达到使用门槛";
} }
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!