diff --git a/app/Services/CouponService.php b/app/Services/CouponService.php index 21200aba..dcae3adb 100644 --- a/app/Services/CouponService.php +++ b/app/Services/CouponService.php @@ -8,6 +8,7 @@ use App\Models\ProductPart; use App\Models\ReceivePartCouponLog; use App\Models\User; use App\Models\UserCoupon; +use Illuminate\Database\QueryException; class CouponService { @@ -112,17 +113,27 @@ class CouponService protected function receiveSomeCoupons(User $user, array $coupons, ?int $activityId = null) { $userCoupons = []; - foreach ($coupons as $coupon) { - for ($i = 0; $i < $coupon['num']; $i++) { - $userCoupons[] = self::createUserCouponData($user->id, $coupon['coupon'], $activityId ?? null); - } + foreach ($coupons as $key=> $coupon) { //更新对应券发送量,余量; - $coupon['coupon']->increment('sent', $coupon['num']); - if ($coupon['coupon']->limit > 0) {//限量才减少余量 - $coupon['coupon']->decrement('stock', $coupon['num']); + try { + $canSent = true; + if ($coupon['coupon']->limit > 0) {//限量才减少余量 + $coupon['coupon']->decrement('stock', $coupon['num']); + } + } catch (QueryException $e) { + if (strpos($e->getMessage(), 'Numeric value out of range') !== false) { + $canSent = false; + } else { + throw new $e(); + } + } + if ($canSent) { + for ($i = 0; $i < $coupon['num']; $i++) { + $userCoupons[] = self::createUserCouponData($user->id, $coupon['coupon'], $activityId ?? null); + } + $coupon['coupon']->increment('sent', $coupon['num']); } } - // dd($userCoupons); UserCoupon::insert($userCoupons); }