87 lines
2 KiB
PHP
87 lines
2 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
|
|
|
class RegistrationCode extends Model
|
|
{
|
|
use HasFactory;
|
|
|
|
public const STATUS_AVAILABLE = 'available';
|
|
public const STATUS_USED = 'used';
|
|
public const STATUS_EXPIRED = 'expired';
|
|
|
|
protected $fillable = [
|
|
'code',
|
|
'role',
|
|
'name',
|
|
'status',
|
|
'broker_partner_id',
|
|
'partner_id',
|
|
'assigned_to_code_id',
|
|
'used_by_user_id',
|
|
'used_at',
|
|
'expires_at',
|
|
'metadata',
|
|
];
|
|
|
|
protected $casts = [
|
|
'metadata' => 'array',
|
|
'expires_at' => 'datetime',
|
|
'used_at' => 'datetime',
|
|
];
|
|
|
|
public function broker(): BelongsTo
|
|
{
|
|
return $this->belongsTo(Partner::class, 'broker_partner_id');
|
|
}
|
|
|
|
public function partner(): BelongsTo
|
|
{
|
|
return $this->belongsTo(Partner::class);
|
|
}
|
|
|
|
public function usedBy(): BelongsTo
|
|
{
|
|
return $this->belongsTo(User::class, 'used_by_user_id');
|
|
}
|
|
|
|
public function assignedToCode(): BelongsTo
|
|
{
|
|
return $this->belongsTo(RegistrationCode::class, 'assigned_to_code_id');
|
|
}
|
|
|
|
public function scopeAvailable($query)
|
|
{
|
|
return $query->where('status', self::STATUS_AVAILABLE);
|
|
}
|
|
|
|
public function isAvailable(): bool
|
|
{
|
|
if ($this->status !== self::STATUS_AVAILABLE) {
|
|
return false;
|
|
}
|
|
|
|
if ($this->expires_at && now()->greaterThan($this->expires_at)) {
|
|
return false;
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
public function markUsed(?User $user = null): void
|
|
{
|
|
$this->status = self::STATUS_USED;
|
|
$this->used_at = now();
|
|
if ($user) {
|
|
$this->used_by_user_id = $user->id;
|
|
if ($user->partner_id && !$this->partner_id) {
|
|
$this->partner_id = $user->partner_id;
|
|
}
|
|
}
|
|
$this->save();
|
|
}
|
|
}
|