Commit 080022e4 by 章家宝

fixbug:优惠券金额计算

1 parent 0f60137a
......@@ -64,7 +64,7 @@ public interface CouponAccountRepository extends BaseRepository<CouponAccount, L
* @param now 当前时间
* @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(
@Param("accountId") Integer accountId,
@Param("status") Integer status,
......
......@@ -44,48 +44,6 @@ public class CouponVerificationService {
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>
*/
private Map<String, CouponOrderUsage> loadUsageMap(List<CouponAccount> coupons) {
......@@ -136,127 +94,51 @@ public class CouponVerificationService {
}
/**
* 基于预加载 Map 计算优惠券实际抵扣金额(抵扣车款),无 DB 查询
*/
private BigDecimal calculateActualDeductionFromCache(CouponAccount coupon, BigDecimal transactionAmount,
Map<Long, CouponTemplate> templateMap,
Map<String, List<CouponTierRule>> tierRuleMap) {
BigDecimal faceAmount = coupon.getFaceAmount();
if (!CouponTypeEnum.TIERED_AMOUNT.getCode().equals(coupon.getCouponType())) {
// 固定面额券:直接返回面额
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;
}
/**
* 计算优惠券实际抵扣金额(用于抵扣车款)
* 计算优惠券实际抵扣金额
*
* @param coupon 优惠券
* @param orderPrice 订单金额(车款),用于门槛校验
* @param targetAmount 目标抵扣金额(车款或佣金),用于限制最大抵扣金额
* @param templateMap 模板缓存(可为空,非阶梯券不需要)
* @param tierRuleMap 阶梯规则缓存(可为空,非阶梯券不需要)
* @return 实际抵扣金额(不超过目标抵扣金额)
*/
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 rawDeduction;
// 根据优惠券类型计算抵扣金额
if (CouponTypeEnum.TIERED_AMOUNT.getCode().equals(coupon.getCouponType())) {
// 阶梯满减券:根据成交价和阶梯规则计算
return calculateTieredDeduction(coupon.getTemplateId(), transactionAmount, faceAmount);
if (!CouponTypeEnum.TIERED_AMOUNT.getCode().equals(coupon.getCouponType())) {
// 固定面额券:直接使用面额
rawDeduction = faceAmount;
} else {
// 固定面额券:直接返回面额
return faceAmount;
}
}
/**
* 计算阶梯满减券的抵扣金额
*
* @param templateDbId 模板数据库 ID(Long 类型)
* @param transactionAmount 订单成交价
* @param faceAmount 券面额(最高抵扣金额)
* @return 实际抵扣金额
*/
private BigDecimal calculateTieredDeduction(Long templateDbId, BigDecimal transactionAmount, BigDecimal faceAmount) {
// 1. 查询模板获取 template_id(字符串)
CouponTemplate template = couponTemplateRepository.findByIdAndDeleteFlag(templateDbId, DeleteFlag.NOT_DELETED.getCode())
.orElseThrow(() -> new BusinessCodeException(ErrorCodeEnum.DATA_NOT_EXISTS, "优惠券模板不存在"));
// 2. 查询该模板的所有阶梯规则
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;
// 阶梯券:从缓存 Map 取模板和阶梯规则,门槛校验只根据订单金额(orderPrice)
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());
rawDeduction = BigDecimal.ZERO;
} else {
// 阶梯门槛校验只根据订单金额(orderPrice),不管抵扣类型
Optional<CouponTierRule> matchedTier = tierRules.stream()
.filter(rule -> orderPrice.compareTo(rule.getThresholdAmount()) >= 0)
.max(Comparator.comparing(CouponTierRule::getThresholdAmount));
if (matchedTier.isPresent()) {
BigDecimal tierDeduction = matchedTier.get().getDeductionAmount();
rawDeduction = tierDeduction.compareTo(faceAmount) > 0 ? faceAmount : tierDeduction;
} else {
rawDeduction = BigDecimal.ZERO;
}
}
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 {
*
* @param accountId 用户账户 ID
* @param orderId 订单 ID
* @param orderCode 订单编号
* @param couponId 优惠券实例 ID
* @param transactionAmount 订单成交价
* @param vehicleId 车辆 ID
* @param vehicleInfo 车辆信息
* @return 实际抵扣金额
*/
@Transactional(rollbackFor = Exception.class)
......@@ -292,8 +170,7 @@ public class CouponVerificationService {
BigDecimal orderPrice = BigDecimal.valueOf(order.getOrderPrice());
BigDecimal commissionPrice = BigDecimal.valueOf(order.getCommissionPrice());
// 根据抵扣类型计算交易金额:车款抵扣用成交价,佣金抵扣用佣金
BigDecimal transactionAmount = coupon.getDeductionType() != null && coupon.getDeductionType() == 1
BigDecimal targetAmount = coupon.getDeductionType() != null && coupon.getDeductionType() == 1
? orderPrice : commissionPrice;
// 获取车辆信息
......@@ -321,7 +198,7 @@ public class CouponVerificationService {
.findByOrderIdAndDeleteFlag(orderId, DeleteFlag.NOT_DELETED.getCode())
.orElse(null);
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 {
throw new BusinessCodeException(ErrorCodeEnum.COMMON_ERROR, "优惠券已被其他订单使用");
}
// 8. 校验使用门槛
if (coupon.getThresholdAmount() != null &&
transactionAmount.compareTo(coupon.getThresholdAmount()) < 0) {
throw new BusinessCodeException(ErrorCodeEnum.COMMON_ERROR,
// 8. 校验使用门槛(不管抵扣类型,只根据订单金额校验门槛)
if (coupon.getThresholdAmount() != null
&& orderPrice.compareTo(coupon.getThresholdAmount()) < 0) {
throw new BusinessCodeException(ErrorCodeEnum.COMMON_ERROR,
"订单金额未达到优惠券使用门槛,门槛金额:" + coupon.getThresholdAmount() + "元");
}
// 9. 计算实际抵扣金额
BigDecimal actualDeduction = calculateActualDeduction(coupon, transactionAmount);
// 10. 对于阶梯券,校验是否达到阶梯门槛
if (CouponTypeEnum.TIERED_AMOUNT.getCode().equals(coupon.getCouponType())) {
if (actualDeduction.compareTo(BigDecimal.ZERO) <= 0) {
throw new BusinessCodeException(ErrorCodeEnum.COMMON_ERROR,
"订单金额未达到阶梯券使用门槛");
}
}
Map<Long, CouponTemplate> templateMap = loadTemplateMapForTiered(List.of(coupon));
Map<String, List<CouponTierRule>> tierRuleMap = loadTierRuleMap(templateMap);
BigDecimal actualDeduction = calculateActualDeduction(
coupon, orderPrice, targetAmount, templateMap, tierRuleMap);
// 11. 更新优惠券状态为已核销
coupon.setStatus(CouponUserStatusEnum.VERIFIED.getCode());
......@@ -388,7 +260,7 @@ public class CouponVerificationService {
.orderCode(orderCode)
.vehicleId(vehicleId)
.vehicleInfo(vehicleInfo)
.transactionAmount(transactionAmount)
.transactionAmount(orderPrice)
.faceAmount(coupon.getFaceAmount())
.actualDeduction(actualDeduction)
.isDowngraded(actualDeduction.compareTo(coupon.getFaceAmount()) < 0 ? 1 : 0)
......@@ -555,10 +427,12 @@ public class CouponVerificationService {
// 转换为VO并判断可用性(actualDeduction 每张券只计算一次)
List<OrderCouponRespVO> couponVOList = allCoupons.stream()
.map(coupon -> {
BigDecimal pickedAmount = coupon.getDeductionType() != null && coupon.getDeductionType() == 1
// 根据抵扣类型确定目标抵扣金额(限制最大抵扣金额)
BigDecimal targetAmount = coupon.getDeductionType() != null && coupon.getDeductionType() == 1
? orderPrice : commissionPrice;
BigDecimal actualDeduction = calculateActualDeductionFromCache(
coupon, pickedAmount, templateMap, tierRuleMap);
// 计算实际抵扣金额:门槛校验用 orderPrice,最大抵扣限制用 targetAmount
BigDecimal actualDeduction = calculateActualDeduction(
coupon, orderPrice, targetAmount, templateMap, tierRuleMap);
String unavailableReason = checkCouponUnavailableReason(
coupon, orderPrice, commissionPrice, now, usageMap, actualDeduction);
return convertToOrderCouponVO(coupon, maxVehicleDeduction, maxCommissionDeduction,
......@@ -678,7 +552,12 @@ public class CouponVerificationService {
BigDecimal commissionPrice, LocalDateTime now,
Map<String, CouponOrderUsage> usageMap,
BigDecimal actualDeduction) {
// 1. 已过期
// 1. 未生效
if (now.isBefore(coupon.getValidStartTime())) {
return "优惠券未生效";
}
// 2. 已过期
if (now.isAfter(coupon.getValidEndTime())) {
return "优惠券已过期";
}
......@@ -689,11 +568,9 @@ public class CouponVerificationService {
return "优惠券已被使用";
}
// 3. 根据抵扣类型检查门槛金额
BigDecimal transactionAmount = coupon.getDeductionType() != null && coupon.getDeductionType() == 1
? orderPrice : commissionPrice;
// 3. 校验门槛金额(不管抵扣类型,只根据订单金额校验门槛)
if (coupon.getThresholdAmount() != null &&
transactionAmount.compareTo(coupon.getThresholdAmount()) < 0) {
orderPrice.compareTo(coupon.getThresholdAmount()) < 0) {
return "未达到使用门槛";
}
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!