Voucher.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. <?php
  2. namespace App\Models;
  3. use Exception;
  4. use Illuminate\Database\Eloquent\Factories\HasFactory;
  5. use Illuminate\Database\Eloquent\Model;
  6. use Illuminate\Database\Eloquent\Relations\BelongsToMany;
  7. use Spatie\Activitylog\LogOptions;
  8. use Spatie\Activitylog\Traits\LogsActivity;
  9. /**
  10. * Class Voucher
  11. */
  12. class Voucher extends Model
  13. {
  14. use HasFactory, LogsActivity;
  15. public function getActivitylogOptions(): LogOptions
  16. {
  17. return LogOptions::defaults()
  18. -> logOnlyDirty()
  19. -> logOnly(['*'])
  20. -> dontSubmitEmptyLogs();
  21. }
  22. /**
  23. * @var string[]
  24. */
  25. protected $fillable = [
  26. 'memo',
  27. 'code',
  28. 'credits',
  29. 'uses',
  30. 'expires_at',
  31. ];
  32. /**
  33. * The attributes that should be cast to native types.
  34. *
  35. * @var array
  36. */
  37. protected $casts = [
  38. 'expires_at' => 'datetime',
  39. 'credits' => 'float',
  40. 'uses' => 'integer', ];
  41. protected $appends = ['used', 'status'];
  42. /**
  43. * @return int
  44. */
  45. public function getUsedAttribute()
  46. {
  47. return $this->users()->count();
  48. }
  49. /**
  50. * @return string
  51. */
  52. public function getStatusAttribute()
  53. {
  54. return $this->getStatus();
  55. }
  56. public static function boot()
  57. {
  58. parent::boot();
  59. static::deleting(function (Voucher $voucher) {
  60. $voucher->users()->detach();
  61. });
  62. }
  63. /**
  64. * @return BelongsToMany
  65. */
  66. public function users()
  67. {
  68. return $this->belongsToMany(User::class);
  69. }
  70. /**
  71. * @return string
  72. */
  73. public function getStatus()
  74. {
  75. if ($this->users()->count() >= $this->uses) {
  76. return 'USES_LIMIT_REACHED';
  77. }
  78. if (! is_null($this->expires_at)) {
  79. if ($this->expires_at->isPast()) {
  80. return __('EXPIRED');
  81. }
  82. }
  83. return __('VALID');
  84. }
  85. /**
  86. * @param User $user
  87. * @return float
  88. *
  89. * @throws Exception
  90. */
  91. public function redeem(User $user)
  92. {
  93. try {
  94. $user->increment('credits', $this->credits);
  95. $this->users()->attach($user);
  96. $this->logRedeem($user);
  97. } catch (Exception $exception) {
  98. throw $exception;
  99. }
  100. return $this->credits;
  101. }
  102. /**
  103. * @param User $user
  104. * @return null
  105. */
  106. private function logRedeem(User $user)
  107. {
  108. activity()
  109. ->performedOn($this)
  110. ->causedBy($user)
  111. ->log('redeemed');
  112. return null;
  113. }
  114. }