Voucher.php 2.3 KB

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