CouponService.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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 $coupon;
  9. public $planId;
  10. public $userId;
  11. public function __construct($code)
  12. {
  13. $this->coupon = Coupon::where('code', $code)->first();
  14. }
  15. public function use(Order $order):bool
  16. {
  17. $this->setPlanId($order->plan_id);
  18. $this->setUserId($order->user_id);
  19. $this->check();
  20. switch ($this->coupon->type) {
  21. case 1:
  22. $order->discount_amount = $this->coupon->value;
  23. break;
  24. case 2:
  25. $order->discount_amount = $order->total_amount * ($this->coupon->value / 100);
  26. break;
  27. }
  28. if ($this->coupon->limit_use !== NULL) {
  29. $this->coupon->limit_use = $this->coupon->limit_use - 1;
  30. if (!$this->coupon->save()) {
  31. return false;
  32. }
  33. }
  34. return true;
  35. }
  36. public function getId()
  37. {
  38. return $this->coupon->id;
  39. }
  40. public function getCoupon()
  41. {
  42. return $this->coupon;
  43. }
  44. public function setPlanId($planId)
  45. {
  46. $this->planId = $planId;
  47. }
  48. public function setUserId($userId)
  49. {
  50. $this->userId = $userId;
  51. }
  52. public function checkLimitUseWithUser():bool
  53. {
  54. $usedCount = Order::where('coupon_id', $this->coupon->id)
  55. ->where('user_id', $this->userId)
  56. ->whereNotIn('status', [0, 2])
  57. ->count();
  58. if ($usedCount >= $this->coupon->limit_use_with_user) return false;
  59. return true;
  60. }
  61. public function check()
  62. {
  63. if (!$this->coupon) {
  64. abort(500, __('Invalid coupon'));
  65. }
  66. if ($this->coupon->limit_use <= 0 && $this->coupon->limit_use !== NULL) {
  67. abort(500, __('This coupon is no longer available'));
  68. }
  69. if (time() < $this->coupon->started_at) {
  70. abort(500, __('This coupon has not yet started'));
  71. }
  72. if (time() > $this->coupon->ended_at) {
  73. abort(500, __('This coupon has expired'));
  74. }
  75. if ($this->coupon->limit_plan_ids && $this->planId) {
  76. if (!in_array($this->planId, $this->coupon->limit_plan_ids)) {
  77. abort(500, __('The coupon code cannot be used for this subscription'));
  78. }
  79. }
  80. if ($this->coupon->limit_use_with_user !== NULL && $this->userId) {
  81. if (!$this->checkLimitUseWithUser()) {
  82. abort(500, __('The coupon can only be used :limit_use_with_user per person', [
  83. 'limit_use_with_user' => $this->coupon->limit_use_with_user
  84. ]));
  85. }
  86. }
  87. }
  88. }