where('source', $source)->where('order_id', $orderId)->first(); if (!$link) return; $coupon = DB::table('promotion_coupons')->where('id', $link->coupon_id)->lockForUpdate()->first(); if (!$coupon) throw new \RuntimeException('退款优惠券记录不存在'); $use = DB::table('promotion_coupon_uses')->where('id', $link->id)->whereNull('refunded_at')->lockForUpdate()->first(); if (!$use) return; $now = PromotionFacts::now(); DB::table('promotion_coupon_uses')->where('id', $use->id)->update(['refunded_at' => $now, 'updated_at' => $now]); // Current read: an outer REPEATABLE READ transaction may already have an older snapshot. $remaining = DB::table('promotion_coupon_uses')->where('coupon_id', $use->coupon_id) ->whereNull('refunded_at')->lockForUpdate()->get(['id']); if ($remaining->isNotEmpty()) return; DB::table('promotion_coupons')->where('id', $use->coupon_id)->where('status', 'used') ->update(['status' => 'unused', 'used_source' => null, 'used_stake' => null, 'used_at' => null, 'updated_at' => $now]); }); } }