feat: shift assignment workflow with claim, approve, reject, cancel, and bulk approve

Implements the complete ShiftAssignment lifecycle:
- ShiftAssignmentStatus enum with allowed transitions
- ShiftAssignmentService with claim/assign/approve/reject/cancel/bulkApprove
- ShiftAssignmentController with event-scoped endpoints
- ShiftAssignmentPolicy (organizer + volunteer self-cancel)
- VolunteerAvailability model, controller, and sync endpoint
- Refactored ShiftController to delegate to service layer
- 31 workflow tests covering all paths and multi-tenancy

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-04-10 17:00:56 +02:00
parent 303280286f
commit 0cdc192239
21 changed files with 1830 additions and 77 deletions

View File

@@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
namespace App\Enums;
enum ShiftAssignmentStatus: string
{
case PENDING_APPROVAL = 'pending_approval';
case APPROVED = 'approved';
case REJECTED = 'rejected';
case CANCELLED = 'cancelled';
case COMPLETED = 'completed';
/** @return list<self> */
public function allowedTransitions(): array
{
return match ($this) {
self::PENDING_APPROVAL => [self::APPROVED, self::REJECTED, self::CANCELLED],
self::APPROVED => [self::CANCELLED, self::COMPLETED],
self::REJECTED, self::CANCELLED, self::COMPLETED => [],
};
}
public function canTransitionTo(self $target): bool
{
return in_array($target, $this->allowedTransitions(), true);
}
public function isTerminal(): bool
{
return $this->allowedTransitions() === [];
}
}

View File

@@ -0,0 +1,101 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers\Api\V1;
use App\Enums\ShiftAssignmentStatus;
use App\Http\Controllers\Controller;
use App\Http\Requests\Api\V1\BulkApproveShiftAssignmentRequest;
use App\Http\Requests\Api\V1\RejectShiftAssignmentRequest;
use App\Http\Resources\Api\V1\ShiftAssignmentResource;
use App\Models\Event;
use App\Models\ShiftAssignment;
use App\Services\ShiftAssignmentService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use Illuminate\Support\Facades\Gate;
final class ShiftAssignmentController extends Controller
{
public function __construct(
private readonly ShiftAssignmentService $service,
) {}
public function index(Request $request, Event $event): AnonymousResourceCollection
{
Gate::authorize('viewAny', [ShiftAssignment::class, $event]);
$query = ShiftAssignment::query()
->whereHas('shift.festivalSection', fn ($q) => $q->where('event_id', $event->id))
->with(['person', 'shift.festivalSection', 'shift.timeSlot']);
if ($request->filled('status')) {
$status = ShiftAssignmentStatus::tryFrom($request->string('status')->toString());
if ($status !== null) {
$query->where('status', $status);
}
}
if ($request->filled('shift_id')) {
$query->where('shift_id', $request->string('shift_id')->toString());
}
if ($request->filled('person_id')) {
$query->where('person_id', $request->string('person_id')->toString());
}
if ($request->filled('section_id')) {
$query->whereHas('shift', fn ($q) => $q->where('festival_section_id', $request->string('section_id')->toString()));
}
$assignments = $query->orderByDesc('created_at')->paginate(50);
return ShiftAssignmentResource::collection($assignments);
}
public function approve(Event $event, ShiftAssignment $shiftAssignment): JsonResponse
{
Gate::authorize('approve', [$shiftAssignment, $event]);
$shiftAssignment = $this->service->approve($shiftAssignment, request()->user());
return $this->success(new ShiftAssignmentResource($shiftAssignment->load(['person', 'shift.festivalSection', 'shift.timeSlot'])));
}
public function reject(RejectShiftAssignmentRequest $request, Event $event, ShiftAssignment $shiftAssignment): JsonResponse
{
Gate::authorize('reject', [$shiftAssignment, $event]);
$shiftAssignment = $this->service->reject(
$shiftAssignment,
$request->user(),
$request->validated('reason'),
);
return $this->success(new ShiftAssignmentResource($shiftAssignment->load(['person', 'shift.festivalSection', 'shift.timeSlot'])));
}
public function cancel(Event $event, ShiftAssignment $shiftAssignment): JsonResponse
{
Gate::authorize('cancel', [$shiftAssignment, $event]);
$shiftAssignment = $this->service->cancel($shiftAssignment, request()->user());
return $this->success(new ShiftAssignmentResource($shiftAssignment->load(['person', 'shift.festivalSection', 'shift.timeSlot'])));
}
public function bulkApprove(BulkApproveShiftAssignmentRequest $request, Event $event): JsonResponse
{
Gate::authorize('bulkApprove', [ShiftAssignment::class, $event]);
$assignments = ShiftAssignment::whereIn('id', $request->validated('assignment_ids'))
->with('shift')
->get();
$results = $this->service->bulkApprove($assignments, $request->user());
return $this->success($results);
}
}

View File

@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace App\Http\Controllers\Api\V1;
use App\Enums\ShiftAssignmentStatus;
use App\Http\Controllers\Controller;
use App\Http\Requests\Api\V1\AssignShiftRequest;
use App\Http\Requests\Api\V1\StoreShiftRequest;
@@ -12,21 +13,26 @@ use App\Http\Resources\Api\V1\ShiftAssignmentResource;
use App\Http\Resources\Api\V1\ShiftResource;
use App\Models\Event;
use App\Models\FestivalSection;
use App\Models\Person;
use App\Models\Shift;
use App\Models\ShiftAssignment;
use App\Services\ShiftAssignmentService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use Illuminate\Support\Facades\Gate;
final class ShiftController extends Controller
{
public function __construct(
private readonly ShiftAssignmentService $shiftAssignmentService,
) {}
public function index(Event $event, FestivalSection $section): AnonymousResourceCollection
{
Gate::authorize('viewAny', [Shift::class, $event]);
$shifts = $section->shifts()
->with(['timeSlot', 'location'])
->withCount(['shiftAssignments as filled_slots' => fn ($q) => $q->where('status', 'approved')])
->withCount(['shiftAssignments as filled_slots' => fn ($q) => $q->where('status', ShiftAssignmentStatus::APPROVED)])
->get();
return ShiftResource::collection($shifts);
@@ -65,41 +71,8 @@ final class ShiftController extends Controller
{
Gate::authorize('assign', [$shift, $event, $section]);
$personId = $request->validated('person_id');
// Check if shift is full
$approvedCount = $shift->shiftAssignments()->where('status', 'approved')->count();
if ($approvedCount >= $shift->slots_total) {
return $this->error('Shift is vol — alle slots zijn bezet.', 422);
}
// Check overlap conflict if allow_overlap is false
if (! $shift->allow_overlap) {
$conflict = ShiftAssignment::where('person_id', $personId)
->where('time_slot_id', $shift->time_slot_id)
->whereNotIn('status', ['rejected', 'cancelled'])
->exists();
if ($conflict) {
return $this->error('Deze persoon is al ingepland voor dit tijdslot.', 422);
}
}
$assignment = $shift->shiftAssignments()->create([
'person_id' => $personId,
'time_slot_id' => $shift->time_slot_id,
'status' => 'approved',
'auto_approved' => false,
'assigned_by' => $request->user()->id,
'assigned_at' => now(),
'approved_at' => now(),
]);
// Update shift status if full
$newApprovedCount = $shift->shiftAssignments()->where('status', 'approved')->count();
if ($newApprovedCount >= $shift->slots_total) {
$shift->update(['status' => 'full']);
}
$person = Person::findOrFail($request->validated('person_id'));
$assignment = $this->shiftAssignmentService->assign($shift, $person, $request->user());
return $this->created(new ShiftAssignmentResource($assignment));
}
@@ -108,39 +81,8 @@ final class ShiftController extends Controller
{
Gate::authorize('claim', [$shift, $event, $section]);
$personId = $request->validated('person_id');
// Check claiming slots available
$claimedCount = $shift->shiftAssignments()
->whereNotIn('status', ['rejected', 'cancelled'])
->count();
if ($shift->slots_open_for_claiming <= 0 || $claimedCount >= $shift->slots_open_for_claiming) {
return $this->error('Geen claimbare slots beschikbaar voor deze shift.', 422);
}
// Check overlap conflict if allow_overlap is false
if (! $shift->allow_overlap) {
$conflict = ShiftAssignment::where('person_id', $personId)
->where('time_slot_id', $shift->time_slot_id)
->whereNotIn('status', ['rejected', 'cancelled'])
->exists();
if ($conflict) {
return $this->error('Deze persoon is al ingepland voor dit tijdslot.', 422);
}
}
$autoApprove = $section->crew_auto_accepts;
$assignment = $shift->shiftAssignments()->create([
'person_id' => $personId,
'time_slot_id' => $shift->time_slot_id,
'status' => $autoApprove ? 'approved' : 'pending_approval',
'auto_approved' => $autoApprove,
'assigned_at' => now(),
'approved_at' => $autoApprove ? now() : null,
]);
$person = Person::findOrFail($request->validated('person_id'));
$assignment = $this->shiftAssignmentService->claim($shift, $person);
return $this->created(new ShiftAssignmentResource($assignment));
}

View File

@@ -0,0 +1,105 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers\Api\V1;
use App\Http\Controllers\Controller;
use App\Http\Requests\Api\V1\SyncVolunteerAvailabilityRequest;
use App\Models\Event;
use App\Models\Person;
use App\Models\TimeSlot;
use App\Models\VolunteerAvailability;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Gate;
use Illuminate\Validation\ValidationException;
final class VolunteerAvailabilityController extends Controller
{
public function index(Event $event, Person $person): JsonResponse
{
Gate::authorize('view', [$person, $event]);
$availabilities = VolunteerAvailability::where('person_id', $person->id)
->with('timeSlot')
->get()
->map(fn (VolunteerAvailability $a) => [
'id' => $a->id,
'time_slot_id' => $a->time_slot_id,
'preference_level' => $a->preference_level,
'submitted_at' => $a->submitted_at?->toIso8601String(),
'time_slot' => $a->timeSlot ? [
'id' => $a->timeSlot->id,
'name' => $a->timeSlot->name,
'date' => $a->timeSlot->date?->toDateString(),
'start_time' => $a->timeSlot->start_time,
'end_time' => $a->timeSlot->end_time,
] : null,
]);
return response()->json(['data' => $availabilities]);
}
/**
* @throws ValidationException
*/
public function sync(SyncVolunteerAvailabilityRequest $request, Event $event, Person $person): JsonResponse
{
Gate::authorize('update', [$person, $event]);
$availabilities = $request->validated('availabilities');
// Validate all time_slot_ids belong to the event (or parent festival)
$validTimeSlotIds = $event->getAllRelevantTimeSlots()->pluck('id')->toArray();
$invalidSlots = collect($availabilities)
->pluck('time_slot_id')
->diff($validTimeSlotIds);
if ($invalidSlots->isNotEmpty()) {
throw ValidationException::withMessages([
'availabilities' => ['Een of meer tijdsloten behoren niet tot dit evenement.'],
]);
}
// Validate time slots have person_type matching the person's crowd_type system_type
$personSystemType = $person->crowdType?->system_type;
if ($personSystemType !== null) {
$requestedSlotIds = collect($availabilities)->pluck('time_slot_id')->toArray();
$mismatchedSlots = TimeSlot::whereIn('id', $requestedSlotIds)
->where('person_type', '!=', $personSystemType)
->exists();
if ($mismatchedSlots) {
throw ValidationException::withMessages([
'availabilities' => ['Een of meer tijdsloten komen niet overeen met het type van deze persoon.'],
]);
}
}
// Delete existing availabilities for this person
VolunteerAvailability::where('person_id', $person->id)->delete();
// Create new availabilities
$now = now();
foreach ($availabilities as $item) {
VolunteerAvailability::create([
'person_id' => $person->id,
'time_slot_id' => $item['time_slot_id'],
'preference_level' => $item['preference_level'] ?? 3,
'submitted_at' => $now,
]);
}
activity('volunteer_availability')
->causedBy($request->user())
->performedOn($person)
->withProperties([
'count' => count($availabilities),
'time_slot_ids' => collect($availabilities)->pluck('time_slot_id')->toArray(),
])
->log('volunteer_availability.synced');
return $this->success(null, 'Beschikbaarheid opgeslagen.');
}
}

View File

@@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
namespace App\Http\Requests\Api\V1;
use Illuminate\Foundation\Http\FormRequest;
final class BulkApproveShiftAssignmentRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
/** @return array<string, mixed> */
public function rules(): array
{
return [
'assignment_ids' => ['required', 'array', 'min:1', 'max:100'],
'assignment_ids.*' => ['required', 'ulid', 'exists:shift_assignments,id'],
];
}
}

View File

@@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace App\Http\Requests\Api\V1;
use Illuminate\Foundation\Http\FormRequest;
final class RejectShiftAssignmentRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
/** @return array<string, mixed> */
public function rules(): array
{
return [
'reason' => ['nullable', 'string', 'max:1000'],
];
}
}

View File

@@ -0,0 +1,25 @@
<?php
declare(strict_types=1);
namespace App\Http\Requests\Api\V1;
use Illuminate\Foundation\Http\FormRequest;
final class SyncVolunteerAvailabilityRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
/** @return array<string, mixed> */
public function rules(): array
{
return [
'availabilities' => ['required', 'array'],
'availabilities.*.time_slot_id' => ['required', 'ulid', 'exists:time_slots,id'],
'availabilities.*.preference_level' => ['sometimes', 'integer', 'min:1', 'max:5'],
];
}
}

View File

@@ -15,10 +15,24 @@ final class ShiftAssignmentResource extends JsonResource
'id' => $this->id,
'shift_id' => $this->shift_id,
'person_id' => $this->person_id,
'status' => $this->status,
'time_slot_id' => $this->time_slot_id,
'status' => $this->status->value,
'auto_approved' => $this->auto_approved,
'assigned_by' => $this->assigned_by,
'assigned_at' => $this->assigned_at?->toIso8601String(),
'approved_by' => $this->approved_by,
'approved_at' => $this->approved_at?->toIso8601String(),
'rejection_reason' => $this->rejection_reason,
'hours_expected' => $this->hours_expected,
'hours_completed' => $this->hours_completed,
'checked_in_at' => $this->checked_in_at?->toIso8601String(),
'checked_out_at' => $this->checked_out_at?->toIso8601String(),
'is_cancellable' => $this->isCancellable(),
'is_approvable' => $this->isApprovable(),
'created_at' => $this->created_at?->toIso8601String(),
'person' => new PersonResource($this->whenLoaded('person')),
'shift' => new ShiftResource($this->whenLoaded('shift')),
];
}
}

View File

@@ -76,6 +76,11 @@ final class Person extends Model
return $this->hasMany(ShiftAssignment::class);
}
public function volunteerAvailabilities(): HasMany
{
return $this->hasMany(VolunteerAvailability::class);
}
public function identityMatches(): HasMany
{
return $this->hasMany(PersonIdentityMatch::class);

View File

@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace App\Models;
use App\Enums\ShiftAssignmentStatus;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Concerns\HasUlids;
@@ -99,7 +100,7 @@ final class Shift extends Model
return (int) $this->attributes['filled_slots'];
}
return $this->shiftAssignments()->where('status', 'approved')->count();
return $this->shiftAssignments()->where('status', ShiftAssignmentStatus::APPROVED)->count();
});
}

View File

@@ -4,6 +4,8 @@ declare(strict_types=1);
namespace App\Models;
use App\Enums\ShiftAssignmentStatus;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Concerns\HasUlids;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
@@ -36,11 +38,14 @@ final class ShiftAssignment extends Model
protected function casts(): array
{
return [
'status' => ShiftAssignmentStatus::class,
'auto_approved' => 'boolean',
'assigned_at' => 'datetime',
'approved_at' => 'datetime',
'checked_in_at' => 'datetime',
'checked_out_at' => 'datetime',
'hours_expected' => 'decimal:2',
'hours_completed' => 'decimal:2',
];
}
@@ -58,4 +63,37 @@ final class ShiftAssignment extends Model
{
return $this->belongsTo(TimeSlot::class);
}
public function assignedByUser(): BelongsTo
{
return $this->belongsTo(User::class, 'assigned_by');
}
public function approvedByUser(): BelongsTo
{
return $this->belongsTo(User::class, 'approved_by');
}
public function scopeActive(Builder $query): Builder
{
return $query->whereIn('status', [
ShiftAssignmentStatus::PENDING_APPROVAL,
ShiftAssignmentStatus::APPROVED,
]);
}
public function scopeForStatus(Builder $query, ShiftAssignmentStatus $status): Builder
{
return $query->where('status', $status);
}
public function isCancellable(): bool
{
return $this->status->canTransitionTo(ShiftAssignmentStatus::CANCELLED);
}
public function isApprovable(): bool
{
return $this->status->canTransitionTo(ShiftAssignmentStatus::APPROVED);
}
}

View File

@@ -0,0 +1,45 @@
<?php
declare(strict_types=1);
namespace App\Models;
use Illuminate\Database\Eloquent\Concerns\HasUlids;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
final class VolunteerAvailability extends Model
{
use HasFactory;
use HasUlids;
public $timestamps = false;
protected $table = 'volunteer_availabilities';
protected $fillable = [
'person_id',
'time_slot_id',
'preference_level',
'submitted_at',
];
protected function casts(): array
{
return [
'preference_level' => 'integer',
'submitted_at' => 'datetime',
];
}
public function person(): BelongsTo
{
return $this->belongsTo(Person::class);
}
public function timeSlot(): BelongsTo
{
return $this->belongsTo(TimeSlot::class);
}
}

View File

@@ -0,0 +1,66 @@
<?php
declare(strict_types=1);
namespace App\Policies;
use App\Models\Event;
use App\Models\ShiftAssignment;
use App\Models\User;
final class ShiftAssignmentPolicy
{
public function viewAny(User $user, Event $event): bool
{
return $user->hasRole('super_admin')
|| $event->organisation->users()->where('user_id', $user->id)->exists();
}
public function approve(User $user, ShiftAssignment $assignment, Event $event): bool
{
return $this->canManageEvent($user, $event);
}
public function reject(User $user, ShiftAssignment $assignment, Event $event): bool
{
return $this->canManageEvent($user, $event);
}
public function cancel(User $user, ShiftAssignment $assignment, Event $event): bool
{
if ($this->canManageEvent($user, $event)) {
return true;
}
// Volunteers can cancel their own assignments
$person = $assignment->person;
return $person->user_id !== null && $person->user_id === $user->id;
}
public function bulkApprove(User $user, Event $event): bool
{
return $this->canManageEvent($user, $event);
}
private function canManageEvent(User $user, Event $event): bool
{
if ($user->hasRole('super_admin')) {
return true;
}
$isOrgAdmin = $event->organisation->users()
->where('user_id', $user->id)
->wherePivot('role', 'org_admin')
->exists();
if ($isOrgAdmin) {
return true;
}
return $event->users()
->where('user_id', $user->id)
->wherePivot('role', 'event_manager')
->exists();
}
}

View File

@@ -0,0 +1,377 @@
<?php
declare(strict_types=1);
namespace App\Services;
use App\Enums\ShiftAssignmentStatus;
use App\Models\Person;
use App\Models\Shift;
use App\Models\ShiftAssignment;
use App\Models\User;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
final class ShiftAssignmentService
{
/**
* @throws ValidationException
*/
public function claim(Shift $shift, Person $person): ShiftAssignment
{
return DB::transaction(function () use ($shift, $person): ShiftAssignment {
$this->validateShiftIsOpen($shift);
$this->validatePersonApproved($person);
$this->validateClaimCapacity($shift);
$this->validateNoConflict($shift, $person);
$autoApprove = $shift->festivalSection->crew_auto_accepts;
$status = $autoApprove
? ShiftAssignmentStatus::APPROVED
: ShiftAssignmentStatus::PENDING_APPROVAL;
$assignment = $shift->shiftAssignments()->create([
'person_id' => $person->id,
'time_slot_id' => $shift->time_slot_id,
'status' => $status,
'auto_approved' => $autoApprove,
'assigned_at' => now(),
'approved_at' => $autoApprove ? now() : null,
]);
$this->updateShiftStatusIfFull($shift);
activity('shift_assignment')
->causedBy(auth()->user())
->performedOn($assignment)
->withProperties([
'shift_id' => $shift->id,
'person_id' => $person->id,
'auto_approved' => $autoApprove,
])
->log('shift_assignment.claimed');
if ($autoApprove) {
activity('shift_assignment')
->causedBy(auth()->user())
->performedOn($assignment)
->withProperties(['shift_id' => $shift->id])
->log('shift_assignment.auto_approved');
}
return $assignment;
});
}
/**
* @throws ValidationException
*/
public function assign(Shift $shift, Person $person, User $assignedBy): ShiftAssignment
{
return DB::transaction(function () use ($shift, $person, $assignedBy): ShiftAssignment {
$this->validateShiftIsOpen($shift);
$this->validateAssignCapacity($shift);
$this->validateNoConflict($shift, $person);
$assignment = $shift->shiftAssignments()->create([
'person_id' => $person->id,
'time_slot_id' => $shift->time_slot_id,
'status' => ShiftAssignmentStatus::APPROVED,
'auto_approved' => false,
'assigned_by' => $assignedBy->id,
'assigned_at' => now(),
'approved_by' => $assignedBy->id,
'approved_at' => now(),
]);
$this->updateShiftStatusIfFull($shift);
activity('shift_assignment')
->causedBy($assignedBy)
->performedOn($assignment)
->withProperties([
'shift_id' => $shift->id,
'person_id' => $person->id,
'assigned_by' => $assignedBy->id,
])
->log('shift_assignment.assigned');
return $assignment;
});
}
/**
* @throws ValidationException
*/
public function approve(ShiftAssignment $assignment, User $approvedBy): ShiftAssignment
{
return DB::transaction(function () use ($assignment, $approvedBy): ShiftAssignment {
$this->validateStatusTransition($assignment, ShiftAssignmentStatus::APPROVED);
$shift = $assignment->shift;
$approvedCount = $shift->shiftAssignments()
->where('status', ShiftAssignmentStatus::APPROVED)
->count();
if ($approvedCount >= $shift->slots_total) {
throw ValidationException::withMessages([
'shift' => ['Shift is vol — alle slots zijn bezet.'],
]);
}
$oldStatus = $assignment->status;
$assignment->update([
'status' => ShiftAssignmentStatus::APPROVED,
'approved_by' => $approvedBy->id,
'approved_at' => now(),
]);
$this->updateShiftStatusIfFull($shift);
activity('shift_assignment')
->causedBy($approvedBy)
->performedOn($assignment)
->withProperties([
'old_status' => $oldStatus->value,
'new_status' => ShiftAssignmentStatus::APPROVED->value,
])
->log('shift_assignment.approved');
return $assignment->fresh();
});
}
/**
* @throws ValidationException
*/
public function reject(ShiftAssignment $assignment, User $rejectedBy, ?string $reason = null): ShiftAssignment
{
$this->validateStatusTransition($assignment, ShiftAssignmentStatus::REJECTED);
$oldStatus = $assignment->status;
$assignment->update([
'status' => ShiftAssignmentStatus::REJECTED,
'rejection_reason' => $reason,
]);
activity('shift_assignment')
->causedBy($rejectedBy)
->performedOn($assignment)
->withProperties([
'old_status' => $oldStatus->value,
'new_status' => ShiftAssignmentStatus::REJECTED->value,
'reason' => $reason,
])
->log('shift_assignment.rejected');
return $assignment->fresh();
}
/**
* @throws ValidationException
*/
public function cancel(ShiftAssignment $assignment, User $cancelledBy): ShiftAssignment
{
return DB::transaction(function () use ($assignment, $cancelledBy): ShiftAssignment {
$this->validateStatusTransition($assignment, ShiftAssignmentStatus::CANCELLED);
$wasApproved = $assignment->status === ShiftAssignmentStatus::APPROVED;
$oldStatus = $assignment->status;
$assignment->update([
'status' => ShiftAssignmentStatus::CANCELLED,
]);
if ($wasApproved) {
$this->updateShiftStatusAfterCancellation($assignment->shift);
}
activity('shift_assignment')
->causedBy($cancelledBy)
->performedOn($assignment)
->withProperties([
'old_status' => $oldStatus->value,
'new_status' => ShiftAssignmentStatus::CANCELLED->value,
])
->log('shift_assignment.cancelled');
return $assignment->fresh();
});
}
/**
* @return Collection<int, array{assignment_id: string, status: string}>
*/
public function bulkApprove(Collection $assignments, User $approvedBy): Collection
{
return DB::transaction(function () use ($assignments, $approvedBy): Collection {
return $assignments->map(function (ShiftAssignment $assignment) use ($approvedBy): array {
if ($assignment->status !== ShiftAssignmentStatus::PENDING_APPROVAL) {
return [
'assignment_id' => $assignment->id,
'status' => 'skipped',
'reason' => "Status is {$assignment->status->value}, not pending_approval.",
];
}
$shift = $assignment->shift;
$approvedCount = $shift->shiftAssignments()
->where('status', ShiftAssignmentStatus::APPROVED)
->count();
if ($approvedCount >= $shift->slots_total) {
return [
'assignment_id' => $assignment->id,
'status' => 'skipped',
'reason' => 'Shift is vol.',
];
}
$assignment->update([
'status' => ShiftAssignmentStatus::APPROVED,
'approved_by' => $approvedBy->id,
'approved_at' => now(),
]);
$this->updateShiftStatusIfFull($shift);
activity('shift_assignment')
->causedBy($approvedBy)
->performedOn($assignment)
->withProperties([
'old_status' => ShiftAssignmentStatus::PENDING_APPROVAL->value,
'new_status' => ShiftAssignmentStatus::APPROVED->value,
])
->log('shift_assignment.approved');
return [
'assignment_id' => $assignment->id,
'status' => 'approved',
];
});
});
}
/**
* @throws ValidationException
*/
private function validateShiftIsOpen(Shift $shift): void
{
if ($shift->status !== 'open') {
throw ValidationException::withMessages([
'shift' => ['Shift is niet open voor inschrijvingen.'],
]);
}
}
/**
* @throws ValidationException
*/
private function validatePersonApproved(Person $person): void
{
if ($person->status !== 'approved') {
throw ValidationException::withMessages([
'person' => ['Persoon is nog niet goedgekeurd.'],
]);
}
}
/**
* @throws ValidationException
*/
private function validateClaimCapacity(Shift $shift): void
{
if ($shift->slots_open_for_claiming <= 0) {
throw ValidationException::withMessages([
'shift' => ['Geen claimbare slots beschikbaar voor deze shift.'],
]);
}
$activeCount = $shift->shiftAssignments()
->whereNotIn('status', [
ShiftAssignmentStatus::REJECTED,
ShiftAssignmentStatus::CANCELLED,
])
->count();
if ($activeCount >= $shift->slots_open_for_claiming) {
throw ValidationException::withMessages([
'shift' => ['Geen claimbare slots beschikbaar voor deze shift.'],
]);
}
}
/**
* @throws ValidationException
*/
private function validateAssignCapacity(Shift $shift): void
{
$approvedCount = $shift->shiftAssignments()
->where('status', ShiftAssignmentStatus::APPROVED)
->count();
if ($approvedCount >= $shift->slots_total) {
throw ValidationException::withMessages([
'shift' => ['Shift is vol — alle slots zijn bezet.'],
]);
}
}
/**
* @throws ValidationException
*/
private function validateNoConflict(Shift $shift, Person $person): void
{
if ($shift->allow_overlap) {
return;
}
$conflict = ShiftAssignment::where('person_id', $person->id)
->where('time_slot_id', $shift->time_slot_id)
->active()
->exists();
if ($conflict) {
throw ValidationException::withMessages([
'person_id' => ['Deze persoon is al ingepland voor dit tijdslot.'],
]);
}
}
/**
* @throws ValidationException
*/
private function validateStatusTransition(ShiftAssignment $assignment, ShiftAssignmentStatus $target): void
{
if (! $assignment->status->canTransitionTo($target)) {
throw ValidationException::withMessages([
'status' => ["Statusovergang van '{$assignment->status->value}' naar '{$target->value}' is niet toegestaan."],
]);
}
}
private function updateShiftStatusIfFull(Shift $shift): void
{
$approvedCount = $shift->shiftAssignments()
->where('status', ShiftAssignmentStatus::APPROVED)
->count();
if ($approvedCount >= $shift->slots_total && $shift->status === 'open') {
$shift->update(['status' => 'full']);
}
}
private function updateShiftStatusAfterCancellation(Shift $shift): void
{
$approvedCount = $shift->shiftAssignments()
->where('status', ShiftAssignmentStatus::APPROVED)
->count();
if ($approvedCount < $shift->slots_total && $shift->status === 'full') {
$shift->update(['status' => 'open']);
}
}
}