CouponService.php 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. <?php
  2. namespace App\Services;
  3. use App\Models\Coupon;
  4. use App\Models\Order;
  5. use Illuminate\Support\Facades\DB;
  6. class CouponService
  7. {
  8. public $order;
  9. public function __construct($code)
  10. {
  11. $this->coupon = Coupon::where('code', $code)->first();
  12. if (!$this->coupon) {
  13. abort(500, '优惠券无效');
  14. }
  15. if ($this->coupon->limit_use <= 0 && $this->coupon->limit_use !== NULL) {
  16. abort(500, '优惠券已无可用次数');
  17. }
  18. if (time() < $this->coupon->started_at) {
  19. abort(500, '优惠券还未到可用时间');
  20. }
  21. if (time() > $this->coupon->ended_at) {
  22. abort(500, '优惠券已过期');
  23. }
  24. }
  25. public function use(Order $order)
  26. {
  27. switch ($this->coupon->type) {
  28. case 1:
  29. $order->discount_amount = $this->coupon->value;
  30. break;
  31. case 2:
  32. $order->discount_amount = $order->total_amount * ($this->coupon->value / 100);
  33. break;
  34. }
  35. if ($this->coupon->limit_use !== NULL) {
  36. $this->coupon->limit_use = $this->coupon->limit_use - 1;
  37. if (!$this->coupon->save()) {
  38. return false;
  39. }
  40. }
  41. return true;
  42. }
  43. }