Coupon.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. <?php
  2. namespace App\Models;
  3. use App\Settings\CouponSettings;
  4. use Illuminate\Database\Eloquent\Factories\HasFactory;
  5. use Illuminate\Database\Eloquent\Model;
  6. use Spatie\Activitylog\LogOptions;
  7. use Spatie\Activitylog\Traits\LogsActivity;
  8. use Carbon\Carbon;
  9. use Illuminate\Database\Eloquent\Relations\BelongsToMany;
  10. class Coupon extends Model
  11. {
  12. use HasFactory, LogsActivity;
  13. public function getActivitylogOptions(): LogOptions
  14. {
  15. return LogOptions::defaults()
  16. ->logOnlyDirty()
  17. ->logOnly(['*'])
  18. ->dontSubmitEmptyLogs();
  19. }
  20. /**
  21. * @var string[]
  22. */
  23. protected $fillable = [
  24. 'code',
  25. 'type',
  26. 'value',
  27. 'uses',
  28. 'max_uses',
  29. 'expires_at'
  30. ];
  31. /**
  32. * @var string[]
  33. */
  34. protected $casts = [
  35. 'value' => 'float',
  36. 'uses' => 'integer',
  37. 'max_uses' => 'integer',
  38. 'expires_at' => 'timestamp'
  39. ];
  40. /**
  41. * Returns the date format used by the coupons.
  42. *
  43. * @return string
  44. */
  45. public static function formatDate(): string
  46. {
  47. return 'Y-MM-DD HH:mm:ss';
  48. }
  49. /**
  50. * Returns the current state of the coupon.
  51. *
  52. * @return string
  53. */
  54. public function getStatus()
  55. {
  56. if ($this->uses >= $this->max_uses) {
  57. return 'USES_LIMIT_REACHED';
  58. }
  59. if (!is_null($this->expires_at)) {
  60. if ($this->expires_at <= Carbon::now(config('app.timezone'))->timestamp) {
  61. return __('EXPIRED');
  62. }
  63. }
  64. return __('VALID');
  65. }
  66. /**
  67. * Check if a user has already exceeded the uses of a coupon.
  68. *
  69. * @param User $user The request being made.
  70. *
  71. * @return bool
  72. */
  73. public function isMaxUsesReached($user): bool
  74. {
  75. $coupon_settings = new CouponSettings;
  76. $coupon_uses = $user->coupons()->where('id', $this->id)->count();
  77. return $coupon_uses >= $coupon_settings->max_uses_per_user;
  78. }
  79. /**
  80. * Generate a specified quantity of coupon codes.
  81. *
  82. * @param int $amount Amount of coupons to be generated.
  83. *
  84. * @return array
  85. */
  86. public static function generateRandomCoupon(int $amount = 10): array
  87. {
  88. $coupons = [];
  89. for ($i = 0; $i < $amount; $i++) {
  90. $random_coupon = strtoupper(bin2hex(random_bytes(3)));
  91. $coupons[] = $random_coupon;
  92. }
  93. return $coupons;
  94. }
  95. /**
  96. * @return BelongsToMany
  97. */
  98. public function users()
  99. {
  100. return $this->belongsToMany(User::class, 'user_coupons');
  101. }
  102. }