ctrlpanel/app/Models/Voucher.php

131 lines
2.6 KiB
PHP
Raw Permalink Normal View History

2021-07-09 22:18:22 +00:00
<?php
namespace App\Models;
use Exception;
2021-07-09 22:18:22 +00:00
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
2023-01-05 18:33:46 +00:00
use Spatie\Activitylog\LogOptions;
use Spatie\Activitylog\Traits\LogsActivity;
2021-07-09 22:18:22 +00:00
/**
* Class Voucher
*/
class Voucher extends Model
{
use HasFactory, LogsActivity;
2023-01-05 18:33:46 +00:00
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()
-> logOnlyDirty()
-> logOnly(['*'])
-> dontSubmitEmptyLogs();
}
2021-07-09 22:18:22 +00:00
/**
* @var string[]
*/
protected $fillable = [
'memo',
'code',
'credits',
'uses',
'expires_at',
];
2023-01-05 17:03:38 +00:00
2021-10-02 16:29:32 +00:00
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'expires_at' => 'datetime',
2021-10-02 16:29:32 +00:00
'credits' => 'float',
'uses' => 'integer', ];
2021-10-02 16:29:32 +00:00
protected $appends = ['used', 'status'];
2021-07-15 20:16:26 +00:00
/**
* @return int
*/
public function getUsedAttribute()
{
return $this->users()->count();
}
/**
* @return string
*/
2021-10-02 16:29:32 +00:00
public function getStatusAttribute()
{
2021-07-15 20:16:26 +00:00
return $this->getStatus();
}
2021-07-09 22:18:22 +00:00
public static function boot()
{
parent::boot();
static::deleting(function (Voucher $voucher) {
$voucher->users()->detach();
});
}
/**
* @return BelongsToMany
*/
public function users()
{
return $this->belongsToMany(User::class);
}
2021-07-10 06:58:11 +00:00
/**
* @return string
*/
public function getStatus()
{
if ($this->users()->count() >= $this->uses) {
return 'USES_LIMIT_REACHED';
}
if (! is_null($this->expires_at)) {
if ($this->expires_at->isPast()) {
return __('EXPIRED');
}
2021-07-10 06:58:11 +00:00
}
2021-12-13 15:27:56 +00:00
return __('VALID');
2021-07-09 22:18:22 +00:00
}
/**
* @param User $user
2021-07-10 06:58:11 +00:00
* @return float
*
* @throws Exception
2021-07-10 06:58:11 +00:00
*/
public function redeem(User $user)
{
2021-07-10 06:58:11 +00:00
try {
$user->increment('credits', $this->credits);
2021-07-10 06:58:11 +00:00
$this->users()->attach($user);
$this->logRedeem($user);
} catch (Exception $exception) {
2021-07-10 06:58:11 +00:00
throw $exception;
}
return $this->credits;
}
/**
* @param User $user
* @return null
2021-07-09 22:18:22 +00:00
*/
private function logRedeem(User $user)
2021-07-09 22:18:22 +00:00
{
activity()
->performedOn($this)
->causedBy($user)
->log('redeemed');
return null;
2021-07-09 22:18:22 +00:00
}
}