diff --git a/app-modules/events/database/factories/CheckInFactory.php b/app-modules/events/database/factories/CheckInFactory.php index fa621af9f..2392e1fec 100644 --- a/app-modules/events/database/factories/CheckInFactory.php +++ b/app-modules/events/database/factories/CheckInFactory.php @@ -22,6 +22,7 @@ public function definition(): array 'event_date' => Date::today(), 'method' => fake()->randomElement(CheckInMethod::cases()), 'payload' => null, + 'checked_in_at' => Date::now(), ]; } } diff --git a/app-modules/events/database/migrations/2026_05_22_000001_add_checked_in_at_to_events_check_ins_table.php b/app-modules/events/database/migrations/2026_05_22_000001_add_checked_in_at_to_events_check_ins_table.php new file mode 100644 index 000000000..8b7967eb8 --- /dev/null +++ b/app-modules/events/database/migrations/2026_05_22_000001_add_checked_in_at_to_events_check_ins_table.php @@ -0,0 +1,24 @@ +timestampTz('checked_in_at')->nullable()->after('payload'); + }); + } + + public function down(): void + { + Schema::table('events_check_ins', function (Blueprint $table): void { + $table->dropColumn('checked_in_at'); + }); + } +}; diff --git a/app-modules/events/lang/en/check_in.php b/app-modules/events/lang/en/check_in.php new file mode 100644 index 000000000..c163fc1fe --- /dev/null +++ b/app-modules/events/lang/en/check_in.php @@ -0,0 +1,10 @@ + 'Only confirmed or checked-in enrollments can be checked in.', + 'check_in_outside_event_date_range' => 'Check-in date must be within the event date range.', + 'already_checked_in_for_date' => 'This enrollment has already checked in for this date.', + 'invalid_check_in_actor' => 'Manual check-in requires the organizer user id.', +]; diff --git a/app-modules/events/lang/en/exceptions.php b/app-modules/events/lang/en/exceptions.php index 056dd6539..58511678b 100644 --- a/app-modules/events/lang/en/exceptions.php +++ b/app-modules/events/lang/en/exceptions.php @@ -3,9 +3,11 @@ declare(strict_types=1); return [ + 'invalid_transition' => 'Cannot transition enrollment from :from to :to.', 'already_enrolled' => 'You are already enrolled in this event.', 'event_past' => 'This event has already started and is no longer accepting enrollments.', 'event_not_active' => 'This event is not available for enrollment.', 'invalid_enrollment_method' => 'This event requires application enrollment, not RSVP.', 'event_full' => 'This event has reached maximum capacity and does not have a waitlist.', + 'response_message_not_implemented' => 'Response message is not implemented for enrollment status: :status.', ]; diff --git a/app-modules/events/lang/pt_BR/check_in.php b/app-modules/events/lang/pt_BR/check_in.php new file mode 100644 index 000000000..46a65b78e --- /dev/null +++ b/app-modules/events/lang/pt_BR/check_in.php @@ -0,0 +1,10 @@ + 'Apenas inscrições confirmadas ou com check-in realizado podem receber check-in.', + 'check_in_outside_event_date_range' => 'A data do check-in deve estar dentro do período do evento.', + 'already_checked_in_for_date' => 'Esta inscrição já possui check-in para essa data.', + 'invalid_check_in_actor' => 'Check-in manual exige o ID do usuário organizador.', +]; diff --git a/app-modules/events/lang/pt_BR/exceptions.php b/app-modules/events/lang/pt_BR/exceptions.php index 27d80f367..fdd707908 100644 --- a/app-modules/events/lang/pt_BR/exceptions.php +++ b/app-modules/events/lang/pt_BR/exceptions.php @@ -3,9 +3,11 @@ declare(strict_types=1); return [ + 'invalid_transition' => 'Não é possível transicionar inscrição de :from para :to.', 'already_enrolled' => 'Você já está inscrito neste evento.', 'event_past' => 'Este evento já começou e não aceita mais inscrições.', 'event_not_active' => 'Este evento não está disponível para inscrição.', 'invalid_enrollment_method' => 'Esse evento exige inscrição via formulário, não RSVP.', 'event_full' => 'Este evento atingiu a capacidade máxima e não possui lista de espera.', + 'response_message_not_implemented' => 'Mensagem de resposta não implementada para o status de inscrição: :status.', ]; diff --git a/app-modules/events/src/CheckIn/Actions/CheckInAction.php b/app-modules/events/src/CheckIn/Actions/CheckInAction.php new file mode 100644 index 000000000..5739fb856 --- /dev/null +++ b/app-modules/events/src/CheckIn/Actions/CheckInAction.php @@ -0,0 +1,105 @@ +loadLockedEnrollment($dto->enrollment); + $event = $enrollment->event; + $normalizedEventDate = Date::parse($dto->eventDate->toDateString())->startOfDay(); + + $this->validateCommonRules($enrollment, $normalizedEventDate); + $isFirstCheckIn = !CheckIn::query() + ->where('enrollment_id', $enrollment->id) + ->exists(); + + try { + $checkIn = CheckIn::query()->create([ + 'enrollment_id' => $enrollment->id, + 'method' => $dto->method, + 'payload' => $dto->payload, + 'event_date' => $normalizedEventDate, + 'checked_in_at' => now(), + ]); + } catch (UniqueConstraintViolationException) { + throw CheckInException::alreadyCheckedInForDate(); + } + + if ($isFirstCheckIn && $enrollment->status === EnrollmentStatus::Confirmed) { + resolve(TransitionEnrollmentAction::class)->handle( + new TransitionEnrollmentDTO( + enrollment: $enrollment, + toStatus: EnrollmentStatus::CheckedIn, + triggeredBy: $dto->triggeredBy, + actorId: $dto->actorUserId, + timestamp: $checkIn->checked_in_at, + ), + ); + } + + $xpRewardOnCheckedIn = (int) ($event->enrollmentPolicy->xp_on_checked_in ?? 0); + + event(new ParticipantCheckedIn( + checkInId: $checkIn->id, + enrollmentId: $enrollment->id, + eventId: $enrollment->event_id, + userId: $enrollment->user_id, + eventDate: $normalizedEventDate->toDateString(), + xpRewardOnCheckedIn: $xpRewardOnCheckedIn, + )); + + return $checkIn->load('enrollment'); + }); + } + + private function loadLockedEnrollment(Enrollment $enrollment): Enrollment + { + return Enrollment::query() + ->with(['event.enrollmentPolicy']) + ->whereKey($enrollment->id) + ->lockForUpdate() + ->firstOrFail(); + } + + private function validateCommonRules(Enrollment $enrollment, CarbonInterface $eventDate): void + { + throw_unless( + in_array($enrollment->status, [EnrollmentStatus::Confirmed, EnrollmentStatus::CheckedIn], strict: true), + CheckInException::invalidCheckInStatus(), + ); + + $event = $enrollment->event; + $eventDateString = $eventDate->toDateString(); + + throw_unless( + $eventDateString >= $event->starts_at->toDateString() && $eventDateString <= $event->ends_at->toDateString(), + CheckInException::checkInOutsideEventDateRange(), + ); + + throw_if( + CheckIn::query() + ->where('enrollment_id', $enrollment->id) + ->whereDate('event_date', $eventDate->toDateString()) + ->exists(), + CheckInException::alreadyCheckedInForDate(), + ); + } +} diff --git a/app-modules/events/src/CheckIn/Actions/ManualCheckInAction.php b/app-modules/events/src/CheckIn/Actions/ManualCheckInAction.php new file mode 100644 index 000000000..8f82399e1 --- /dev/null +++ b/app-modules/events/src/CheckIn/Actions/ManualCheckInAction.php @@ -0,0 +1,28 @@ +handle( + new CheckInDTO( + enrollment: $dto->enrollment, + method: CheckInMethod::Manual, + payload: ['actor_user_id' => $dto->actorUserId], + eventDate: $dto->eventDate, + actorUserId: $dto->actorUserId, + triggeredBy: TriggeredBy::Admin, + ), + ); + } +} diff --git a/app-modules/events/src/CheckIn/DTOs/CheckInDTO.php b/app-modules/events/src/CheckIn/DTOs/CheckInDTO.php new file mode 100644 index 000000000..becb5dcd6 --- /dev/null +++ b/app-modules/events/src/CheckIn/DTOs/CheckInDTO.php @@ -0,0 +1,25 @@ + $payload + */ + public function __construct( + public Enrollment $enrollment, + public CheckInMethod $method, + public array $payload, + public CarbonInterface $eventDate, + public string $actorUserId, + public TriggeredBy $triggeredBy, + ) {} +} diff --git a/app-modules/events/src/CheckIn/DTOs/ManualCheckInDTO.php b/app-modules/events/src/CheckIn/DTOs/ManualCheckInDTO.php new file mode 100644 index 000000000..261a00d3f --- /dev/null +++ b/app-modules/events/src/CheckIn/DTOs/ManualCheckInDTO.php @@ -0,0 +1,20 @@ +actorUserId), CheckInException::invalidCheckInActor()); + } +} diff --git a/app-modules/events/src/CheckIn/Events/ParticipantCheckedIn.php b/app-modules/events/src/CheckIn/Events/ParticipantCheckedIn.php new file mode 100644 index 000000000..8ddddc728 --- /dev/null +++ b/app-modules/events/src/CheckIn/Events/ParticipantCheckedIn.php @@ -0,0 +1,22 @@ +|null $payload + * @property Carbon $checked_in_at * @property Carbon $created_at * @property Carbon $updated_at */ @@ -35,6 +36,7 @@ final class CheckIn extends Model 'event_date', 'method', 'payload', + 'checked_in_at', ]; /** @return BelongsTo */ @@ -55,6 +57,7 @@ protected function casts(): array 'event_date' => 'date', 'method' => CheckInMethod::class, 'payload' => 'array', + 'checked_in_at' => 'datetime', ]; } } diff --git a/app-modules/events/src/Enrollment/Actions/EnrollUserAction.php b/app-modules/events/src/Enrollment/Actions/EnrollUserAction.php index a43493e6a..bff9b7318 100644 --- a/app-modules/events/src/Enrollment/Actions/EnrollUserAction.php +++ b/app-modules/events/src/Enrollment/Actions/EnrollUserAction.php @@ -53,7 +53,7 @@ public function handle(EnrollUserDTO $dto): Enrollment enrollmentId: $enrollment->id, eventId: $dto->eventId, userId: $dto->userId, - xpRewardOnConfirmed: $policy?->xp_on_confirmed ?? 0, + xpRewardOnConfirmed: $policy->xp_on_confirmed ?? 0, )); } diff --git a/app-modules/events/src/Enrollment/Actions/TransitionEnrollmentAction.php b/app-modules/events/src/Enrollment/Actions/TransitionEnrollmentAction.php new file mode 100644 index 000000000..a68420708 --- /dev/null +++ b/app-modules/events/src/Enrollment/Actions/TransitionEnrollmentAction.php @@ -0,0 +1,43 @@ +enrollment->status; + $toStatus = $dto->toStatus; + + throw_unless( + $fromStatus->canTransitionTo($toStatus), + EnrollmentException::invalidTransition($fromStatus, $toStatus), + ); + + $attributes = [ + 'status' => $toStatus, + ]; + + if ($timestampColumn = $toStatus->timestampColumn()) { + $attributes[$timestampColumn] = $dto->timestamp ?? now(); + } + + $dto->enrollment->update($attributes); + + return EnrollmentTransition::query()->create([ + 'enrollment_id' => $dto->enrollment->id, + 'from_status' => $fromStatus, + 'to_status' => $toStatus, + 'actor_id' => $dto->actorId, + 'triggered_by' => $dto->triggeredBy, + 'reason' => $dto->reason, + 'metadata' => $dto->metadata ?: null, + ]); + } +} diff --git a/app-modules/events/src/Enrollment/DTOs/TransitionEnrollmentDTO.php b/app-modules/events/src/Enrollment/DTOs/TransitionEnrollmentDTO.php new file mode 100644 index 000000000..c84a27bf7 --- /dev/null +++ b/app-modules/events/src/Enrollment/DTOs/TransitionEnrollmentDTO.php @@ -0,0 +1,26 @@ + $metadata + */ + public function __construct( + public Enrollment $enrollment, + public EnrollmentStatus $toStatus, + public TriggeredBy $triggeredBy, + public ?string $actorId = null, + public ?string $reason = null, + public array $metadata = [], + public ?CarbonInterface $timestamp = null, + ) {} +} diff --git a/app-modules/events/src/Enrollment/Enums/EnrollmentStatus.php b/app-modules/events/src/Enrollment/Enums/EnrollmentStatus.php index 70d1e9930..500b9bb88 100644 --- a/app-modules/events/src/Enrollment/Enums/EnrollmentStatus.php +++ b/app-modules/events/src/Enrollment/Enums/EnrollmentStatus.php @@ -9,6 +9,7 @@ use Filament\Support\Contracts\HasIcon; use Filament\Support\Contracts\HasLabel; use Filament\Support\Icons\Heroicon; +use He4rt\Events\Enrollment\Exceptions\EnrollmentException; enum EnrollmentStatus: string implements HasColor, HasIcon, HasLabel { @@ -65,6 +66,14 @@ public function canTransitionTo(self $target): bool }; } + public function timestampColumn(): ?string + { + return match ($this) { + self::Confirmed, self::CheckedIn, self::Attended, self::Cancelled => $this->value.'_at', + default => null, + }; + } + public function isTerminal(): bool { return in_array($this, [self::Attended, self::Cancelled, self::Rejected, self::NoShow], strict: true); @@ -90,6 +99,7 @@ public function getResponseMessage(): string return match ($this) { self::Confirmed => __('events::pages.confirm_presence_success'), self::Waitlisted => __('events::pages.waitlist_success'), + default => throw EnrollmentException::responseMessageNotImplemented($this), }; } } diff --git a/app-modules/events/src/Enrollment/Exceptions/EnrollmentException.php b/app-modules/events/src/Enrollment/Exceptions/EnrollmentException.php index 8ffc2cff5..e72ce0a8c 100644 --- a/app-modules/events/src/Enrollment/Exceptions/EnrollmentException.php +++ b/app-modules/events/src/Enrollment/Exceptions/EnrollmentException.php @@ -5,10 +5,19 @@ namespace He4rt\Events\Enrollment\Exceptions; use Exception; +use He4rt\Events\Enrollment\Enums\EnrollmentStatus; use Symfony\Component\HttpFoundation\Response; final class EnrollmentException extends Exception { + public static function invalidTransition(EnrollmentStatus $from, EnrollmentStatus $to): self + { + return new self( + __('events::exceptions.invalid_transition', ['from' => $from->value, 'to' => $to->value]), + Response::HTTP_UNPROCESSABLE_ENTITY, + ); + } + public static function alreadyEnrolled(): self { return new self( @@ -48,4 +57,12 @@ public static function eventFull(): self Response::HTTP_UNPROCESSABLE_ENTITY, ); } + + public static function responseMessageNotImplemented(EnrollmentStatus $status): self + { + return new self( + __('events::exceptions.response_message_not_implemented', ['status' => $status->value]), + Response::HTTP_INTERNAL_SERVER_ERROR, + ); + } } diff --git a/app-modules/events/src/Enrollment/Models/Enrollment.php b/app-modules/events/src/Enrollment/Models/Enrollment.php index 3d163885e..093d44f42 100644 --- a/app-modules/events/src/Enrollment/Models/Enrollment.php +++ b/app-modules/events/src/Enrollment/Models/Enrollment.php @@ -97,16 +97,19 @@ protected static function newFactory(): EnrollmentFactory return EnrollmentFactory::new(); } + /** @param Builder $query */ protected function scopeConfirmed(Builder $query): void { $query->where('status', EnrollmentStatus::Confirmed); } + /** @param Builder $query */ protected function scopeWaitlisted(Builder $query): void { $query->where('status', EnrollmentStatus::Waitlisted); } + /** @param Builder $query */ protected function scopeActive(Builder $query): void { $query->whereNotIn('status', [ diff --git a/app-modules/events/src/Event/Models/Event.php b/app-modules/events/src/Event/Models/Event.php index c6c61e216..5f6006fd4 100644 --- a/app-modules/events/src/Event/Models/Event.php +++ b/app-modules/events/src/Event/Models/Event.php @@ -97,21 +97,25 @@ protected static function newFactory(): EventFactory return EventFactory::new(); } + /** @param Builder $query */ protected function scopePublished(Builder $query): void { $query->where('status', EventStatus::Published); } + /** @param Builder $query */ protected function scopeViewableByParticipant(Builder $query): void { $query->whereIn('status', EventStatus::viewableByParticipant()); } + /** @param Builder $query */ protected function scopeUpcoming(Builder $query): void { $query->where('starts_at', '>', now()); } + /** @param Builder $query */ protected function scopeActive(Builder $query): void { $query->where('status', EventStatus::Published) diff --git a/app-modules/events/tests/Feature/CheckInActionTest.php b/app-modules/events/tests/Feature/CheckInActionTest.php new file mode 100644 index 000000000..01a5dc38b --- /dev/null +++ b/app-modules/events/tests/Feature/CheckInActionTest.php @@ -0,0 +1,174 @@ +create(); + $participant = User::factory()->create(); + $startsAt = now()->setTime(9, 0); + + $event = Event::factory() + ->for($tenant) + ->create(array_merge([ + 'starts_at' => $startsAt, + 'ends_at' => $startsAt->clone()->setTime(18, 0), + 'status' => EventStatus::Published, + ], $eventAttributes)); + + return Enrollment::factory()->create(array_merge([ + 'event_id' => $event->id, + 'user_id' => $participant->id, + 'status' => EnrollmentStatus::Confirmed, + 'confirmed_at' => now(), + ], $enrollmentAttributes)); +} + +test('when organizer checks in confirmed enrollment, then check-in is recorded and enrollment transitions', function (): void { + EventFacade::fake([ParticipantCheckedIn::class]); + + $organizer = User::factory()->create(); + $enrollment = createConfirmedEnrollmentForCheckIn(); + + $checkIn = resolve(ManualCheckInAction::class)->handle( + new ManualCheckInDTO( + enrollment: $enrollment, + actorUserId: $organizer->id, + eventDate: now(), + ), + ); + + expect($checkIn)->toBeInstanceOf(CheckIn::class) + ->and($checkIn->enrollment_id)->toBe($enrollment->id) + ->and($checkIn->method)->toBe(CheckInMethod::Manual) + ->and($checkIn->event_date->isSameDay(now()))->toBeTrue() + ->and($checkIn->checked_in_at)->not->toBeNull() + ->and($checkIn->payload)->toBe(['actor_user_id' => $organizer->id]) + ->and($enrollment->fresh()->status)->toBe(EnrollmentStatus::CheckedIn) + ->and($enrollment->fresh()->checked_in_at)->not->toBeNull(); + + $transition = EnrollmentTransition::query() + ->where('enrollment_id', $enrollment->id) + ->where('to_status', EnrollmentStatus::CheckedIn) + ->first(); + + expect($transition)->not->toBeNull() + ->and($transition->from_status)->toBe(EnrollmentStatus::Confirmed) + ->and($transition->actor_id)->toBe($organizer->id) + ->and($transition->triggered_by)->toBe(TriggeredBy::Admin); + + EventFacade::assertDispatched(fn (ParticipantCheckedIn $event): bool => $event->enrollmentId === $enrollment->id + && $event->eventId === $enrollment->event_id + && $event->userId === $enrollment->user_id + && $event->checkInId === $checkIn->id); +}); + +test('when checked-in enrollment checks in on another event date, then only check-in record is created', function (): void { + $organizer = User::factory()->create(); + $startsAt = now()->setTime(9, 0); + $enrollment = createConfirmedEnrollmentForCheckIn([ + 'starts_at' => $startsAt, + 'ends_at' => $startsAt->clone()->addDay()->setTime(18, 0), + ], [ + 'status' => EnrollmentStatus::CheckedIn, + ]); + + CheckIn::factory()->create([ + 'enrollment_id' => $enrollment->id, + 'event_date' => $startsAt->toDateString(), + 'method' => CheckInMethod::Manual, + 'checked_in_at' => now(), + ]); + + $checkIn = resolve(ManualCheckInAction::class)->handle( + new ManualCheckInDTO( + enrollment: $enrollment, + actorUserId: $organizer->id, + eventDate: $startsAt->clone()->addDay(), + ), + ); + + expect($checkIn->event_date->isSameDay($startsAt->clone()->addDay()))->toBeTrue() + ->and(CheckIn::query()->where('enrollment_id', $enrollment->id)->count())->toBe(2) + ->and(EnrollmentTransition::query() + ->where('enrollment_id', $enrollment->id) + ->where('to_status', EnrollmentStatus::CheckedIn) + ->count())->toBe(0); +}); + +test('when enrollment already has check-in for event date, then duplicate is rejected', function (): void { + $enrollment = createConfirmedEnrollmentForCheckIn(); + + CheckIn::factory()->create([ + 'enrollment_id' => $enrollment->id, + 'event_date' => now()->toDateString(), + 'method' => CheckInMethod::Manual, + ]); + + expect(fn (): CheckIn => resolve(ManualCheckInAction::class)->handle( + new ManualCheckInDTO( + enrollment: $enrollment, + actorUserId: User::factory()->create()->id, + eventDate: now(), + ), + ))->toThrow(CheckInException::class); +}); + +test('when check-in date is outside event date range, then check-in is rejected', function (): void { + $startsAt = now()->setTime(9, 0); + $enrollment = createConfirmedEnrollmentForCheckIn([ + 'starts_at' => $startsAt, + 'ends_at' => $startsAt->clone()->setTime(18, 0), + ]); + + expect(fn (): CheckIn => resolve(ManualCheckInAction::class)->handle( + new ManualCheckInDTO( + enrollment: $enrollment, + actorUserId: User::factory()->create()->id, + eventDate: $startsAt->clone()->addDay(), + ), + ))->toThrow(CheckInException::class); +}); + +test('when enrollment status is not confirmed or checked in, then check-in is rejected', function (): void { + $enrollment = createConfirmedEnrollmentForCheckIn(enrollmentAttributes: [ + 'status' => EnrollmentStatus::Waitlisted, + 'confirmed_at' => null, + ]); + + expect(fn (): CheckIn => resolve(ManualCheckInAction::class)->handle( + new ManualCheckInDTO( + enrollment: $enrollment, + actorUserId: User::factory()->create()->id, + eventDate: now(), + ), + ))->toThrow(CheckInException::class); +}); + +test('when manual check-in has no actor user id, then check-in is rejected', function (): void { + $enrollment = createConfirmedEnrollmentForCheckIn(); + + expect(fn (): CheckIn => resolve(ManualCheckInAction::class)->handle( + new ManualCheckInDTO( + enrollment: $enrollment, + actorUserId: '', + eventDate: now(), + ), + ))->toThrow(CheckInException::class); +}); diff --git a/app-modules/events/tests/Feature/EventResourceTest.php b/app-modules/events/tests/Feature/EventResourceTest.php index 4fbb7f2ea..8d0763ab9 100644 --- a/app-modules/events/tests/Feature/EventResourceTest.php +++ b/app-modules/events/tests/Feature/EventResourceTest.php @@ -4,8 +4,11 @@ use Filament\Facades\Filament; use He4rt\Events\CheckIn\Enums\CheckInMethod; +use He4rt\Events\CheckIn\Models\CheckIn; use He4rt\Events\Enrollment\Enums\AttendanceRequirement; use He4rt\Events\Enrollment\Enums\EnrollmentMethod; +use He4rt\Events\Enrollment\Enums\EnrollmentStatus; +use He4rt\Events\Enrollment\Models\Enrollment; use He4rt\Events\Enrollment\Models\EnrollmentPolicy; use He4rt\Events\Event\Enums\EventType; use He4rt\Events\Event\Models\Event; @@ -137,3 +140,87 @@ ]) ->assertSuccessful(); }); + +test('when admin checks in an enrollment from relation manager, then participant is checked in', function (): void { + $event = Event::factory()->create([ + 'starts_at' => now()->setTime(9, 0), + 'ends_at' => now()->setTime(18, 0), + ]); + + $enrollment = Enrollment::factory()->create([ + 'event_id' => $event->id, + 'status' => EnrollmentStatus::Confirmed, + 'confirmed_at' => now(), + ]); + + livewire(EnrollmentsRelationManager::class, [ + 'ownerRecord' => $event, + 'pageClass' => EditEvent::class, + ]) + ->callTableAction('checkIn', $enrollment, data: [ + 'event_date' => now()->toDateString(), + ]) + ->assertHasNoTableActionErrors(); + + expect($enrollment->fresh()->status)->toBe(EnrollmentStatus::CheckedIn) + ->and(CheckIn::query()->where('enrollment_id', $enrollment->id)->count())->toBe(1); +}); + +test('when admin bulk checks in selected enrollments, then all selected participants are checked in', function (): void { + $event = Event::factory()->create([ + 'starts_at' => now()->setTime(9, 0), + 'ends_at' => now()->setTime(18, 0), + ]); + + $enrollments = Enrollment::factory() + ->count(2) + ->create([ + 'event_id' => $event->id, + 'status' => EnrollmentStatus::Confirmed, + 'confirmed_at' => now(), + ]); + + livewire(EnrollmentsRelationManager::class, [ + 'ownerRecord' => $event, + 'pageClass' => EditEvent::class, + ]) + ->callTableBulkAction('checkInSelected', $enrollments, data: [ + 'event_date' => now()->toDateString(), + ]) + ->assertHasNoTableBulkActionErrors(); + + expect(Enrollment::query()->whereKey($enrollments->pluck('id'))->where('status', EnrollmentStatus::CheckedIn)->count())->toBe(2) + ->and(CheckIn::query()->whereIn('enrollment_id', $enrollments->pluck('id'))->count())->toBe(2); +}); + +test('when enrollment has check-ins, then relation manager shows check-in history', function (): void { + $startsAt = now()->setTime(9, 0); + $event = Event::factory()->create([ + 'starts_at' => $startsAt, + 'ends_at' => $startsAt->clone()->addDay()->setTime(18, 0), + ]); + + $enrollment = Enrollment::factory()->create([ + 'event_id' => $event->id, + 'status' => EnrollmentStatus::CheckedIn, + ]); + + CheckIn::factory()->create([ + 'enrollment_id' => $enrollment->id, + 'event_date' => $startsAt->toDateString(), + 'method' => CheckInMethod::Manual, + ]); + + CheckIn::factory()->create([ + 'enrollment_id' => $enrollment->id, + 'event_date' => $startsAt->clone()->addDay()->toDateString(), + 'method' => CheckInMethod::Manual, + ]); + + livewire(EnrollmentsRelationManager::class, [ + 'ownerRecord' => $event, + 'pageClass' => EditEvent::class, + ]) + ->assertSee($startsAt->toDateString()) + ->assertSee($startsAt->clone()->addDay()->toDateString()); +}); diff --git a/app-modules/events/tests/Unit/EnrollmentStatusTest.php b/app-modules/events/tests/Unit/EnrollmentStatusTest.php index 1f0f934e7..35afe8448 100644 --- a/app-modules/events/tests/Unit/EnrollmentStatusTest.php +++ b/app-modules/events/tests/Unit/EnrollmentStatusTest.php @@ -3,6 +3,7 @@ declare(strict_types=1); use He4rt\Events\Enrollment\Enums\EnrollmentStatus; +use He4rt\Events\Enrollment\Exceptions\EnrollmentException; test('when a pending enrollment is evaluated, then it can transition to confirmed, rejected, or cancelled', function (): void { expect(EnrollmentStatus::Pending->canTransitionTo(EnrollmentStatus::Confirmed))->toBeTrue() @@ -74,3 +75,8 @@ [EnrollmentStatus::Confirmed, 'events::pages.confirm_presence_success'], [EnrollmentStatus::Waitlisted, 'events::pages.waitlist_success'], ]); + +test('when response message is requested for unsupported enrollment status, then it fails explicitly', function (): void { + expect(fn (): string => EnrollmentStatus::Pending->getResponseMessage()) + ->toThrow(EnrollmentException::class); +}); diff --git a/app-modules/panel-admin/src/Filament/Resources/Events/RelationManagers/EnrollmentsRelationManager.php b/app-modules/panel-admin/src/Filament/Resources/Events/RelationManagers/EnrollmentsRelationManager.php index fed021bc8..edb1020aa 100644 --- a/app-modules/panel-admin/src/Filament/Resources/Events/RelationManagers/EnrollmentsRelationManager.php +++ b/app-modules/panel-admin/src/Filament/Resources/Events/RelationManagers/EnrollmentsRelationManager.php @@ -4,11 +4,25 @@ namespace He4rt\PanelAdmin\Filament\Resources\Events\RelationManagers; +use Filament\Actions\Action; +use Filament\Actions\BulkAction; +use Filament\Actions\BulkActionGroup; +use Filament\Forms\Components\DatePicker; +use Filament\Notifications\Notification; use Filament\Resources\RelationManagers\RelationManager; +use Filament\Support\Icons\Heroicon; use Filament\Tables\Columns\TextColumn; use Filament\Tables\Filters\SelectFilter; use Filament\Tables\Table; +use He4rt\Events\CheckIn\Actions\ManualCheckInAction; +use He4rt\Events\CheckIn\DTOs\ManualCheckInDTO; +use He4rt\Events\CheckIn\Models\CheckIn; use He4rt\Events\Enrollment\Enums\EnrollmentStatus; +use He4rt\Events\Enrollment\Models\Enrollment; +use He4rt\Events\Event\Models\Event; +use Illuminate\Database\Eloquent\Builder; +use Illuminate\Database\Eloquent\Collection; +use Illuminate\Support\Facades\Date; final class EnrollmentsRelationManager extends RelationManager { @@ -23,6 +37,7 @@ public function table(Table $table): Table { return $table ->recordTitleAttribute('id') + ->modifyQueryUsing(fn (Builder $query): Builder => $query->with(['checkIns', 'user'])) ->columns([ TextColumn::make('user.name') ->label('Participant') @@ -44,6 +59,15 @@ public function table(Table $table): Table ->dateTime() ->sortable(), + TextColumn::make('check_in_history') + ->label('Check-in History') + ->state(fn (Enrollment $record): string => $record->checkIns + ->sortBy('event_date') + ->map(fn (CheckIn $checkIn): string => $checkIn->event_date->toDateString()) + ->implode(', ')) + ->placeholder('-') + ->toggleable(), + TextColumn::make('cancelled_at') ->label('Cancelled At') ->dateTime() @@ -54,6 +78,88 @@ public function table(Table $table): Table SelectFilter::make('status') ->label('Status') ->options(EnrollmentStatus::class), + ]) + ->recordActions([ + $this->checkInAction(), + ]) + ->toolbarActions([ + BulkActionGroup::make([ + $this->bulkCheckInAction(), + ]), ]); } + + private function checkInAction(): Action + { + return Action::make('checkIn') + ->label('Check In') + ->icon(Heroicon::OutlinedCheckCircle) + ->color('success') + ->visible(fn (Enrollment $record): bool => $record->status->is(EnrollmentStatus::Confirmed, EnrollmentStatus::CheckedIn)) + ->schema($this->checkInSchema()) + ->action(function (Enrollment $record, array $data): void { + $this->checkIn($record, $data); + + Notification::make() + ->success() + ->title('Participant checked in.') + ->send(); + }); + } + + private function bulkCheckInAction(): BulkAction + { + return BulkAction::make('checkInSelected') + ->label('Check In Selected') + ->icon(Heroicon::OutlinedCheckCircle) + ->color('success') + ->schema($this->checkInSchema()) + ->action(function (Collection $records, array $data): void { + foreach ($records as $record) { + if (!$record instanceof Enrollment) { + continue; + } + + $this->checkIn($record, $data); + } + + Notification::make() + ->success() + ->title('Selected participants checked in.') + ->send(); + }) + ->deselectRecordsAfterCompletion(); + } + + /** + * @return array + */ + private function checkInSchema(): array + { + /** @var Event $event */ + $event = $this->getOwnerRecord(); + + return [ + DatePicker::make('event_date') + ->label('Date') + ->default(now()) + ->minDate($event->starts_at->toDateString()) + ->maxDate($event->ends_at->toDateString()) + ->required(), + ]; + } + + /** + * @param array $data + */ + private function checkIn(Enrollment $enrollment, array $data): CheckIn + { + return resolve(ManualCheckInAction::class)->handle( + new ManualCheckInDTO( + enrollment: $enrollment, + actorUserId: (string) auth()->id(), + eventDate: Date::parse($data['event_date']), + ), + ); + } }