|
|
@@ -73,15 +73,30 @@ public class GiftCardServiceImpl extends ServiceImpl<GiftCardMapper, GiftCard> i
|
|
|
return false;
|
|
|
}
|
|
|
|
|
|
- // 1. 扣减库存(使用乐观锁防止超卖)
|
|
|
- // 使用逗号拼接多个字段的原子更新操作,避免使用 String.format
|
|
|
- String updateExpr = "stock = stock - " + quantity + ", sales = sales + " + quantity;
|
|
|
+ // 2. 校验购物卡状态
|
|
|
+ if (card.getIsDelete() != NOT_DELETE) {
|
|
|
+ log.warn("购买失败,购物卡已删除,ID: {}", id);
|
|
|
+ return false;
|
|
|
+ }
|
|
|
+ if (card.getIsPublished() != PUBLISHED) {
|
|
|
+ log.warn("购买失败,购物卡未上架,ID: {}", id);
|
|
|
+ return false;
|
|
|
+ }
|
|
|
+
|
|
|
+ // 3. 校验库存是否充足
|
|
|
+ if (card.getStock() < quantity) {
|
|
|
+ log.warn("购买失败,库存不足,ID: {},库存: {},需求数量: {}", id, card.getStock(), quantity);
|
|
|
+ return false;
|
|
|
+ }
|
|
|
+
|
|
|
+ // 4. 扣减库存(使用乐观锁防止超卖)
|
|
|
+ String updateExpr = String.format("stock = stock - %d, sales = sales + %d", quantity, quantity);
|
|
|
|
|
|
LambdaUpdateWrapper<GiftCard> updateWrapper = new LambdaUpdateWrapper<>();
|
|
|
updateWrapper.eq(GiftCard::getId, id)
|
|
|
- .eq(GiftCard::getIsDelete, NOT_DELETE) // 确保商品未被删除
|
|
|
- .eq(GiftCard::getIsPublished, PUBLISHED) // 确保商品已上架
|
|
|
- .ge(GiftCard::getStock, quantity) // 核心:库存必须大于等于购买数量
|
|
|
+ .eq(GiftCard::getIsDelete, NOT_DELETE)
|
|
|
+ .eq(GiftCard::getIsPublished, PUBLISHED)
|
|
|
+ .ge(GiftCard::getStock, quantity) // 关键:确保库存充足
|
|
|
.setSql(updateExpr);
|
|
|
|
|
|
int rowsAffected = this.baseMapper.update(null, updateWrapper);
|
|
|
@@ -93,9 +108,11 @@ public class GiftCardServiceImpl extends ServiceImpl<GiftCardMapper, GiftCard> i
|
|
|
|
|
|
log.info("购买成功,购物卡ID: {}, 数量: {}", id, quantity);
|
|
|
|
|
|
- // 异步创建订单
|
|
|
+ // 5. 异步创建订单(传入完整的购物卡对象,避免异步方法中再次查询)
|
|
|
createOrderAsync(card, quantity, merchantId);
|
|
|
|
|
|
+ // 6. 异步添加购物金明细 TODO
|
|
|
+
|
|
|
return true;
|
|
|
}
|
|
|
|
|
|
@@ -123,11 +140,17 @@ public class GiftCardServiceImpl extends ServiceImpl<GiftCardMapper, GiftCard> i
|
|
|
@Async
|
|
|
public void createOrderAsync(GiftCard card, Integer quantity, String merchantId) {
|
|
|
try {
|
|
|
- this.giftCardOrderService.buildOrders(card, quantity, merchantId);
|
|
|
- log.info("购物卡订单创建成功");
|
|
|
+ // 注意:异步方法中不要依赖主线程的事务,订单创建失败不应影响库存扣减
|
|
|
+ List<GiftCardOrder> orders = this.giftCardOrderService.buildOrders(card, quantity, merchantId);
|
|
|
+
|
|
|
+ if (orders != null && !orders.isEmpty()) {
|
|
|
+ log.info("购物卡订单创建成功,订单数量: {},购物卡ID: {}", orders.size(), card.getId());
|
|
|
+ } else {
|
|
|
+ log.warn("购物卡订单创建返回为空,购物卡ID: {}", card.getId());
|
|
|
+ }
|
|
|
} catch (Exception e) {
|
|
|
- log.error("异步创建订单失败,订单数据: cardId={}, quantity={}, merchantId={}", card.getId(), quantity, merchantId, e);
|
|
|
- // 可以考虑重试机制或告警
|
|
|
+ log.error("异步创建订单失败,订单数据: cardId={}, quantity={}, merchantId={}",
|
|
|
+ card.getId(), quantity, merchantId, e);
|
|
|
}
|
|
|
}
|
|
|
|