6
0
Fork 0
release
李静 2022-05-18 03:40:52 +00:00 committed by Gitee
parent 136ea25ded
commit 83e8e29de3
No known key found for this signature in database
GPG Key ID: 173E9B9CA92EEF8F
1 changed files with 44 additions and 0 deletions

View File

@ -182,4 +182,48 @@ class CouponService
'activity_id' => $activityId ?? null,
];
}
/**
* 送优惠券
*
* @param \App\Models\User $user
* @param \App\Models\Coupon $coupon
* @param int $num
* @return void
*/
public function sendCoupon(User $user, Coupon $coupon, int $num)
{
// 如果优惠券数量有限制,需扣除优惠券库存
if ($coupon->limit > 0) {
if ($coupon->stock < $num) {
throw new BizException('优惠券数量不足');
}
$coupon->decrement('stock', $num);
}
$coupon->increment('sent', $num);
$tz = now();
$coupons = [];
for ($i = 0; $i < $num; $i++) {
$coupons[] = [
'user_id' => $user->id,
'coupon_id' => $coupon->id,
'coupon_name' => $coupon->name,
'coupon_type' => $coupon->type,
'coupon_amount' => (int) bcmul($coupon->amount, 100),
'coupon_threshold'=> (int) bcmul($coupon->threshold, 100),
'use_start_at' => $coupon->use_start_at ?: $tz,
'use_end_at' => $coupon->use_end_at ?: $tz->copy()->addDays($coupon->use_day),
'activity_id' => null,
'created_at' => $tz,
'updated_at' => $tz,
];
}
UserCoupon::insert($coupons);
}
}