93 lines
2.3 KiB
PHP
93 lines
2.3 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
|
use Carbon\Carbon;
|
|
|
|
class TenantPackage extends Model
|
|
{
|
|
use HasFactory;
|
|
|
|
protected $table = 'tenant_packages';
|
|
|
|
protected $fillable = [
|
|
'tenant_id',
|
|
'package_id',
|
|
'purchased_price',
|
|
'purchased_at',
|
|
'expires_at',
|
|
'used_events',
|
|
'active',
|
|
];
|
|
|
|
protected $casts = [
|
|
'purchased_price' => 'decimal:2',
|
|
'purchased_at' => 'datetime',
|
|
'expires_at' => 'datetime',
|
|
'used_events' => 'integer',
|
|
'active' => 'boolean',
|
|
];
|
|
|
|
public function tenant(): BelongsTo
|
|
{
|
|
return $this->belongsTo(Tenant::class);
|
|
}
|
|
|
|
public function package(): BelongsTo
|
|
{
|
|
return $this->belongsTo(Package::class);
|
|
}
|
|
|
|
public function isActive(): bool
|
|
{
|
|
return $this->active && (!$this->expires_at || $this->expires_at->isFuture());
|
|
}
|
|
|
|
public function canCreateEvent(): bool
|
|
{
|
|
if (!$this->isActive()) {
|
|
return false;
|
|
}
|
|
|
|
if (!$this->package->isReseller()) {
|
|
return false;
|
|
}
|
|
|
|
$maxEvents = $this->package->max_events_per_year ?? 0;
|
|
return $this->used_events < $maxEvents;
|
|
}
|
|
|
|
public function getRemainingEventsAttribute(): int
|
|
{
|
|
if (!$this->package->isReseller()) {
|
|
return 0;
|
|
}
|
|
|
|
$max = $this->package->max_events_per_year ?? 0;
|
|
return max(0, $max - $this->used_events);
|
|
}
|
|
|
|
protected static function boot()
|
|
{
|
|
parent::boot();
|
|
|
|
static::creating(function ($tenantPackage) {
|
|
if (!$tenantPackage->purchased_at) {
|
|
$tenantPackage->purchased_at = now();
|
|
}
|
|
if (!$tenantPackage->expires_at && $tenantPackage->package) {
|
|
$tenantPackage->expires_at = now()->addYear(); // Standard für Reseller
|
|
}
|
|
$tenantPackage->active = true;
|
|
});
|
|
|
|
static::updating(function ($tenantPackage) {
|
|
if ($tenantPackage->isDirty('expires_at') && $tenantPackage->expires_at->isPast()) {
|
|
$tenantPackage->active = false;
|
|
}
|
|
});
|
|
}
|
|
} |