Files
crewli/api/app/Models/Shift.php

132 lines
3.3 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Models;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Concerns\HasUlids;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
final class Shift extends Model
{
use HasFactory;
use HasUlids;
use SoftDeletes;
protected $fillable = [
'festival_section_id',
'time_slot_id',
'location_id',
'title',
'description',
'instructions',
'coordinator_notes',
'slots_total',
'slots_open_for_claiming',
'is_lead_role',
'report_time',
'actual_start_time',
'actual_end_time',
'end_date',
'allow_overlap',
'assigned_crew_id',
'events_during_shift',
'status',
];
protected function casts(): array
{
return [
'is_lead_role' => 'boolean',
'allow_overlap' => 'boolean',
'end_date' => 'date',
'events_during_shift' => 'array',
'slots_total' => 'integer',
'slots_open_for_claiming' => 'integer',
];
}
public function festivalSection(): BelongsTo
{
return $this->belongsTo(FestivalSection::class);
}
public function timeSlot(): BelongsTo
{
return $this->belongsTo(TimeSlot::class);
}
public function location(): BelongsTo
{
return $this->belongsTo(Location::class);
}
public function assignedCrew(): BelongsTo
{
return $this->belongsTo(User::class, 'assigned_crew_id');
}
public function shiftAssignments(): HasMany
{
return $this->hasMany(ShiftAssignment::class);
}
public function waitlist(): HasMany
{
return $this->hasMany(ShiftWaitlist::class);
}
protected function effectiveStartTime(): Attribute
{
return Attribute::get(fn () => $this->actual_start_time ?? $this->timeSlot?->start_time);
}
protected function effectiveEndTime(): Attribute
{
return Attribute::get(fn () => $this->actual_end_time ?? $this->timeSlot?->end_time);
}
protected function filledSlots(): Attribute
{
return Attribute::get(function () {
if (array_key_exists('filled_slots', $this->attributes)) {
return (int) $this->attributes['filled_slots'];
}
return $this->shiftAssignments()->where('status', 'approved')->count();
});
}
protected function fillRate(): Attribute
{
return Attribute::get(function () {
if ($this->slots_total === 0) {
return 0;
}
return round($this->filled_slots / $this->slots_total, 2);
});
}
public function scopeOpen(Builder $query): Builder
{
return $query->where('status', 'open');
}
public function scopeDraft(Builder $query): Builder
{
return $query->where('status', 'draft');
}
public function scopeFull(Builder $query): Builder
{
return $query->where('status', 'full');
}
}