feat(api): enrich TimeSlotResource with shift statistics
Add shifts_count, total_slots, filled_slots, and sections_count computed fields to TimeSlotResource. Update TimeSlotController to eager-load shifts with assignment counts for aggregate calculations. Includes test verifying only approved assignments count towards filled_slots. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -20,11 +20,24 @@ final class TimeSlotController extends Controller
|
||||
{
|
||||
Gate::authorize('viewAny', [TimeSlot::class, $event]);
|
||||
|
||||
$timeSlots = $event->timeSlots()->orderBy('date')->orderBy('start_time')->get();
|
||||
$timeSlots = $event->timeSlots()
|
||||
->withCount('shifts')
|
||||
->with(['shifts' => fn ($q) => $q->withCount([
|
||||
'shiftAssignments as assignments_count' => fn ($q) => $q->where('status', 'approved'),
|
||||
])])
|
||||
->orderBy('date')
|
||||
->orderBy('start_time')
|
||||
->get();
|
||||
|
||||
if ($event->isSubEvent() && request()->boolean('include_parent') && $event->parent_event_id) {
|
||||
$parentTimeSlots = TimeSlot::where('event_id', $event->parent_event_id)
|
||||
->with('event')
|
||||
->withCount('shifts')
|
||||
->with([
|
||||
'event',
|
||||
'shifts' => fn ($q) => $q->withCount([
|
||||
'shiftAssignments as assignments_count' => fn ($q) => $q->where('status', 'approved'),
|
||||
]),
|
||||
])
|
||||
->orderBy('date')
|
||||
->orderBy('start_time')
|
||||
->get();
|
||||
|
||||
@@ -23,6 +23,21 @@ final class TimeSlotResource extends JsonResource
|
||||
'duration_hours' => $this->duration_hours,
|
||||
'source' => $this->resource->getAttribute('source'),
|
||||
'event_name' => $this->whenLoaded('event', fn () => $this->event->name),
|
||||
'shifts_count' => $this->whenCounted('shifts'),
|
||||
// Aggregates computed from eager-loaded shifts with assignment counts.
|
||||
// For events with >200 shifts, consider replacing with a raw aggregate query.
|
||||
'total_slots' => $this->when(
|
||||
$this->relationLoaded('shifts'),
|
||||
fn () => (int) $this->shifts->sum('slots_total'),
|
||||
),
|
||||
'filled_slots' => $this->when(
|
||||
$this->relationLoaded('shifts'),
|
||||
fn () => (int) $this->shifts->sum(fn ($shift) => $shift->assignments_count ?? 0),
|
||||
),
|
||||
'sections_count' => $this->when(
|
||||
$this->relationLoaded('shifts'),
|
||||
fn () => $this->shifts->pluck('festival_section_id')->unique()->count(),
|
||||
),
|
||||
'created_at' => $this->created_at->toIso8601String(),
|
||||
];
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user