87 lines
2.2 KiB
PHP
87 lines
2.2 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use App\Enums\IsShow;
|
|
use App\Enums\VoucherType;
|
|
use Illuminate\Database\Eloquent\Attributes\Scope;
|
|
use Illuminate\Database\Eloquent\Builder;
|
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
|
use Illuminate\Database\Eloquent\Relations\HasMany;
|
|
use Illuminate\Database\Eloquent\SoftDeletes;
|
|
use Veelasky\LaravelHashId\Eloquent\HashableId;
|
|
|
|
class Voucher extends Model
|
|
{
|
|
use HasFactory, HashableId, SoftDeletes;
|
|
|
|
protected $guarded = ['id'];
|
|
|
|
protected function casts(): array
|
|
{
|
|
return [
|
|
'type' => VoucherType::class,
|
|
'discount_amount' => 'int',
|
|
'min_purchase' => 'int',
|
|
'max_discount' => 'int',
|
|
'quota' => 'int',
|
|
'available_count' => 'int',
|
|
'limit_per_user' => 'int',
|
|
'is_show' => IsShow::class,
|
|
];
|
|
}
|
|
|
|
#[Scope]
|
|
public function active(Builder $query): void
|
|
{
|
|
$query->whereDate('start_date', '<=', now())
|
|
->where(function ($q) {
|
|
$q->whereNull('end_date')
|
|
->orWhereDate('end_date', '>=', now());
|
|
});
|
|
}
|
|
|
|
#[Scope]
|
|
public function inactive(Builder $query): void
|
|
{
|
|
$query->whereDate('end_date', '<', now());
|
|
}
|
|
|
|
#[Scope]
|
|
public function upcoming(Builder $query): void
|
|
{
|
|
$query->whereDate('start_date', '>', now());
|
|
}
|
|
|
|
#[Scope]
|
|
public function forTier(Builder $query, ?int $tierId): void
|
|
{
|
|
$query->where(function ($q) use ($tierId) {
|
|
$q->whereDoesntHave('tiers')
|
|
->when($tierId, fn ($query) => $query->orWhereHas('tiers', fn ($q) => $q->where('tiers.id', $tierId)));
|
|
});
|
|
}
|
|
|
|
public function outlets(): BelongsToMany
|
|
{
|
|
return $this->belongsToMany(Outlet::class);
|
|
}
|
|
|
|
public function orders(): HasMany
|
|
{
|
|
return $this->hasMany(Order::class);
|
|
}
|
|
|
|
public function tiers(): BelongsToMany
|
|
{
|
|
return $this->belongsToMany(Tier::class);
|
|
}
|
|
|
|
public function users(): BelongsToMany
|
|
{
|
|
return $this->belongsToMany(User::class);
|
|
}
|
|
}
|