Commit b81fc7a1 by 章家宝

feat:优惠券需求,优惠券模板手动发放扣减库存改为原子性操作

1 parent db34dcf7
......@@ -6,6 +6,9 @@ import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.EntityGraph;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.summerframework.orm.BaseRepository;
......@@ -87,4 +90,17 @@ public interface CouponTemplateRepository extends BaseRepository<CouponTemplate,
* @return 是否存在
*/
boolean existsByTemplateIdAndDeleteFlag(String templateId, String deleteFlag);
/**
* 原子扣减库存(防止超发)
* 使用数据库级别的原子操作,确保并发安全
*
* @param templateId 模板 ID
* @param deductQuantity 扣减数量
* @return 影响的行数,如果返回 0 表示库存不足
*/
@Modifying
@Query("UPDATE CouponTemplate t SET t.remainingQuantity = t.remainingQuantity - :deductQuantity " +
"WHERE t.id = :templateId AND t.remainingQuantity >= :deductQuantity AND t.deleteFlag = 'N'")
int deductStock(@Param("templateId") Long templateId, @Param("deductQuantity") Integer deductQuantity);
}
......@@ -339,7 +339,7 @@ public class CouponTemplateService {
throw new BusinessCodeException(ErrorCodeEnum.COMMON_ERROR, "优惠券模板已停用,无法发放");
}
// 3. 校验库存
// 3. 校验库存(初步校验,实际扣减时使用原子操作)
if (template.getRemainingQuantity() != null && template.getRemainingQuantity() < vo.getAccountIds().size()) {
throw new BusinessCodeException(ErrorCodeEnum.COMMON_ERROR, "库存不足,剩余库存:" + template.getRemainingQuantity());
}
......@@ -359,8 +359,10 @@ public class CouponTemplateService {
validEndTime = validStartTime.plusDays(validDays);
}
// 5. 为每个用户发放优惠券
// 5. 为每个用户发放优惠券(逐个扣减库存,防止超发)
int successCount = 0;
int insufficientStockCount = 0;
for (Integer accountId : vo.getAccountIds()) {
try {
// 查询用户信息
......@@ -370,6 +372,16 @@ public class CouponTemplateService {
continue;
}
// 先扣减库存(原子操作,防止并发超发)
if (template.getRemainingQuantity() != null) {
int affectedRows = couponTemplateRepository.deductStock(template.getId(), 1);
if (affectedRows == 0) {
insufficientStockCount++;
log.warn("库存不足,跳过发放:accountId={}, templateId={}", accountId, template.getId());
continue;
}
}
// 生成优惠券实例 ID
String couponId = "CPN" + System.currentTimeMillis() + UUID.randomUUID().toString().replace("-", "").substring(0, 6).toUpperCase();
......@@ -427,10 +439,11 @@ public class CouponTemplateService {
}
}
// 6. 扣减库存
if (template.getRemainingQuantity() != null) {
template.setRemainingQuantity(template.getRemainingQuantity() - successCount);
couponTemplateRepository.save(template);
// 6. 输出统计信息
if (insufficientStockCount > 0) {
log.warn("库存不足导致部分发放失败:templateId={}, 库存不足跳过={}张",
vo.getTemplateId(), insufficientStockCount);
throw new BusinessCodeException(ErrorCodeEnum.COMMON_ERROR, String.format("库存不足导致部分发放失败:库存不足跳过%d张", insufficientStockCount));
}
log.info("手动发放优惠券完成:templateId={}, 应发放={}, 成功发放={}",
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!