fix(coupon): 修复优惠券重复领取和状态检查逻辑

- 修改数据库查询方法返回类型为List以支持多条记录查询
- 更新AutoCouponServiceImpl中的重复领取检查逻辑
- 在CouponServiceImpl中实现可用优惠券筛选功能
- 优化优惠券状态验证逻辑并改进错误信息提示
- 修复使用优惠券时的状态判断条件
This commit is contained in:
2026-01-20 15:53:33 +08:00
parent 143426db1f
commit e268d236f4
3 changed files with 17 additions and 7 deletions

View File

@@ -33,7 +33,7 @@ public interface PriceCouponClaimRecordMapper extends BaseMapper<PriceCouponClai
*/
@Select("SELECT * FROM price_coupon_claim_record " +
"WHERE user_id = #{userId} AND coupon_id = #{couponId}")
PriceCouponClaimRecord selectUserCouponRecord(@Param("userId") Long userId,
List<PriceCouponClaimRecord> selectUserCouponRecords(@Param("userId") Long userId,
@Param("couponId") Long couponId);
/**

View File

@@ -54,12 +54,14 @@ public class AutoCouponServiceImpl implements IAutoCouponService {
for (Long couponId : couponIds) {
try {
// 检查用户是否已领取过该券(领券即消耗首次资格)
PriceCouponClaimRecord existingRecord = couponClaimRecordMapper.selectUserCouponRecord(
List<PriceCouponClaimRecord> existingRecords = couponClaimRecordMapper.selectUserCouponRecords(
memberId,
couponId
);
if (existingRecord != null) {
if (existingRecords != null && !existingRecords.isEmpty()) {
// 只要有记录(无论状态),都算已领取过
PriceCouponClaimRecord existingRecord = existingRecords.get(0);
log.debug("用户已领取过优惠券,跳过: memberId={}, couponId={}, claimTime={}",
memberId, couponId, existingRecord.getClaimTime());
skipCount++;

View File

@@ -223,15 +223,23 @@ public class CouponServiceImpl implements ICouponService {
@Override
@Transactional
public CouponUseResult useCoupon(CouponUseRequest request) {
PriceCouponClaimRecord record = couponClaimRecordMapper.selectUserCouponRecord(
List<PriceCouponClaimRecord> records = couponClaimRecordMapper.selectUserCouponRecords(
request.getUserId(), request.getCouponId());
if (record == null) {
if (records == null || records.isEmpty()) {
throw new CouponInvalidException("用户未拥有该优惠券");
}
// 查找一张可用的优惠券(状态为CLAIMED)
PriceCouponClaimRecord record = records.stream()
.filter(r -> r.getStatus() == CouponStatus.CLAIMED)
.findFirst()
.orElse(null);
if (record.getStatus() != CouponStatus.CLAIMED) {
throw new CouponInvalidException("优惠券状态无效: " + record.getStatus());
if (record == null) {
// 如果没有可用的,抛出异常。为了错误信息准确,可以检查最后一张的状态
CouponStatus lastStatus = records.getFirst().getStatus();
throw new CouponInvalidException("优惠券状态无效: " + lastStatus);
}
int updateCount = couponConfigMapper.incrementUsedQuantity(request.getCouponId());