From 022f471d3563ce78dc1954fc330e4342dcd850b9 Mon Sep 17 00:00:00 2001 From: Davi Castello Branco Tavares de Oliveira Date: Thu, 4 Jun 2026 19:54:35 -0400 Subject: [PATCH 01/24] feat(enrollment): `resolveAttendance()` method to validate the checkins during the event and change the EnrollmentStatus. --- .../src/Enrollment/Models/EnrollmentPolicy.php | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/app-modules/events/src/Enrollment/Models/EnrollmentPolicy.php b/app-modules/events/src/Enrollment/Models/EnrollmentPolicy.php index 015370905..297cbf6db 100644 --- a/app-modules/events/src/Enrollment/Models/EnrollmentPolicy.php +++ b/app-modules/events/src/Enrollment/Models/EnrollmentPolicy.php @@ -9,6 +9,7 @@ use He4rt\Events\Database\Factories\EnrollmentPolicyFactory; use He4rt\Events\Enrollment\Enums\AttendanceRequirement; use He4rt\Events\Enrollment\Enums\EnrollmentMethod; +use He4rt\Events\Enrollment\Enums\EnrollmentStatus; use He4rt\Events\Event\Models\Event; use Illuminate\Database\Eloquent\Attributes\Table; use Illuminate\Database\Eloquent\Concerns\HasUuids; @@ -69,6 +70,19 @@ public function event(): BelongsTo return $this->belongsTo(Event::class); } + public function resolveAttendance(Enrollment $enrollment): EnrollmentStatus + { + $checkInDays = $enrollment->checkIns()->count(); + + $meets = match ($this->attendance_requirement) { + AttendanceRequirement::AllDays => $checkInDays === $enrollment->event->totalDays(), + AttendanceRequirement::AnyDay => $checkInDays >= 1, + AttendanceRequirement::MinimumDays => $checkInDays >= ($this->minimum_days ?? 0), + }; + + return $meets ? EnrollmentStatus::Attended : EnrollmentStatus::NoShow; + } + protected static function newFactory(): EnrollmentPolicyFactory { return EnrollmentPolicyFactory::new(); From da47e5c168dca8c699cdb71b5f536609830992a7 Mon Sep 17 00:00:00 2001 From: Davi Castello Branco Tavares de Oliveira Date: Thu, 4 Jun 2026 19:57:34 -0400 Subject: [PATCH 02/24] feat(panel_admin): override EnrollmentStatus on the admin panel. --- .../EnrollmentsRelationManager.php | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) 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 e87498d5b..e57cba159 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 @@ -10,6 +10,8 @@ use Filament\Actions\DeleteAction; use Filament\Actions\DeleteBulkAction; use Filament\Forms\Components\DatePicker; +use Filament\Forms\Components\Select; +use Filament\Forms\Components\Textarea; use Filament\Notifications\Notification; use Filament\Resources\RelationManagers\RelationManager; use Filament\Support\Icons\Heroicon; @@ -19,6 +21,8 @@ use He4rt\Events\CheckIn\Actions\ManualCheckInAction; use He4rt\Events\CheckIn\DTOs\ManualCheckInDTO; use He4rt\Events\CheckIn\Models\CheckIn; +use He4rt\Events\Closure\Actions\OverrideEnrollmentStatusAction; +use He4rt\Events\Closure\DTOs\OverrideEnrollmentStatusDTO; use He4rt\Events\Enrollment\Enums\EnrollmentStatus; use He4rt\Events\Enrollment\Models\Enrollment; use He4rt\Events\Event\Models\Event; @@ -84,6 +88,7 @@ public function table(Table $table): Table ]) ->recordActions([ $this->checkInAction(), + $this->overrideStatusAction(), DeleteAction::make(), ]) ->toolbarActions([ @@ -167,4 +172,43 @@ private function checkIn(Enrollment $enrollment, array $data): CheckIn ), ); } + + private function overrideStatusAction(): Action + { + return Action::make('overrideStatus') + ->label('Override Status') + ->icon(Heroicon::OutlinedPencilSquare) + ->color('warning') + ->visible(fn (Enrollment $record): bool => in_array($record->status, [EnrollmentStatus::NoShow, EnrollmentStatus::Confirmed], strict: true)) + ->schema([ + Select::make('to_status') + ->label('New Status') + ->options(fn (Enrollment $record): array => match ($record->status) { + EnrollmentStatus::NoShow => [EnrollmentStatus::Attended->value => 'Attended'], + EnrollmentStatus::Confirmed => [EnrollmentStatus::CheckedIn->value => 'Checked In'], + default => [], + }) + ->required(), + Textarea::make('reason') + ->label('Reason') + ->required() + ->minLength(3) + ->rows(3), + ]) + ->action(function (Enrollment $record, array $data): void { + resolve(OverrideEnrollmentStatusAction::class)->handle( + new OverrideEnrollmentStatusDTO( + enrollment: $record, + toStatus: EnrollmentStatus::from($data['to_status']), + actorId: (string) auth()->id(), + reason: $data['reason'], + ), + ); + + Notification::make() + ->success() + ->title('Enrollment status overridden.') + ->send(); + }); + } } From 747dc31da07b6f9dbff2e83c0dee1e40b4f00bad Mon Sep 17 00:00:00 2001 From: Davi Castello Branco Tavares de Oliveira Date: Thu, 4 Jun 2026 20:02:59 -0400 Subject: [PATCH 03/24] feat(events): schedule `ClosePendingEventsCommand` --- app-modules/events/src/EventsServiceProvider.php | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/app-modules/events/src/EventsServiceProvider.php b/app-modules/events/src/EventsServiceProvider.php index bfe3c5882..0aa2f2e6b 100644 --- a/app-modules/events/src/EventsServiceProvider.php +++ b/app-modules/events/src/EventsServiceProvider.php @@ -5,12 +5,18 @@ namespace He4rt\Events; use He4rt\Events\CheckIn\Listeners\GenerateQrTokenOnConfirmed; +use He4rt\Events\Console\Commands\ClosePendingEventsCommand; use He4rt\Events\Enrollment\Events\EnrollmentConfirmed; +use Illuminate\Console\Scheduling\Schedule; +use Illuminate\Contracts\Container\BindingResolutionException; use Illuminate\Support\Facades\Event; use Illuminate\Support\ServiceProvider; class EventsServiceProvider extends ServiceProvider { + /** + * @throws BindingResolutionException + */ public function boot(): void { $this->loadMigrationsFrom(__DIR__.'/../database/migrations'); @@ -18,5 +24,12 @@ public function boot(): void $this->loadTranslationsFrom(__DIR__.'/../lang', 'events'); Event::listen(EnrollmentConfirmed::class, GenerateQrTokenOnConfirmed::class); + + if ($this->app->runningInConsole()) { + $this->app->make(Schedule::class) + ->command(ClosePendingEventsCommand::class) + ->everyFifteenMinutes() + ->withoutOverlapping(); + } } } From 4f6c111f6a12f5622c8ad2f0af87a29d49ad43e1 Mon Sep 17 00:00:00 2001 From: Davi Castello Branco Tavares de Oliveira Date: Thu, 4 Jun 2026 20:03:42 -0400 Subject: [PATCH 04/24] chore(exceptions): new exceptions translations --- app-modules/events/lang/en/exceptions.php | 2 ++ app-modules/events/lang/pt_BR/exceptions.php | 2 ++ 2 files changed, 4 insertions(+) diff --git a/app-modules/events/lang/en/exceptions.php b/app-modules/events/lang/en/exceptions.php index 58511678b..8305ba864 100644 --- a/app-modules/events/lang/en/exceptions.php +++ b/app-modules/events/lang/en/exceptions.php @@ -10,4 +10,6 @@ '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.', + 'override_reason_required' => 'A reason is required when overriding an enrollment status.', + 'override_not_allowed' => 'Override from :from to :to is not allowed.', ]; diff --git a/app-modules/events/lang/pt_BR/exceptions.php b/app-modules/events/lang/pt_BR/exceptions.php index fdd707908..86b5e6147 100644 --- a/app-modules/events/lang/pt_BR/exceptions.php +++ b/app-modules/events/lang/pt_BR/exceptions.php @@ -10,4 +10,6 @@ '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.', + 'override_reason_required' => 'É obrigatório informar um motivo ao sobrescrever o status de uma inscrição.', + 'override_not_allowed' => 'Sobrescrita de :from para :to não é permitida.', ]; From d47fe97a7139f43eceaca17097816c895aebf4d5 Mon Sep 17 00:00:00 2001 From: Davi Castello Branco Tavares de Oliveira Date: Thu, 4 Jun 2026 20:04:13 -0400 Subject: [PATCH 05/24] docs(adr): ADRs for issue #247 --- .../0007-event-closure-as-scheduled-job.md | 52 ++++++++++++++++ ...dmin-status-override-as-separate-action.md | 60 +++++++++++++++++++ 2 files changed, 112 insertions(+) create mode 100644 app-modules/events/docs/adr/0007-event-closure-as-scheduled-job.md create mode 100644 app-modules/events/docs/adr/0008-admin-status-override-as-separate-action.md diff --git a/app-modules/events/docs/adr/0007-event-closure-as-scheduled-job.md b/app-modules/events/docs/adr/0007-event-closure-as-scheduled-job.md new file mode 100644 index 000000000..431d29652 --- /dev/null +++ b/app-modules/events/docs/adr/0007-event-closure-as-scheduled-job.md @@ -0,0 +1,52 @@ +# ADR-0007: Event closure as scheduled job + +## Status + +Accepted — 2026-06-04 + +## Context + +After an event's `ends_at`, enrollments must be resolved to terminal states: `attended` (success, when `attendance_requirement` is satisfied per the policy) or `no_show` (failure, when not). Without automated closure, enrollments stay in `confirmed` or `checked_in` indefinitely, blocking `ParticipantAttended` dispatch and the XP reward that Gamification awards on that event (ADR-0002). Manual organizer action does not scale, and real-time closure on `ends_at` is fragile (clock drift, job queue downtime, multi-day events whose `ends_at` is the final day). + +The closure step is also the natural place to mark `confirmed` participants who never checked in as `no_show`. This is a system-driven consequence, not an organizer decision. + +## Decision + +### Closure is a post-event scheduled sweep + +A scheduled job runs after events end and resolves every non-terminal enrollment to a terminal state. This is decoupled from any real-time trigger on `ends_at` so that queue downtime, clock drift, or off-by-one date math cannot leave enrollments stranded. + +### Per-event job granularity + +`ProcessEventClosureJob` handles one event at a time (constructor takes `string $eventId`). The job implements `ShouldQueue` and `ShouldBeUnique` with `uniqueId = $eventId` and `uniqueFor = 1800` seconds. This means concurrent dispatches for the same event collapse into a single execution, and the lock covers the full retry window (backoff sum ≈ 16 minutes, plus buffer). + +`$backoff = [1, 5, 10]` and `tries = 4` (1 initial + 3 retries). After exhaustion, `failed()` runs and logs the `event_id` plus the exception message. + +### Per-enrollment transactions, not per-event + +`CloseEventAction::handle(Event $event): int` opens one `DB::transaction` per enrollment inside its loop, not one transaction wrapping the entire event. This is a deliberate departure from the "all-or-nothing per operation" default in favour of **partial commits that preserve audit trails on failure**. + +The loop is: + +1. Re-load the enrollment with `lockForUpdate()`. +2. If the enrollment is already terminal (`isTerminal()` returns true — e.g. a previous attempt succeeded, or an admin override landed between attempts), skip it. +3. Resolve the target status: `EnrollmentPolicy::resolveAttendance($enrollment)` for `checked_in` (returns `Attended` or `NoShow`), or `NoShow` directly for `confirmed`. +4. Call the existing `TransitionEnrollmentAction` (ADR-0001, ADR-0003) with `triggered_by = System`. This writes the audit row and updates the status + timestamp atomically. +5. If the target is `Attended`, dispatch `ParticipantAttended` (mirroring `ParticipantCheckedIn` payload shape — IDs, not models). + +Idempotency is therefore structural: the `isTerminal()` re-check + `canTransitionTo()` guard + `lockForUpdate()` make a second run a no-op for already-closed enrollments. + +### Discovery via artisan command + +A `ClosePendingEventsCommand` (`events:close-pending`) queries `Event` where `ends_at < now()` AND has at least one enrollment in `confirmed` or `checked_in`, then dispatches one `ProcessEventClosureJob` per match. Scheduled every 15 minutes in `EventsServiceProvider::boot()` via `Schedule::command(...)->everyFifteenMinutes()->withoutOverlapping()`. + +This is the same pattern `IntegrationDevToServiceProvider` uses for its own scheduled command, so the discovery mechanism is testable (`Artisan::call`) and manually runnable. + +## Consequences + +- **Audit trail on partial failure** — if the 3rd enrollment in a 100-enrollment event throws mid-loop, the first two keep their `EnrollmentTransition` records. The retry can pick up from the 3rd without re-doing work or losing history. +- **Concurrency-safe** — `ShouldBeUnique` prevents two jobs processing the same event, even if the scheduler fires twice in a race. +- **Retry-friendly** — completed enrollments are skipped via the `isTerminal()` re-check, so retries do not re-dispatch `ParticipantAttended` or write duplicate transitions. +- **Worst-case latency** — `ends_at` to closure is at most 15 minutes (one scheduler tick) plus job queue latency. Acceptable for terminal-state assignment, which is not user-facing in real time. +- **Trade-off** — a 3-retry ceiling means persistent infrastructure failures (DB outage spanning >16 minutes) end up in the `failed()` log instead of auto-recovery. The command will redispatch on the next scheduler tick, so eventual closure is still likely without human intervention. +- **Trade-off** — the 15-minute cadence means a `ParticipantAttended` event may fire up to 15 minutes after the event ends. Gamification's XP grant follows the same window. Documented in `EnrollmentPolicy::$xp_on_attended` consumers (Gamification listeners). diff --git a/app-modules/events/docs/adr/0008-admin-status-override-as-separate-action.md b/app-modules/events/docs/adr/0008-admin-status-override-as-separate-action.md new file mode 100644 index 000000000..9e52805fb --- /dev/null +++ b/app-modules/events/docs/adr/0008-admin-status-override-as-separate-action.md @@ -0,0 +1,60 @@ +# ADR-0008: Admin status override as separate Action + +## Status + +Accepted — 2026-06-04 + +## Context + +The enrollment state machine (ADR-0001) blocks all transitions out of terminal states. This is correct for the normal lifecycle: an `attended` enrollment should never revert to `checked_in`, and `no_show` should never silently become `attended`. But real-world organizer needs include: + +- A participant marked `no_show` who actually attended (organizer missed a check-in, code expired, manual check-in failed silently). +- A late arrival who confirmed but missed the formal check-in window and the organizer wants to mark them `checked_in` to record the presence. + +These are **admin corrections**, not normal lifecycle transitions. They need a different validation surface, a stronger audit story, and a clear rule that they bypass the state machine for a tightly-scoped set of cases. + +## Decision + +### Override is a separate Action + +Introduce `OverrideEnrollmentStatusAction` as a sibling to `TransitionEnrollmentAction`, not a force-flag on it. The two actions have different validation, different intent, and different side effects. A force flag on `TransitionEnrollmentAction` would have to be threaded through `TransitionEnrollmentDTO`, the transition audit, and any future caller — and would silently widen the surface that can bypass the state machine. + +### Allowed overrides are explicit and narrow + +The Action validates the `(fromStatus, toStatus)` pair against an explicit allowlist: + +| From | To | Use case | +| ----------- | ------------ | ---------------------------------------- | +| `no_show` | `attended` | Organizer corrects a missed check-in | +| `confirmed` | `checked_in` | Late arrival that missed formal check-in | + +Any other pair — including `attended → no_show`, `cancelled → attended`, or any path starting from `attended`/`cancelled`/`rejected` — is rejected with `OverrideEnrollmentStatusException::overrideNotAllowed(from, to)`. + +### Reason is required and recorded + +`OverrideEnrollmentStatusDTO` takes a non-empty `reason` string. The Action throws `OverrideEnrollmentStatusException::reasonRequired()` on empty input. The reason is written to `EnrollmentTransition::$reason` for accountability, alongside `triggered_by = admin` and `actor_id = $organizer->id`. + +### Override does not re-dispatch domain events + +No `ParticipantAttended` or `ParticipantCheckedIn` is dispatched on override. The override is a correction of the audit trail, not a fresh occurrence. XP implications: + +- `no_show → attended` does not grant XP retroactively. The participant was marked absent by the closure job; admin correction updates the record but the system-level "first time attended" event has already passed. +- `confirmed → checked_in` does not dispatch `ParticipantCheckedIn`. Same reasoning — the check-in did not happen through the normal flow, and the system event has semantic meaning tied to actual check-in mechanics. + +If retroactive XP is ever needed, it is a separate decision (likely a `ParticipantManuallyAttended` event, with its own audience in Gamification). + +### Filament UI is inline in the EnrollmentsRelationManager + +An `overrideStatusAction()` method is added to `EnrollmentsRelationManager` next to the existing `checkInAction()` method (same private-method pattern, same Action delegation style). It opens a modal with a reason textarea and a status select pre-populated with the allowed targets. The action is visible only when the current status is in the allowlist source set (`no_show`, `confirmed`) — anything else hides the action entirely. + +### No runtime inconsistency checks + +The form and factory enforce that `minimum_days` is set when `attendance_requirement = MinimumDays`. There is no save-time guard on `EnrollmentPolicy` for inconsistent `(requirement, minimum_days)` — this is defense at the edges only. See ADR-0007 for the closure-side evaluator that trusts the data. + +## Consequences + +- **Strong accountability** — every override writes an audit row with the organizer's identity and their stated reason. +- **Tightly scoped bypass** — the state machine is still the gatekeeper for all non-override transitions. The override path is the _only_ way to leave a terminal state, and it is one line in one Action. +- **No XP duplication risk** — by not re-dispatching domain events, an admin override cannot grant XP twice for the same participant-event pair. +- **Trade-off** — overriding a status that has downstream side effects beyond XP (e.g. waitlist promotion triggered by `confirmed → cancelled`) does not replay those side effects. Acceptable for the current scope; flag if a new side-effect is added. +- **Trade-off** — the inline `overrideStatusAction()` method grows `EnrollmentsRelationManager` by ~30 lines. If a third enrollment-related action lands, extract them into a `Actions/` directory inside the relation manager (matching the `GenerateCheckInCodeAction` / `RevokeCheckInCodeAction` pattern already used by `CheckInCodesRelationManager`). From 36ca23b4a843adb7c2347c7fef827c61ca8c7470 Mon Sep 17 00:00:00 2001 From: Davi Castello Branco Tavares de Oliveira Date: Thu, 4 Jun 2026 20:11:53 -0400 Subject: [PATCH 06/24] feat(events): closure pending events command `events:close-pending` --- .../Commands/ClosePendingEventsCommand.php | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 app-modules/events/src/Console/Commands/ClosePendingEventsCommand.php diff --git a/app-modules/events/src/Console/Commands/ClosePendingEventsCommand.php b/app-modules/events/src/Console/Commands/ClosePendingEventsCommand.php new file mode 100644 index 000000000..66316f07b --- /dev/null +++ b/app-modules/events/src/Console/Commands/ClosePendingEventsCommand.php @@ -0,0 +1,37 @@ +where('ends_at', '<', now()) + ->whereHas('enrollments', function (Builder $query): void { + $query->whereIn('status', [EnrollmentStatus::Confirmed, EnrollmentStatus::CheckedIn]); + }) + ->each(function (Event $event) use (&$count): void { + dispatch(new ProcessEventClosureJob($event->id)); + $count++; + }); + + $this->info(sprintf('Dispatched %d closure job(s).', $count)); + + return self::SUCCESS; + } +} From 325d2840950d9ce3be5ed1af082803cc06b4f827 Mon Sep 17 00:00:00 2001 From: Davi Castello Branco Tavares de Oliveira Date: Thu, 4 Jun 2026 20:17:36 -0400 Subject: [PATCH 07/24] feat(panel-admin): added attendance requirements on `EventForm` --- .../Resources/Events/Schemas/EventForm.php | 53 ++++++++++++++++++- 1 file changed, 51 insertions(+), 2 deletions(-) diff --git a/app-modules/panel-admin/src/Filament/Resources/Events/Schemas/EventForm.php b/app-modules/panel-admin/src/Filament/Resources/Events/Schemas/EventForm.php index e4d353aff..b52554a08 100644 --- a/app-modules/panel-admin/src/Filament/Resources/Events/Schemas/EventForm.php +++ b/app-modules/panel-admin/src/Filament/Resources/Events/Schemas/EventForm.php @@ -19,6 +19,7 @@ use He4rt\Events\Event\Enums\EventStatus; use He4rt\Events\Event\Enums\EventType; use He4rt\Events\Event\Models\Event; +use Illuminate\Support\Facades\Date; use Illuminate\Validation\Rules\Unique; final class EventForm @@ -114,14 +115,19 @@ public static function configure(Schema $schema): Schema Select::make('attendance_requirement') ->label('Attendance Requirement') - ->options(AttendanceRequirement::class) + ->options(fn (Get $get): array => self::attendanceRequirementOptions($get)) + ->live() ->required(), TextInput::make('minimum_days') ->label('Minimum Days') + ->helperText('Required when attendance requirement is "Minimum Days". Default 1, max = event days.') ->integer() ->minValue(1) - ->nullable(), + ->maxValue(fn (Get $get): ?int => self::minimumDaysMaxValue($get)) + ->default(1) + ->required(fn (Get $get): bool => $get('attendance_requirement') === AttendanceRequirement::MinimumDays->value) + ->visible(fn (Get $get): bool => $get('attendance_requirement') === AttendanceRequirement::MinimumDays->value), TextInput::make('cancellation_deadline_hours') ->label('Cancellation Deadline (hours before event)') @@ -157,4 +163,47 @@ public static function configure(Schema $schema): Schema ]), ]); } + + /** + * @return array + */ + private static function attendanceRequirementOptions(Get $get): array + { + $all = [ + AttendanceRequirement::AllDays->value => __('events::enums.attendance_requirement.all_days'), + AttendanceRequirement::AnyDay->value => __('events::enums.attendance_requirement.any_day'), + AttendanceRequirement::MinimumDays->value => __('events::enums.attendance_requirement.minimum_days'), + ]; + + $startsAt = $get('starts_at'); + $endsAt = $get('ends_at'); + + if ($startsAt === null || $endsAt === null) { + return $all; + } + + $startsDay = Date::parse($startsAt)->startOfDay(); + $endsDay = Date::parse($endsAt)->startOfDay(); + + if ($startsDay->equalTo($endsDay)) { + return [AttendanceRequirement::AnyDay->value => $all[AttendanceRequirement::AnyDay->value]]; + } + + return $all; + } + + private static function minimumDaysMaxValue(Get $get): ?int + { + $startsAt = $get('starts_at'); + $endsAt = $get('ends_at'); + + if ($startsAt === null || $endsAt === null) { + return null; + } + + $startsDay = Date::parse($startsAt)->startOfDay(); + $endsDay = Date::parse($endsAt)->startOfDay(); + + return (int) $startsDay->diffInDays($endsDay) + 1; + } } From 5d3895112c1c0e503b204098ebb9d7cec3ff3a4f Mon Sep 17 00:00:00 2001 From: Davi Castello Branco Tavares de Oliveira Date: Thu, 4 Jun 2026 20:18:59 -0400 Subject: [PATCH 08/24] feat(events): added attendance_requirements and minimun_days to `EnrollmentPolicyFactory` --- .../events/database/factories/EnrollmentPolicyFactory.php | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/app-modules/events/database/factories/EnrollmentPolicyFactory.php b/app-modules/events/database/factories/EnrollmentPolicyFactory.php index 45add3dfc..b4b771f71 100644 --- a/app-modules/events/database/factories/EnrollmentPolicyFactory.php +++ b/app-modules/events/database/factories/EnrollmentPolicyFactory.php @@ -18,14 +18,16 @@ final class EnrollmentPolicyFactory extends Factory public function definition(): array { + $requirement = fake()->randomElement(AttendanceRequirement::cases()); + return [ 'event_id' => Event::factory(), 'enrollment_method' => fake()->randomElement(EnrollmentMethod::cases()), 'check_in_method' => fake()->randomElement(CheckInMethod::cases()), 'capacity' => fake()->optional()->numberBetween(10, 200), 'has_waitlist' => false, - 'attendance_requirement' => AttendanceRequirement::AllDays, - 'minimum_days' => null, + 'attendance_requirement' => $requirement, + 'minimum_days' => $requirement === AttendanceRequirement::MinimumDays ? 1 : null, 'cancellation_deadline_hours' => null, 'xp_on_confirmed' => 0, 'xp_on_checked_in' => 0, From 0fdf456e32108d006bf2c6d97d77ff9618e2a6e9 Mon Sep 17 00:00:00 2001 From: Davi Castello Branco Tavares de Oliveira Date: Thu, 4 Jun 2026 20:19:48 -0400 Subject: [PATCH 09/24] feat(events): Close event implementation --- .../src/Closure/Actions/CloseEventAction.php | 76 +++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 app-modules/events/src/Closure/Actions/CloseEventAction.php diff --git a/app-modules/events/src/Closure/Actions/CloseEventAction.php b/app-modules/events/src/Closure/Actions/CloseEventAction.php new file mode 100644 index 000000000..1108aaf30 --- /dev/null +++ b/app-modules/events/src/Closure/Actions/CloseEventAction.php @@ -0,0 +1,76 @@ +enrollments() + ->whereIn('status', [EnrollmentStatus::Confirmed, EnrollmentStatus::CheckedIn]) + ->each(function (Enrollment $enrollment) use (&$attendances): void { + $attendances += $this->closeOne($enrollment); + }); + + return $attendances; + } + + /** + * @throws Throwable + */ + private function closeOne(Enrollment $enrollment): int + { + return DB::transaction(static function () use ($enrollment): int { + $locked = Enrollment::query() + ->with('event.enrollmentPolicy') + ->whereKey($enrollment->id) + ->lockForUpdate() + ->first(); + + if ($locked === null || $locked->status->isTerminal()) { + return 0; + } + + $toStatus = $locked->status === EnrollmentStatus::CheckedIn + ? $locked->event->enrollmentPolicy->resolveAttendance($locked) + : EnrollmentStatus::NoShow; + + resolve(TransitionEnrollmentAction::class)->handle( + new TransitionEnrollmentDTO( + enrollment: $locked, + toStatus: $toStatus, + triggeredBy: TriggeredBy::System, + ), + ); + + if ($toStatus === EnrollmentStatus::Attended) { + $xpReward = ($locked->event->enrollmentPolicy->xp_on_attended ?? 0); + + event(new ParticipantAttended( + enrollmentId: $locked->id, + eventId: $locked->event_id, + userId: $locked->user_id, + xpRewardOnAttended: $xpReward, + )); + + return 1; + } + + return 0; + }); + } +} From 87e959a667b6a203bf279b0847091fbcf4dba90a Mon Sep 17 00:00:00 2001 From: Davi Castello Branco Tavares de Oliveira Date: Thu, 4 Jun 2026 20:21:05 -0400 Subject: [PATCH 10/24] feat(events): Admin override logic --- .../OverrideEnrollmentStatusAction.php | 63 +++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 app-modules/events/src/Closure/Actions/OverrideEnrollmentStatusAction.php diff --git a/app-modules/events/src/Closure/Actions/OverrideEnrollmentStatusAction.php b/app-modules/events/src/Closure/Actions/OverrideEnrollmentStatusAction.php new file mode 100644 index 000000000..578b15d73 --- /dev/null +++ b/app-modules/events/src/Closure/Actions/OverrideEnrollmentStatusAction.php @@ -0,0 +1,63 @@ + EnrollmentStatus::NoShow, 'to' => EnrollmentStatus::Attended], + ['from' => EnrollmentStatus::Confirmed, 'to' => EnrollmentStatus::CheckedIn], + ]; + + /** + * @throws OverrideEnrollmentStatusException + * @throws Throwable + */ + public function handle(OverrideEnrollmentStatusDTO $dto): EnrollmentTransition + { + if (mb_trim($dto->reason) === '') { + throw OverrideEnrollmentStatusException::reasonRequired(); + } + + $fromStatus = $dto->enrollment->status; + + throw_unless( + $this->isAllowed($fromStatus, $dto->toStatus), + OverrideEnrollmentStatusException::overrideNotAllowed($fromStatus, $dto->toStatus), + ); + + return DB::transaction(static function () use ($dto, $fromStatus): EnrollmentTransition { + $attributes = ['status' => $dto->toStatus]; + + if ($timestampColumn = $dto->toStatus->timestampColumn()) { + $attributes[$timestampColumn] = now(); + } + + $dto->enrollment->update($attributes); + + return EnrollmentTransition::query()->create([ + 'enrollment_id' => $dto->enrollment->id, + 'from_status' => $fromStatus, + 'to_status' => $dto->toStatus, + 'actor_id' => $dto->actorId, + 'triggered_by' => TriggeredBy::Admin, + 'reason' => $dto->reason, + ]); + }); + } + + private function isAllowed(EnrollmentStatus $from, EnrollmentStatus $to): bool + { + return array_any(self::ALLOWED_OVERRIDES, fn ($pair) => $pair['from'] === $from && $pair['to'] === $to); + } +} From 821ef1397eda5ebaf846bdd32f3fd6b80c2fc0c6 Mon Sep 17 00:00:00 2001 From: Davi Castello Branco Tavares de Oliveira Date: Thu, 4 Jun 2026 20:22:01 -0400 Subject: [PATCH 11/24] feat(events): Admin `OverrideEnrollment` DTO --- .../DTOs/OverrideEnrollmentStatusDTO.php | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 app-modules/events/src/Closure/DTOs/OverrideEnrollmentStatusDTO.php diff --git a/app-modules/events/src/Closure/DTOs/OverrideEnrollmentStatusDTO.php b/app-modules/events/src/Closure/DTOs/OverrideEnrollmentStatusDTO.php new file mode 100644 index 000000000..f3404c045 --- /dev/null +++ b/app-modules/events/src/Closure/DTOs/OverrideEnrollmentStatusDTO.php @@ -0,0 +1,18 @@ + Date: Thu, 4 Jun 2026 20:23:06 -0400 Subject: [PATCH 12/24] feat(events): Close event job --- .../Closure/Jobs/ProcessEventClosureJob.php | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 app-modules/events/src/Closure/Jobs/ProcessEventClosureJob.php diff --git a/app-modules/events/src/Closure/Jobs/ProcessEventClosureJob.php b/app-modules/events/src/Closure/Jobs/ProcessEventClosureJob.php new file mode 100644 index 000000000..7a68f1a95 --- /dev/null +++ b/app-modules/events/src/Closure/Jobs/ProcessEventClosureJob.php @@ -0,0 +1,56 @@ +eventId; + } + + public function handle(CloseEventAction $action): void + { + $event = Event::query()->find($this->eventId); + + if ($event === null) { + return; + } + + $action->handle($event); + } + + public function failed(Throwable $e): void + { + Log::error('Event closure failed', [ + 'event_id' => $this->eventId, + 'error' => $e->getMessage(), + ]); + } +} From ed4b5b60db161cbbef9314a465f5176deeb28311 Mon Sep 17 00:00:00 2001 From: Davi Castello Branco Tavares de Oliveira Date: Thu, 4 Jun 2026 20:23:30 -0400 Subject: [PATCH 13/24] feat(events): OverrideEnrollment exceptions --- .../OverrideEnrollmentStatusException.php | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 app-modules/events/src/Closure/Exceptions/OverrideEnrollmentStatusException.php diff --git a/app-modules/events/src/Closure/Exceptions/OverrideEnrollmentStatusException.php b/app-modules/events/src/Closure/Exceptions/OverrideEnrollmentStatusException.php new file mode 100644 index 000000000..1a47fd6b7 --- /dev/null +++ b/app-modules/events/src/Closure/Exceptions/OverrideEnrollmentStatusException.php @@ -0,0 +1,28 @@ + $from->value, 'to' => $to->value]), + Response::HTTP_UNPROCESSABLE_ENTITY, + ); + } +} From f9dfa7fddf0a2ab5642d5cf8b7da6bb6d4d8ba78 Mon Sep 17 00:00:00 2001 From: Davi Castello Branco Tavares de Oliveira Date: Thu, 4 Jun 2026 20:32:12 -0400 Subject: [PATCH 14/24] feat(events): add ParticipantAttended event and closure tests - ParticipantAttended domain event dispatched when enrollment reaches attended status - CloseEventActionTest: 6 tests covering all_days, any_day, no-show, idempotency, multi-enrollment - ClosePendingEventsCommandTest: 4 tests for job dispatch logic - OverrideEnrollmentStatusActionTest: 5 tests for admin override (allowed transitions, reason required, exceptions) - ProcessEventClosureJobTest: 5 tests for job config, failure logging, idempotency - EnrollmentPolicyTest: 5 tests for resolveAttendance (all_days, any_day, minimum_days) Refs #247 --- .../Closure/Events/ParticipantAttended.php | 21 ++ .../Feature/Closure/CloseEventActionTest.php | 217 ++++++++++++++++++ .../Closure/ClosePendingEventsCommandTest.php | 108 +++++++++ .../OverrideEnrollmentStatusActionTest.php | 145 ++++++++++++ .../Closure/ProcessEventClosureJobTest.php | 95 ++++++++ .../Enrollment/EnrollmentPolicyTest.php | 142 ++++++++++++ 6 files changed, 728 insertions(+) create mode 100644 app-modules/events/src/Closure/Events/ParticipantAttended.php create mode 100644 app-modules/events/tests/Feature/Closure/CloseEventActionTest.php create mode 100644 app-modules/events/tests/Feature/Closure/ClosePendingEventsCommandTest.php create mode 100644 app-modules/events/tests/Feature/Closure/OverrideEnrollmentStatusActionTest.php create mode 100644 app-modules/events/tests/Feature/Closure/ProcessEventClosureJobTest.php create mode 100644 app-modules/events/tests/Feature/Enrollment/EnrollmentPolicyTest.php diff --git a/app-modules/events/src/Closure/Events/ParticipantAttended.php b/app-modules/events/src/Closure/Events/ParticipantAttended.php new file mode 100644 index 000000000..a19ab6eb7 --- /dev/null +++ b/app-modules/events/src/Closure/Events/ParticipantAttended.php @@ -0,0 +1,21 @@ +create(); + $startsAt = now()->subDays(3)->setTime(9, 0); + + return Event::factory() + ->for($tenant) + ->has(EnrollmentPolicy::factory()->state(array_merge([ + 'attendance_requirement' => AttendanceRequirement::AllDays, + 'minimum_days' => null, + 'xp_on_attended' => 0, + ], $policyAttributes)), 'enrollmentPolicy') + ->create(array_merge([ + 'starts_at' => $startsAt, + 'ends_at' => $startsAt->clone()->addDays(2)->setTime(18, 0), + 'status' => EventStatus::Published, + ], $eventAttributes)); +} + +test('when checked_in enrollment meets all_days, then action transitions to Attended and dispatches ParticipantAttended', function (): void { + EventFacade::fake([ParticipantAttended::class]); + + $startsAt = now()->subDays(3)->setTime(9, 0); + $event = createEventForClosure([ + 'starts_at' => $startsAt, + 'ends_at' => $startsAt->clone()->addDays(2)->setTime(18, 0), + ], [ + 'attendance_requirement' => AttendanceRequirement::AllDays, + 'xp_on_attended' => 75, + ]); + + $enrollment = Enrollment::factory()->create([ + 'event_id' => $event->id, + 'user_id' => User::factory()->create()->id, + 'status' => EnrollmentStatus::CheckedIn, + 'checked_in_at' => now(), + ]); + + 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]); + CheckIn::factory()->create(['enrollment_id' => $enrollment->id, 'event_date' => $startsAt->clone()->addDays(2)->toDateString(), 'method' => CheckInMethod::Manual]); + + $attended = resolve(CloseEventAction::class)->handle($event); + + expect($attended)->toBe(1) + ->and($enrollment->fresh()->status)->toBe(EnrollmentStatus::Attended) + ->and($enrollment->fresh()->attended_at)->not->toBeNull(); + + $transition = EnrollmentTransition::query() + ->where('enrollment_id', $enrollment->id) + ->where('to_status', EnrollmentStatus::Attended) + ->first(); + + expect($transition)->not->toBeNull() + ->and($transition->from_status)->toBe(EnrollmentStatus::CheckedIn) + ->and($transition->triggered_by)->toBe(TriggeredBy::System); + + EventFacade::assertDispatched(fn (ParticipantAttended $e): bool => $e->enrollmentId === $enrollment->id + && $e->eventId === $event->id + && $e->xpRewardOnAttended === 75); +}); + +test('when checked_in enrollment is missing check-ins for all_days, then action transitions to NoShow without dispatching event', function (): void { + EventFacade::fake([ParticipantAttended::class]); + + $startsAt = now()->subDays(3)->setTime(9, 0); + $event = createEventForClosure([ + 'starts_at' => $startsAt, + 'ends_at' => $startsAt->clone()->addDays(2)->setTime(18, 0), + ], [ + 'attendance_requirement' => AttendanceRequirement::AllDays, + ]); + + $enrollment = Enrollment::factory()->create([ + 'event_id' => $event->id, + 'user_id' => User::factory()->create()->id, + 'status' => EnrollmentStatus::CheckedIn, + 'checked_in_at' => now(), + ]); + + CheckIn::factory()->create(['enrollment_id' => $enrollment->id, 'event_date' => $startsAt->toDateString(), 'method' => CheckInMethod::Manual]); + + $attended = resolve(CloseEventAction::class)->handle($event); + + expect($attended)->toBe(0) + ->and($enrollment->fresh()->status)->toBe(EnrollmentStatus::NoShow); + + EventFacade::assertNotDispatched(ParticipantAttended::class); +}); + +test('when confirmed enrollment never checked in, then action transitions to NoShow', function (): void { + EventFacade::fake([ParticipantAttended::class]); + + $event = createEventForClosure(); + $enrollment = Enrollment::factory()->create([ + 'event_id' => $event->id, + 'user_id' => User::factory()->create()->id, + 'status' => EnrollmentStatus::Confirmed, + 'confirmed_at' => now()->subDay(), + ]); + + $attended = resolve(CloseEventAction::class)->handle($event); + + expect($attended)->toBe(0) + ->and($enrollment->fresh()->status)->toBe(EnrollmentStatus::NoShow); + + EventFacade::assertNotDispatched(ParticipantAttended::class); +}); + +test('when terminal enrollment is present, then action skips it', function (): void { + EventFacade::fake([ParticipantAttended::class]); + + $event = createEventForClosure(); + $enrollment = Enrollment::factory()->create([ + 'event_id' => $event->id, + 'user_id' => User::factory()->create()->id, + 'status' => EnrollmentStatus::Cancelled, + 'cancelled_at' => now()->subDay(), + ]); + + $attended = resolve(CloseEventAction::class)->handle($event); + + expect($attended)->toBe(0) + ->and($enrollment->fresh()->status)->toBe(EnrollmentStatus::Cancelled); + + $transitionCount = EnrollmentTransition::query() + ->where('enrollment_id', $enrollment->id) + ->count(); + + expect($transitionCount)->toBe(0); +}); + +test('when action runs twice, then second run is no-op (idempotent)', function (): void { + EventFacade::fake([ParticipantAttended::class]); + + $event = createEventForClosure(); + $enrollment = Enrollment::factory()->create([ + 'event_id' => $event->id, + 'user_id' => User::factory()->create()->id, + 'status' => EnrollmentStatus::Confirmed, + 'confirmed_at' => now()->subDay(), + ]); + + $first = resolve(CloseEventAction::class)->handle($event); + $second = resolve(CloseEventAction::class)->handle($event); + + expect($first)->toBe(0) + ->and($second)->toBe(0); + + $transitions = EnrollmentTransition::query() + ->where('enrollment_id', $enrollment->id) + ->where('to_status', EnrollmentStatus::NoShow) + ->count(); + + expect($transitions)->toBe(1); +}); + +test('when action processes multiple enrollments, then each is closed independently with system audit trail', function (): void { + EventFacade::fake([ParticipantAttended::class]); + + $startsAt = now()->subDays(3)->setTime(9, 0); + $event = createEventForClosure([ + 'starts_at' => $startsAt, + 'ends_at' => $startsAt->clone()->addDays(2)->setTime(18, 0), + ], [ + 'attendance_requirement' => AttendanceRequirement::AnyDay, + ]); + $confirmed = Enrollment::factory()->create([ + 'event_id' => $event->id, + 'user_id' => User::factory()->create()->id, + 'status' => EnrollmentStatus::Confirmed, + 'confirmed_at' => now()->subDay(), + ]); + $checkedIn = Enrollment::factory()->create([ + 'event_id' => $event->id, + 'user_id' => User::factory()->create()->id, + 'status' => EnrollmentStatus::CheckedIn, + 'checked_in_at' => now()->subDay(), + ]); + + CheckIn::factory()->create(['enrollment_id' => $checkedIn->id, 'event_date' => $startsAt->toDateString(), 'method' => CheckInMethod::Manual]); + + resolve(CloseEventAction::class)->handle($event); + + expect($confirmed->fresh()->status)->toBe(EnrollmentStatus::NoShow) + ->and($checkedIn->fresh()->status)->toBe(EnrollmentStatus::Attended) + ->and($checkedIn->fresh()->attended_at)->not->toBeNull(); + + foreach ([$confirmed->id, $checkedIn->id] as $enrollmentId) { + $transition = EnrollmentTransition::query() + ->where('enrollment_id', $enrollmentId) + ->first(); + + expect($transition)->not->toBeNull() + ->and($transition->triggered_by)->toBe(TriggeredBy::System); + } +}); diff --git a/app-modules/events/tests/Feature/Closure/ClosePendingEventsCommandTest.php b/app-modules/events/tests/Feature/Closure/ClosePendingEventsCommandTest.php new file mode 100644 index 000000000..650c2a0f4 --- /dev/null +++ b/app-modules/events/tests/Feature/Closure/ClosePendingEventsCommandTest.php @@ -0,0 +1,108 @@ +create(); + $startsAt = now()->subDays(3)->setTime(9, 0); + + return Event::factory() + ->for($tenant) + ->has(EnrollmentPolicy::factory()->state(array_merge([ + 'attendance_requirement' => AttendanceRequirement::AllDays, + 'minimum_days' => null, + ], $policyAttributes)), 'enrollmentPolicy') + ->create(array_merge([ + 'starts_at' => $startsAt, + 'ends_at' => $startsAt->clone()->setTime(18, 0), + 'status' => EventStatus::Published, + ], $eventAttributes)); +} + +test('when command runs and past event has non-terminal enrollments, then it dispatches a closure job', function (): void { + Bus::fake([ProcessEventClosureJob::class]); + + $event = makeEventForCommandTest(); + Enrollment::factory()->create([ + 'event_id' => $event->id, + 'user_id' => User::factory()->create()->id, + 'status' => EnrollmentStatus::Confirmed, + 'confirmed_at' => now()->subDay(), + ]); + + $this->artisan('events:close-pending') + ->expectsOutputToContain('Dispatched 1 closure job(s).') + ->assertSuccessful(); + + Bus::assertDispatched(fn (ProcessEventClosureJob $job): bool => $job->eventId === $event->id); +}); + +test('when command runs and event is in the future, then no job is dispatched', function (): void { + Bus::fake([ProcessEventClosureJob::class]); + + $futureStartsAt = now()->addDays(5)->setTime(9, 0); + $event = makeEventForCommandTest([ + 'starts_at' => $futureStartsAt, + 'ends_at' => $futureStartsAt->clone()->setTime(18, 0), + ]); + Enrollment::factory()->create([ + 'event_id' => $event->id, + 'user_id' => User::factory()->create()->id, + 'status' => EnrollmentStatus::Confirmed, + 'confirmed_at' => now(), + ]); + + $this->artisan('events:close-pending'); + + Bus::assertNotDispatched(ProcessEventClosureJob::class); +}); + +test('when command runs and past event has only terminal enrollments, then no job is dispatched', function (): void { + Bus::fake([ProcessEventClosureJob::class]); + + $event = makeEventForCommandTest(); + Enrollment::factory()->create([ + 'event_id' => $event->id, + 'user_id' => User::factory()->create()->id, + 'status' => EnrollmentStatus::Attended, + 'attended_at' => now()->subDay(), + ]); + + $this->artisan('events:close-pending'); + + Bus::assertNotDispatched(ProcessEventClosureJob::class); +}); + +test('when command runs and multiple past events need closure, then it dispatches one job per event', function (): void { + Bus::fake([ProcessEventClosureJob::class]); + + $eventA = makeEventForCommandTest(); + $eventB = makeEventForCommandTest(); + Enrollment::factory()->create([ + 'event_id' => $eventA->id, + 'user_id' => User::factory()->create()->id, + 'status' => EnrollmentStatus::Confirmed, + ]); + Enrollment::factory()->create([ + 'event_id' => $eventB->id, + 'user_id' => User::factory()->create()->id, + 'status' => EnrollmentStatus::CheckedIn, + 'checked_in_at' => now()->subDay(), + ]); + + $this->artisan('events:close-pending'); + + Bus::assertDispatchedTimes(ProcessEventClosureJob::class, 2); +}); diff --git a/app-modules/events/tests/Feature/Closure/OverrideEnrollmentStatusActionTest.php b/app-modules/events/tests/Feature/Closure/OverrideEnrollmentStatusActionTest.php new file mode 100644 index 000000000..f78419b02 --- /dev/null +++ b/app-modules/events/tests/Feature/Closure/OverrideEnrollmentStatusActionTest.php @@ -0,0 +1,145 @@ +create(); + $startsAt = now()->subDays(2)->setTime(9, 0); + + return Event::factory() + ->for($tenant) + ->create([ + 'starts_at' => $startsAt, + 'ends_at' => $startsAt->clone()->setTime(18, 0), + 'status' => EventStatus::Published, + ]); +} + +test('when admin overrides no_show enrollment to attended with reason, then transition is recorded with admin trigger', function (): void { + $event = createPastEvent(); + $organizer = User::factory()->create(); + $enrollment = Enrollment::factory()->create([ + 'event_id' => $event->id, + 'user_id' => User::factory()->create()->id, + 'status' => EnrollmentStatus::NoShow, + 'confirmed_at' => now()->subDay(), + ]); + + $transition = resolve(OverrideEnrollmentStatusAction::class)->handle( + new OverrideEnrollmentStatusDTO( + enrollment: $enrollment, + toStatus: EnrollmentStatus::Attended, + actorId: $organizer->id, + reason: 'Participant was actually present', + ), + ); + + expect($transition->from_status)->toBe(EnrollmentStatus::NoShow) + ->and($transition->to_status)->toBe(EnrollmentStatus::Attended) + ->and($transition->triggered_by)->toBe(TriggeredBy::Admin) + ->and($transition->actor_id)->toBe($organizer->id) + ->and($transition->reason)->toBe('Participant was actually present') + ->and($enrollment->fresh()->status)->toBe(EnrollmentStatus::Attended) + ->and($enrollment->fresh()->attended_at)->not->toBeNull(); +}); + +test('when admin overrides confirmed enrollment to checked_in with reason, then status transitions and timestamp is set', function (): void { + $event = createPastEvent(); + $organizer = User::factory()->create(); + $enrollment = Enrollment::factory()->create([ + 'event_id' => $event->id, + 'user_id' => User::factory()->create()->id, + 'status' => EnrollmentStatus::Confirmed, + 'confirmed_at' => now()->subDay(), + ]); + + resolve(OverrideEnrollmentStatusAction::class)->handle( + new OverrideEnrollmentStatusDTO( + enrollment: $enrollment, + toStatus: EnrollmentStatus::CheckedIn, + actorId: $organizer->id, + reason: 'Late arrival', + ), + ); + + $enrollment->refresh(); + + expect($enrollment->status)->toBe(EnrollmentStatus::CheckedIn) + ->and($enrollment->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->triggered_by)->toBe(TriggeredBy::Admin) + ->and($transition->reason)->toBe('Late arrival'); +}); + +test('when admin tries to override without reason, then reason required exception is thrown', function (): void { + $event = createPastEvent(); + $enrollment = Enrollment::factory()->create([ + 'event_id' => $event->id, + 'user_id' => User::factory()->create()->id, + 'status' => EnrollmentStatus::NoShow, + ]); + + expect(fn (): EnrollmentTransition => resolve(OverrideEnrollmentStatusAction::class)->handle( + new OverrideEnrollmentStatusDTO( + enrollment: $enrollment, + toStatus: EnrollmentStatus::Attended, + actorId: User::factory()->create()->id, + reason: ' ', + ), + ))->toThrow(OverrideEnrollmentStatusException::class); +}); + +test('when admin tries to override from cancelled to attended, then override not allowed exception is thrown', function (): void { + $event = createPastEvent(); + $enrollment = Enrollment::factory()->create([ + 'event_id' => $event->id, + 'user_id' => User::factory()->create()->id, + 'status' => EnrollmentStatus::Cancelled, + ]); + + expect(fn (): EnrollmentTransition => resolve(OverrideEnrollmentStatusAction::class)->handle( + new OverrideEnrollmentStatusDTO( + enrollment: $enrollment, + toStatus: EnrollmentStatus::Attended, + actorId: User::factory()->create()->id, + reason: 'Should not work', + ), + ))->toThrow(OverrideEnrollmentStatusException::class); +}); + +test('when admin tries to override from no_show to confirmed, then override not allowed exception is thrown', function (): void { + $event = createPastEvent(); + $enrollment = Enrollment::factory()->create([ + 'event_id' => $event->id, + 'user_id' => User::factory()->create()->id, + 'status' => EnrollmentStatus::NoShow, + ]); + + expect(fn (): EnrollmentTransition => resolve(OverrideEnrollmentStatusAction::class)->handle( + new OverrideEnrollmentStatusDTO( + enrollment: $enrollment, + toStatus: EnrollmentStatus::Confirmed, + actorId: User::factory()->create()->id, + reason: 'Should not work', + ), + ))->toThrow(OverrideEnrollmentStatusException::class); +}); diff --git a/app-modules/events/tests/Feature/Closure/ProcessEventClosureJobTest.php b/app-modules/events/tests/Feature/Closure/ProcessEventClosureJobTest.php new file mode 100644 index 000000000..32ff3762a --- /dev/null +++ b/app-modules/events/tests/Feature/Closure/ProcessEventClosureJobTest.php @@ -0,0 +1,95 @@ +create(); + $startsAt = now()->subDays(3)->setTime(9, 0); + + return Event::factory() + ->for($tenant) + ->has(EnrollmentPolicy::factory()->state(array_merge([ + 'attendance_requirement' => AttendanceRequirement::AllDays, + 'minimum_days' => null, + ], $policyAttributes)), 'enrollmentPolicy') + ->create(array_merge([ + 'starts_at' => $startsAt, + 'ends_at' => $startsAt->clone()->setTime(18, 0), + 'status' => EventStatus::Published, + ], $eventAttributes)); +} + +test('when job runs for an event with non-terminal enrollments, then it closes them', function (): void { + EventFacade::fake([ParticipantAttended::class]); + + $event = makeEventForJobTest(); + $enrollment = Enrollment::factory()->create([ + 'event_id' => $event->id, + 'user_id' => User::factory()->create()->id, + 'status' => EnrollmentStatus::Confirmed, + 'confirmed_at' => now()->subDay(), + ]); + + new ProcessEventClosureJob($event->id)->handle(resolve(CloseEventAction::class)); + + expect($enrollment->fresh()->status)->toBe(EnrollmentStatus::NoShow); + + $transition = EnrollmentTransition::query() + ->where('enrollment_id', $enrollment->id) + ->first(); + + expect($transition)->not->toBeNull() + ->and($transition->triggered_by)->toBe(TriggeredBy::System); +}); + +test('when job unique id is queried, then it returns the event id', function (): void { + $job = new ProcessEventClosureJob('event-123'); + + expect($job->uniqueId())->toBe('event-123'); +}); + +test('when job runs for a non-existent event id, then it silently returns without throwing', function (): void { + EventFacade::fake([ParticipantAttended::class]); + + new ProcessEventClosureJob(Str::uuid()->toString())->handle(resolve(CloseEventAction::class)); + + EventFacade::assertNotDispatched(ParticipantAttended::class); +}); + +test('when job fails, then it logs the event id and error', function (): void { + Log::spy(); + + $exception = new RuntimeException('db down'); + + new ProcessEventClosureJob('event-xyz')->failed($exception); + + Log::shouldHaveReceived('error')->once()->withArgs(fn (string $message, array $context): bool => $message === 'Event closure failed' + && $context['event_id'] === 'event-xyz' + && $context['error'] === 'db down'); +}); + +test('when job is configured, then it has correct backoff, tries, and unique ttl', function (): void { + $job = new ProcessEventClosureJob('event-1'); + + expect($job->tries)->toBe(4) + ->and($job->backoff)->toBe([1, 5, 10]) + ->and($job->uniqueFor)->toBe(1800); +}); diff --git a/app-modules/events/tests/Feature/Enrollment/EnrollmentPolicyTest.php b/app-modules/events/tests/Feature/Enrollment/EnrollmentPolicyTest.php new file mode 100644 index 000000000..a7ff4be33 --- /dev/null +++ b/app-modules/events/tests/Feature/Enrollment/EnrollmentPolicyTest.php @@ -0,0 +1,142 @@ +create(); + $startsAt = now()->setTime(9, 0); + + return Event::factory() + ->for($tenant) + ->has(EnrollmentPolicy::factory()->state(array_merge([ + 'attendance_requirement' => AttendanceRequirement::AllDays, + 'minimum_days' => null, + ], $policyAttributes)), 'enrollmentPolicy') + ->create(array_merge([ + 'starts_at' => $startsAt, + 'ends_at' => $startsAt->clone()->setTime(18, 0), + 'status' => EventStatus::Published, + ], $eventAttributes)); +} + +test('when checked_in enrollment meets all_days requirement, then resolveAttendance returns Attended', function (): void { + $startsAt = now()->setTime(9, 0); + $event = createEventWithPolicy([ + 'starts_at' => $startsAt, + 'ends_at' => $startsAt->clone()->addDays(2)->setTime(18, 0), + ], [ + 'attendance_requirement' => AttendanceRequirement::AllDays, + ]); + + $enrollment = Enrollment::factory()->create([ + 'event_id' => $event->id, + 'user_id' => User::factory()->create()->id, + 'status' => EnrollmentStatus::CheckedIn, + 'checked_in_at' => now(), + ]); + + 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]); + CheckIn::factory()->create(['enrollment_id' => $enrollment->id, 'event_date' => $startsAt->clone()->addDays(2)->toDateString(), 'method' => CheckInMethod::Manual]); + + expect($event->enrollmentPolicy->resolveAttendance($enrollment))->toBe(EnrollmentStatus::Attended); +}); + +test('when checked_in enrollment is missing days for all_days requirement, then resolveAttendance returns NoShow', function (): void { + $startsAt = now()->setTime(9, 0); + $event = createEventWithPolicy([ + 'starts_at' => $startsAt, + 'ends_at' => $startsAt->clone()->addDays(2)->setTime(18, 0), + ], [ + 'attendance_requirement' => AttendanceRequirement::AllDays, + ]); + + $enrollment = Enrollment::factory()->create([ + 'event_id' => $event->id, + 'user_id' => User::factory()->create()->id, + 'status' => EnrollmentStatus::CheckedIn, + 'checked_in_at' => now(), + ]); + + CheckIn::factory()->create(['enrollment_id' => $enrollment->id, 'event_date' => $startsAt->toDateString(), 'method' => CheckInMethod::Manual]); + + expect($event->enrollmentPolicy->resolveAttendance($enrollment))->toBe(EnrollmentStatus::NoShow); +}); + +test('when checked_in enrollment has at least one check-in and requirement is any_day, then resolveAttendance returns Attended', function (): void { + $startsAt = now()->setTime(9, 0); + $event = createEventWithPolicy([ + 'starts_at' => $startsAt, + 'ends_at' => $startsAt->clone()->addDays(2)->setTime(18, 0), + ], [ + 'attendance_requirement' => AttendanceRequirement::AnyDay, + ]); + + $enrollment = Enrollment::factory()->create([ + 'event_id' => $event->id, + 'user_id' => User::factory()->create()->id, + 'status' => EnrollmentStatus::CheckedIn, + 'checked_in_at' => now(), + ]); + + CheckIn::factory()->create(['enrollment_id' => $enrollment->id, 'event_date' => $startsAt->toDateString(), 'method' => CheckInMethod::Manual]); + + expect($event->enrollmentPolicy->resolveAttendance($enrollment))->toBe(EnrollmentStatus::Attended); +}); + +test('when checked_in enrollment meets minimum_days requirement, then resolveAttendance returns Attended', function (): void { + $startsAt = now()->setTime(9, 0); + $event = createEventWithPolicy([ + 'starts_at' => $startsAt, + 'ends_at' => $startsAt->clone()->addDays(2)->setTime(18, 0), + ], [ + 'attendance_requirement' => AttendanceRequirement::MinimumDays, + 'minimum_days' => 2, + ]); + + $enrollment = Enrollment::factory()->create([ + 'event_id' => $event->id, + 'user_id' => User::factory()->create()->id, + 'status' => EnrollmentStatus::CheckedIn, + 'checked_in_at' => now(), + ]); + + 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]); + + expect($event->enrollmentPolicy->resolveAttendance($enrollment))->toBe(EnrollmentStatus::Attended); +}); + +test('when checked_in enrollment is below minimum_days requirement, then resolveAttendance returns NoShow', function (): void { + $startsAt = now()->setTime(9, 0); + $event = createEventWithPolicy([ + 'starts_at' => $startsAt, + 'ends_at' => $startsAt->clone()->addDays(2)->setTime(18, 0), + ], [ + 'attendance_requirement' => AttendanceRequirement::MinimumDays, + 'minimum_days' => 2, + ]); + + $enrollment = Enrollment::factory()->create([ + 'event_id' => $event->id, + 'user_id' => User::factory()->create()->id, + 'status' => EnrollmentStatus::CheckedIn, + 'checked_in_at' => now(), + ]); + + CheckIn::factory()->create(['enrollment_id' => $enrollment->id, 'event_date' => $startsAt->toDateString(), 'method' => CheckInMethod::Manual]); + + expect($event->enrollmentPolicy->resolveAttendance($enrollment))->toBe(EnrollmentStatus::NoShow); +}); From 601efccad4d428fb6b4244550e2f3bc1e6b4e09a Mon Sep 17 00:00:00 2001 From: Davi Castello Branco Tavares de Oliveira Date: Thu, 4 Jun 2026 20:45:27 -0400 Subject: [PATCH 15/24] chore(deps): update package-lock.json metadata --- package-lock.json | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/package-lock.json b/package-lock.json index 710f058a1..9c0973c6a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -36,7 +36,6 @@ "integrity": "sha512-yq6OkJ4p82CAfPl0u9mQebQHKPJkY7WrIuk205cTYnYe+k2Z8YBh11FrbRG/H6ihirqcacOgl2BIO8oyMQLeXw==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@emnapi/wasi-threads": "1.2.1", "tslib": "^2.4.0" @@ -48,7 +47,6 @@ "integrity": "sha512-ewvYlk86xUoGI0zQRNq/mC+16R1QeDlKQy21Ki3oSYXNgLb45GV1P6A0M+/s6nyCuNDqe5VpaY84BzXGwVbwFA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "tslib": "^2.4.0" } @@ -162,7 +160,6 @@ "integrity": "sha512-x9l65fCE/pgoET6RQowgdgG8Xmzs44z6j6Hhg3coINCyCw9JBGJ5ZzMR2XHAM2jmAdbJAIgqB6cUn4/3W3XLTA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "linguist-languages": "^8.0.0", "php-parser": "^3.2.5" @@ -1644,7 +1641,6 @@ "integrity": "sha512-7igPTM53cGHMW8xWuVTydi2KO233VFiTNyF5hLJqpilHfmn8C8gPf+PS7dUT64YcXFbiMGZxS9pCSxL/Dxm/Jw==", "dev": true, "license": "MIT", - "peer": true, "bin": { "prettier": "bin/prettier.cjs" }, @@ -1689,7 +1685,6 @@ "integrity": "sha512-UKii4RjY05SNt/WQi6/NcOn/LsT0/ILLXsxygjbRg5/YZelsSu5jTqorYHPDGq4nZy5q5hpCu+XdGZ1xaJEQgw==", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=20.19" }, @@ -1945,8 +1940,7 @@ "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-4.3.0.tgz", "integrity": "sha512-y6nxMGB1nMW9R6k96e5gdIFzcfL/gTJRNaqGes1YvkLnPVXzWgbqFF2yLC0T8G774n24cx3Pe8XrKoniCOAH+Q==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/tapable": { "version": "2.3.3", @@ -2029,7 +2023,6 @@ "integrity": "sha512-h9bXPmJichP5fLmVQo3PyaGSDE2n3aPuomeAlVRm0JLmt4rY6zmPKd59HYI4LNW8oTK7tlTsuC7l/m7awx9Jcw==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "lightningcss": "^1.32.0", "picomatch": "^4.0.4", From 2e5f05fbf48d7c6c72b66ae92f09c9c6443bc696 Mon Sep 17 00:00:00 2001 From: Davi Castello Branco Tavares de Oliveira Date: Thu, 4 Jun 2026 20:54:56 -0400 Subject: [PATCH 16/24] test(events): read job config from PHP 8 attributes via reflection Avoids duplicating tries/backoff/uniqueFor as both attributes and properties. Keeps attributes as single source of truth, consistent with ScreenContent and ClassifyAndRoute jobs. --- .../Closure/ProcessEventClosureJobTest.php | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/app-modules/events/tests/Feature/Closure/ProcessEventClosureJobTest.php b/app-modules/events/tests/Feature/Closure/ProcessEventClosureJobTest.php index 32ff3762a..7eb8e8242 100644 --- a/app-modules/events/tests/Feature/Closure/ProcessEventClosureJobTest.php +++ b/app-modules/events/tests/Feature/Closure/ProcessEventClosureJobTest.php @@ -15,6 +15,9 @@ use He4rt\Events\Event\Models\Event; use He4rt\Identity\Tenant\Models\Tenant; use He4rt\Identity\User\Models\User; +use Illuminate\Queue\Attributes\Backoff; +use Illuminate\Queue\Attributes\Tries; +use Illuminate\Queue\Attributes\UniqueFor; use Illuminate\Support\Facades\Event as EventFacade; use Illuminate\Support\Facades\Log; use Illuminate\Support\Str; @@ -87,9 +90,13 @@ function makeEventForJobTest(array $eventAttributes = [], array $policyAttribute }); test('when job is configured, then it has correct backoff, tries, and unique ttl', function (): void { - $job = new ProcessEventClosureJob('event-1'); + $ref = new ReflectionClass(ProcessEventClosureJob::class); - expect($job->tries)->toBe(4) - ->and($job->backoff)->toBe([1, 5, 10]) - ->and($job->uniqueFor)->toBe(1800); + $tries = $ref->getAttributes(Tries::class)[0]->newInstance()->tries; + $backoff = $ref->getAttributes(Backoff::class)[0]->newInstance()->backoff; + $uniqueFor = $ref->getAttributes(UniqueFor::class)[0]->newInstance()->uniqueFor; + + expect($tries)->toBe(4) + ->and($backoff)->toBe([1, 5, 10]) + ->and($uniqueFor)->toBe(1800); }); From 4000f2ee547fc8d6459076b786138127c7415d20 Mon Sep 17 00:00:00 2001 From: Davi Castello Branco Tavares de Oliveira Date: Thu, 4 Jun 2026 22:21:50 -0400 Subject: [PATCH 17/24] refactor(events): expose override allowlist as queryable method Collapses duplicated knowledge: the Filament UI was independently reimplementing the allowed override transitions that OverrideEnrollmentStatusAction already owns. New allowedTargetsFor() method is the single source of truth consumed by both the Action's validation and the UI's visibility/options. --- .../OverrideEnrollmentStatusAction.php | 9 +++++++++ .../OverrideEnrollmentStatusActionTest.php | 19 +++++++++++++++++++ .../EnrollmentsRelationManager.php | 10 ++++------ 3 files changed, 32 insertions(+), 6 deletions(-) diff --git a/app-modules/events/src/Closure/Actions/OverrideEnrollmentStatusAction.php b/app-modules/events/src/Closure/Actions/OverrideEnrollmentStatusAction.php index 578b15d73..3ff347782 100644 --- a/app-modules/events/src/Closure/Actions/OverrideEnrollmentStatusAction.php +++ b/app-modules/events/src/Closure/Actions/OverrideEnrollmentStatusAction.php @@ -19,6 +19,15 @@ ['from' => EnrollmentStatus::Confirmed, 'to' => EnrollmentStatus::CheckedIn], ]; + /** @return list */ + public static function allowedTargetsFor(EnrollmentStatus $from): array + { + return array_values(array_map( + static fn (array $pair): EnrollmentStatus => $pair['to'], + array_filter(self::ALLOWED_OVERRIDES, static fn (array $pair): bool => $pair['from'] === $from), + )); + } + /** * @throws OverrideEnrollmentStatusException * @throws Throwable diff --git a/app-modules/events/tests/Feature/Closure/OverrideEnrollmentStatusActionTest.php b/app-modules/events/tests/Feature/Closure/OverrideEnrollmentStatusActionTest.php index f78419b02..22b91c44e 100644 --- a/app-modules/events/tests/Feature/Closure/OverrideEnrollmentStatusActionTest.php +++ b/app-modules/events/tests/Feature/Closure/OverrideEnrollmentStatusActionTest.php @@ -126,6 +126,25 @@ function createPastEvent(): Event ))->toThrow(OverrideEnrollmentStatusException::class); }); +test('when allowedTargetsFor is queried for NoShow, then it returns only Attended', function (): void { + $targets = OverrideEnrollmentStatusAction::allowedTargetsFor(EnrollmentStatus::NoShow); + + expect($targets)->toBe([EnrollmentStatus::Attended]); +}); + +test('when allowedTargetsFor is queried for Confirmed, then it returns only CheckedIn', function (): void { + $targets = OverrideEnrollmentStatusAction::allowedTargetsFor(EnrollmentStatus::Confirmed); + + expect($targets)->toBe([EnrollmentStatus::CheckedIn]); +}); + +test('when allowedTargetsFor is queried for a terminal or unrelated status, then it returns an empty array', function (): void { + expect(OverrideEnrollmentStatusAction::allowedTargetsFor(EnrollmentStatus::Attended))->toBeEmpty() + ->and(OverrideEnrollmentStatusAction::allowedTargetsFor(EnrollmentStatus::Cancelled))->toBeEmpty() + ->and(OverrideEnrollmentStatusAction::allowedTargetsFor(EnrollmentStatus::Rejected))->toBeEmpty() + ->and(OverrideEnrollmentStatusAction::allowedTargetsFor(EnrollmentStatus::NoShow))->not->toBeEmpty(); +}); + test('when admin tries to override from no_show to confirmed, then override not allowed exception is thrown', function (): void { $event = createPastEvent(); $enrollment = Enrollment::factory()->create([ 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 e57cba159..4815268d9 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 @@ -179,15 +179,13 @@ private function overrideStatusAction(): Action ->label('Override Status') ->icon(Heroicon::OutlinedPencilSquare) ->color('warning') - ->visible(fn (Enrollment $record): bool => in_array($record->status, [EnrollmentStatus::NoShow, EnrollmentStatus::Confirmed], strict: true)) + ->visible(fn (Enrollment $record): bool => OverrideEnrollmentStatusAction::allowedTargetsFor($record->status) !== []) ->schema([ Select::make('to_status') ->label('New Status') - ->options(fn (Enrollment $record): array => match ($record->status) { - EnrollmentStatus::NoShow => [EnrollmentStatus::Attended->value => 'Attended'], - EnrollmentStatus::Confirmed => [EnrollmentStatus::CheckedIn->value => 'Checked In'], - default => [], - }) + ->options(fn (Enrollment $record): array => collect(OverrideEnrollmentStatusAction::allowedTargetsFor($record->status)) + ->mapWithKeys(fn (EnrollmentStatus $s): array => [$s->value => $s->getLabel()]) + ->all()) ->required(), Textarea::make('reason') ->label('Reason') From 06703c7b10e557af175ba0364259713794305588 Mon Sep 17 00:00:00 2001 From: Davi Castello Branco Tavares de Oliveira Date: Thu, 4 Jun 2026 22:33:16 -0400 Subject: [PATCH 18/24] chore(events): remove unused getIcon() from EnrollmentStatus enum --- .../src/Enrollment/Enums/EnrollmentStatus.php | 18 +----------------- 1 file changed, 1 insertion(+), 17 deletions(-) diff --git a/app-modules/events/src/Enrollment/Enums/EnrollmentStatus.php b/app-modules/events/src/Enrollment/Enums/EnrollmentStatus.php index 91026cbc0..d42f75dcd 100644 --- a/app-modules/events/src/Enrollment/Enums/EnrollmentStatus.php +++ b/app-modules/events/src/Enrollment/Enums/EnrollmentStatus.php @@ -6,12 +6,10 @@ use Filament\Support\Colors\Color; use Filament\Support\Contracts\HasColor; -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 +enum EnrollmentStatus: string implements HasColor, HasLabel { case Pending = 'pending'; case Confirmed = 'confirmed'; @@ -41,20 +39,6 @@ public function getColor(): array }; } - public function getIcon(): Heroicon - { - return match ($this) { - self::Pending => Heroicon::Clock, - self::Confirmed => Heroicon::CheckCircle, - self::Waitlisted => Heroicon::OutlinedQueueList, - self::CheckedIn => Heroicon::Flag, - self::Attended => Heroicon::Bolt, - self::Cancelled => Heroicon::XCircle, - self::Rejected => Heroicon::NoSymbol, - self::NoShow => Heroicon::ExclamationCircle, - }; - } - public function canTransitionTo(self $target): bool { return match ($this) { From 62ea0af50a24adee2dbd53e6f9b800fefe4de51b Mon Sep 17 00:00:00 2001 From: Davi Castello Branco Tavares de Oliveira Date: Thu, 4 Jun 2026 23:21:25 -0400 Subject: [PATCH 19/24] fix(events): close all enrollments across chunks --- .../src/Closure/Actions/CloseEventAction.php | 2 +- .../Feature/Closure/CloseEventActionTest.php | 30 +++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/app-modules/events/src/Closure/Actions/CloseEventAction.php b/app-modules/events/src/Closure/Actions/CloseEventAction.php index 1108aaf30..ed104df33 100644 --- a/app-modules/events/src/Closure/Actions/CloseEventAction.php +++ b/app-modules/events/src/Closure/Actions/CloseEventAction.php @@ -22,7 +22,7 @@ public function handle(Event $event): int $event->enrollments() ->whereIn('status', [EnrollmentStatus::Confirmed, EnrollmentStatus::CheckedIn]) - ->each(function (Enrollment $enrollment) use (&$attendances): void { + ->eachById(function (Enrollment $enrollment) use (&$attendances): void { $attendances += $this->closeOne($enrollment); }); diff --git a/app-modules/events/tests/Feature/Closure/CloseEventActionTest.php b/app-modules/events/tests/Feature/Closure/CloseEventActionTest.php index d8f1781cc..61aa2f298 100644 --- a/app-modules/events/tests/Feature/Closure/CloseEventActionTest.php +++ b/app-modules/events/tests/Feature/Closure/CloseEventActionTest.php @@ -16,6 +16,7 @@ use He4rt\Events\Event\Models\Event; use He4rt\Identity\Tenant\Models\Tenant; use He4rt\Identity\User\Models\User; +use Illuminate\Contracts\Database\Query\Builder; use Illuminate\Support\Facades\Event as EventFacade; function createEventForClosure(array $eventAttributes = [], array $policyAttributes = []): Event @@ -215,3 +216,32 @@ function createEventForClosure(array $eventAttributes = [], array $policyAttribu ->and($transition->triggered_by)->toBe(TriggeredBy::System); } }); + +test('when action processes more than one chunk of eligible enrollments, then all are closed in one run', function (): void { + EventFacade::fake([ParticipantAttended::class]); + + $event = createEventForClosure(); + + Enrollment::factory() + ->count(1001) + ->create([ + 'event_id' => $event->id, + 'status' => EnrollmentStatus::Confirmed, + 'confirmed_at' => now()->subDay(), + ]); + + resolve(CloseEventAction::class)->handle($event); + + $remainingEligible = Enrollment::query() + ->where('event_id', $event->id) + ->whereIn('status', [EnrollmentStatus::Confirmed, EnrollmentStatus::CheckedIn]) + ->count(); + + $noShowTransitions = EnrollmentTransition::query() + ->whereHas('enrollment', fn (Builder $query) => $query->where('event_id', $event->id)) + ->where('to_status', EnrollmentStatus::NoShow) + ->count(); + + expect($remainingEligible)->toBe(0) + ->and($noShowTransitions)->toBe(1001); +}); From b0e18d19003c8eb3fc1328d8316d74ca4e3c77f6 Mon Sep 17 00:00:00 2001 From: Davi Castello Branco Tavares de Oliveira Date: Thu, 4 Jun 2026 23:23:22 -0400 Subject: [PATCH 20/24] fix(events): enforce current status on overrides --- .../OverrideEnrollmentStatusAction.php | 22 ++++++++----- .../OverrideEnrollmentStatusActionTest.php | 31 +++++++++++++++++++ 2 files changed, 45 insertions(+), 8 deletions(-) diff --git a/app-modules/events/src/Closure/Actions/OverrideEnrollmentStatusAction.php b/app-modules/events/src/Closure/Actions/OverrideEnrollmentStatusAction.php index 3ff347782..6c18f22d9 100644 --- a/app-modules/events/src/Closure/Actions/OverrideEnrollmentStatusAction.php +++ b/app-modules/events/src/Closure/Actions/OverrideEnrollmentStatusAction.php @@ -8,6 +8,7 @@ use He4rt\Events\Closure\Exceptions\OverrideEnrollmentStatusException; use He4rt\Events\Enrollment\Enums\EnrollmentStatus; use He4rt\Events\Enrollment\Enums\TriggeredBy; +use He4rt\Events\Enrollment\Models\Enrollment; use He4rt\Events\Enrollment\Models\EnrollmentTransition; use Illuminate\Support\Facades\DB; use Throwable; @@ -38,24 +39,29 @@ public function handle(OverrideEnrollmentStatusDTO $dto): EnrollmentTransition throw OverrideEnrollmentStatusException::reasonRequired(); } - $fromStatus = $dto->enrollment->status; + return DB::transaction(function () use ($dto): EnrollmentTransition { + $enrollment = Enrollment::query() + ->whereKey($dto->enrollment->id) + ->lockForUpdate() + ->firstOrFail(); - throw_unless( - $this->isAllowed($fromStatus, $dto->toStatus), - OverrideEnrollmentStatusException::overrideNotAllowed($fromStatus, $dto->toStatus), - ); + $fromStatus = $enrollment->status; + + throw_unless( + $this->isAllowed($fromStatus, $dto->toStatus), + OverrideEnrollmentStatusException::overrideNotAllowed($fromStatus, $dto->toStatus), + ); - return DB::transaction(static function () use ($dto, $fromStatus): EnrollmentTransition { $attributes = ['status' => $dto->toStatus]; if ($timestampColumn = $dto->toStatus->timestampColumn()) { $attributes[$timestampColumn] = now(); } - $dto->enrollment->update($attributes); + $enrollment->update($attributes); return EnrollmentTransition::query()->create([ - 'enrollment_id' => $dto->enrollment->id, + 'enrollment_id' => $enrollment->id, 'from_status' => $fromStatus, 'to_status' => $dto->toStatus, 'actor_id' => $dto->actorId, diff --git a/app-modules/events/tests/Feature/Closure/OverrideEnrollmentStatusActionTest.php b/app-modules/events/tests/Feature/Closure/OverrideEnrollmentStatusActionTest.php index 22b91c44e..3ab7031a9 100644 --- a/app-modules/events/tests/Feature/Closure/OverrideEnrollmentStatusActionTest.php +++ b/app-modules/events/tests/Feature/Closure/OverrideEnrollmentStatusActionTest.php @@ -5,6 +5,8 @@ use He4rt\Events\Closure\Actions\OverrideEnrollmentStatusAction; use He4rt\Events\Closure\DTOs\OverrideEnrollmentStatusDTO; use He4rt\Events\Closure\Exceptions\OverrideEnrollmentStatusException; +use He4rt\Events\Enrollment\Actions\TransitionEnrollmentAction; +use He4rt\Events\Enrollment\DTOs\TransitionEnrollmentDTO; use He4rt\Events\Enrollment\Enums\EnrollmentStatus; use He4rt\Events\Enrollment\Enums\TriggeredBy; use He4rt\Events\Enrollment\Models\Enrollment; @@ -162,3 +164,32 @@ function createPastEvent(): Event ), ))->toThrow(OverrideEnrollmentStatusException::class); }); + +test('when admin overrides a stale confirmed enrollment that is already no_show, then current status is enforced', function (): void { + $event = createPastEvent(); + $enrollment = Enrollment::factory()->create([ + 'event_id' => $event->id, + 'user_id' => User::factory()->create()->id, + 'status' => EnrollmentStatus::Confirmed, + 'confirmed_at' => now()->subDay(), + ]); + + resolve(TransitionEnrollmentAction::class)->handle( + new TransitionEnrollmentDTO( + enrollment: $enrollment->fresh(), + toStatus: EnrollmentStatus::NoShow, + triggeredBy: TriggeredBy::System, + ), + ); + + expect(fn (): EnrollmentTransition => resolve(OverrideEnrollmentStatusAction::class)->handle( + new OverrideEnrollmentStatusDTO( + enrollment: $enrollment, + toStatus: EnrollmentStatus::CheckedIn, + actorId: User::factory()->create()->id, + reason: 'Late arrival', + ), + ))->toThrow(OverrideEnrollmentStatusException::class); + + expect($enrollment->fresh()->status)->toBe(EnrollmentStatus::NoShow); +}); From 5ca451aa59055ba6a39d8ca7647464f5037f7243 Mon Sep 17 00:00:00 2001 From: Davi Castello Branco Tavares de Oliveira Date: Fri, 5 Jun 2026 00:23:27 -0400 Subject: [PATCH 21/24] fix(events): read parent dates for attendance policy --- .../tests/Feature/EventResourceTest.php | 42 +++++++++++++++++-- .../Resources/Events/Schemas/EventForm.php | 19 +++++---- 2 files changed, 49 insertions(+), 12 deletions(-) diff --git a/app-modules/events/tests/Feature/EventResourceTest.php b/app-modules/events/tests/Feature/EventResourceTest.php index 229254d9d..f787d8e62 100644 --- a/app-modules/events/tests/Feature/EventResourceTest.php +++ b/app-modules/events/tests/Feature/EventResourceTest.php @@ -3,6 +3,8 @@ declare(strict_types=1); use Filament\Facades\Filament; +use Filament\Forms\Components\Select; +use Filament\Forms\Components\TextInput; use He4rt\Events\CheckIn\Enums\CheckInMethod; use He4rt\Events\CheckIn\Models\CheckIn; use He4rt\Events\CheckIn\Models\CheckInCode; @@ -80,7 +82,7 @@ 'enrollmentPolicy' => [ 'enrollment_method' => EnrollmentMethod::Rsvp, 'check_in_method' => CheckInMethod::Manual, - 'attendance_requirement' => AttendanceRequirement::AllDays, + 'attendance_requirement' => AttendanceRequirement::AnyDay, 'xp_on_confirmed' => 0, 'xp_on_checked_in' => 0, 'xp_on_attended' => 0, @@ -96,6 +98,37 @@ ->and($event->enrollmentPolicy->enrollment_method)->toBe(EnrollmentMethod::Rsvp); }); +test('when creating a same-day event, then attendance requirement options only allow any day', function (): void { + $startsAt = now()->addDay()->setTime(9, 0); + + livewire(CreateEvent::class) + ->fillForm([ + 'starts_at' => $startsAt, + 'ends_at' => $startsAt->clone()->setTime(18, 0), + ]) + ->assertFormFieldExists( + 'enrollmentPolicy.attendance_requirement', + fn (Select $field): bool => array_keys($field->getOptions()) === [AttendanceRequirement::AnyDay->value], + ); +}); + +test('when creating a multi-day event, then minimum days cannot exceed event days', function (): void { + $startsAt = now()->addDay()->setTime(9, 0); + + livewire(CreateEvent::class) + ->fillForm([ + 'starts_at' => $startsAt, + 'ends_at' => $startsAt->clone()->addDays(2)->setTime(18, 0), + 'enrollmentPolicy' => [ + 'attendance_requirement' => AttendanceRequirement::MinimumDays, + ], + ]) + ->assertFormFieldExists( + 'enrollmentPolicy.minimum_days', + fn (TextInput $field): bool => $field->getMaxValue() === 3, + ); +}); + test('when submitting the create form with a duplicate slug for the same tenant, then validation fails', function (): void { $tenant = Filament::getTenant(); $startsAt = now()->addDay(); @@ -113,7 +146,7 @@ 'enrollmentPolicy' => [ 'enrollment_method' => EnrollmentMethod::Rsvp, 'check_in_method' => CheckInMethod::Manual, - 'attendance_requirement' => AttendanceRequirement::AllDays, + 'attendance_requirement' => AttendanceRequirement::AnyDay, 'xp_on_confirmed' => 0, 'xp_on_checked_in' => 0, 'xp_on_attended' => 0, @@ -125,7 +158,10 @@ test('when submitting the edit form with a new title, then it is updated in the database', function (): void { $event = Event::factory() - ->has(EnrollmentPolicy::factory(), 'enrollmentPolicy') + ->has(EnrollmentPolicy::factory()->state([ + 'attendance_requirement' => AttendanceRequirement::AnyDay, + 'minimum_days' => null, + ]), 'enrollmentPolicy') ->create(['title' => 'Old Title']); livewire(EditEvent::class, ['record' => $event->getRouteKey()]) diff --git a/app-modules/panel-admin/src/Filament/Resources/Events/Schemas/EventForm.php b/app-modules/panel-admin/src/Filament/Resources/Events/Schemas/EventForm.php index b52554a08..c55277a3f 100644 --- a/app-modules/panel-admin/src/Filament/Resources/Events/Schemas/EventForm.php +++ b/app-modules/panel-admin/src/Filament/Resources/Events/Schemas/EventForm.php @@ -175,17 +175,13 @@ private static function attendanceRequirementOptions(Get $get): array AttendanceRequirement::MinimumDays->value => __('events::enums.attendance_requirement.minimum_days'), ]; - $startsAt = $get('starts_at'); - $endsAt = $get('ends_at'); + $eventDays = self::eventDays($get); - if ($startsAt === null || $endsAt === null) { + if ($eventDays === null) { return $all; } - $startsDay = Date::parse($startsAt)->startOfDay(); - $endsDay = Date::parse($endsAt)->startOfDay(); - - if ($startsDay->equalTo($endsDay)) { + if ($eventDays === 1) { return [AttendanceRequirement::AnyDay->value => $all[AttendanceRequirement::AnyDay->value]]; } @@ -194,8 +190,13 @@ private static function attendanceRequirementOptions(Get $get): array private static function minimumDaysMaxValue(Get $get): ?int { - $startsAt = $get('starts_at'); - $endsAt = $get('ends_at'); + return self::eventDays($get); + } + + private static function eventDays(Get $get): ?int + { + $startsAt = $get('../starts_at'); + $endsAt = $get('../ends_at'); if ($startsAt === null || $endsAt === null) { return null; From 285d54159f9b858fefa239a0e0f95ab8651b7eae Mon Sep 17 00:00:00 2001 From: Davi Castello Branco Tavares de Oliveira Date: Sat, 6 Jun 2026 15:29:29 -0400 Subject: [PATCH 22/24] feat(events): handle stale enrollment overrides --- .../0008-admin-status-override-as-separate-action.md | 11 ++++++++++- app-modules/events/lang/en/exceptions.php | 1 + app-modules/events/lang/pt_BR/exceptions.php | 1 + .../Actions/OverrideEnrollmentStatusAction.php | 9 +++++---- .../src/Closure/DTOs/OverrideEnrollmentStatusDTO.php | 8 +++++++- .../Exceptions/OverrideEnrollmentStatusException.php | 11 +++++++++++ .../Closure/OverrideEnrollmentStatusActionTest.php | 10 +++++++++- .../RelationManagers/EnrollmentsRelationManager.php | 1 + 8 files changed, 45 insertions(+), 7 deletions(-) diff --git a/app-modules/events/docs/adr/0008-admin-status-override-as-separate-action.md b/app-modules/events/docs/adr/0008-admin-status-override-as-separate-action.md index 9e52805fb..6cac059c3 100644 --- a/app-modules/events/docs/adr/0008-admin-status-override-as-separate-action.md +++ b/app-modules/events/docs/adr/0008-admin-status-override-as-separate-action.md @@ -32,7 +32,16 @@ Any other pair — including `attended → no_show`, `cancelled → attended`, o ### Reason is required and recorded -`OverrideEnrollmentStatusDTO` takes a non-empty `reason` string. The Action throws `OverrideEnrollmentStatusException::reasonRequired()` on empty input. The reason is written to `EnrollmentTransition::$reason` for accountability, alongside `triggered_by = admin` and `actor_id = $organizer->id`. +`OverrideEnrollmentStatusDTO` takes a non-empty `reason` string and rejects empty input with `OverrideEnrollmentStatusException::reasonRequired()`. The reason is written to `EnrollmentTransition::$reason` for accountability, alongside `triggered_by = admin` and `actor_id = $organizer->id`. + +### Stale status is a conflict, not a generic invalid override + +The DTO carries the enrollment status observed by the admin UI. The Action still re-loads the enrollment inside a transaction with a row lock before applying the correction. If the current status no longer matches the observed status, it throws `OverrideEnrollmentStatusException::statusChanged(expected, actual)` instead of `overrideNotAllowed(from, to)`. + +This separates two cases: + +- `overrideNotAllowed` — the requested pair is not part of the correction allowlist. +- `statusChanged` — the requested pair may have been valid when the admin opened the modal, but another process changed the enrollment before save. ### Override does not re-dispatch domain events diff --git a/app-modules/events/lang/en/exceptions.php b/app-modules/events/lang/en/exceptions.php index 8305ba864..116dd963b 100644 --- a/app-modules/events/lang/en/exceptions.php +++ b/app-modules/events/lang/en/exceptions.php @@ -12,4 +12,5 @@ 'response_message_not_implemented' => 'Response message is not implemented for enrollment status: :status.', 'override_reason_required' => 'A reason is required when overriding an enrollment status.', 'override_not_allowed' => 'Override from :from to :to is not allowed.', + 'override_status_changed' => 'Enrollment status changed from :expected to :actual before the override was saved. Review the current status and try again.', ]; diff --git a/app-modules/events/lang/pt_BR/exceptions.php b/app-modules/events/lang/pt_BR/exceptions.php index 86b5e6147..f2a6eaefc 100644 --- a/app-modules/events/lang/pt_BR/exceptions.php +++ b/app-modules/events/lang/pt_BR/exceptions.php @@ -12,4 +12,5 @@ 'response_message_not_implemented' => 'Mensagem de resposta não implementada para o status de inscrição: :status.', 'override_reason_required' => 'É obrigatório informar um motivo ao sobrescrever o status de uma inscrição.', 'override_not_allowed' => 'Sobrescrita de :from para :to não é permitida.', + 'override_status_changed' => 'O status da inscrição mudou de :expected para :actual antes da sobrescrita ser salva. Revise o status atual e tente novamente.', ]; diff --git a/app-modules/events/src/Closure/Actions/OverrideEnrollmentStatusAction.php b/app-modules/events/src/Closure/Actions/OverrideEnrollmentStatusAction.php index 6c18f22d9..240d90ea9 100644 --- a/app-modules/events/src/Closure/Actions/OverrideEnrollmentStatusAction.php +++ b/app-modules/events/src/Closure/Actions/OverrideEnrollmentStatusAction.php @@ -35,10 +35,6 @@ public static function allowedTargetsFor(EnrollmentStatus $from): array */ public function handle(OverrideEnrollmentStatusDTO $dto): EnrollmentTransition { - if (mb_trim($dto->reason) === '') { - throw OverrideEnrollmentStatusException::reasonRequired(); - } - return DB::transaction(function () use ($dto): EnrollmentTransition { $enrollment = Enrollment::query() ->whereKey($dto->enrollment->id) @@ -47,6 +43,11 @@ public function handle(OverrideEnrollmentStatusDTO $dto): EnrollmentTransition $fromStatus = $enrollment->status; + throw_unless( + $fromStatus === $dto->fromStatus, + OverrideEnrollmentStatusException::statusChanged($dto->fromStatus, $fromStatus), + ); + throw_unless( $this->isAllowed($fromStatus, $dto->toStatus), OverrideEnrollmentStatusException::overrideNotAllowed($fromStatus, $dto->toStatus), diff --git a/app-modules/events/src/Closure/DTOs/OverrideEnrollmentStatusDTO.php b/app-modules/events/src/Closure/DTOs/OverrideEnrollmentStatusDTO.php index f3404c045..cddeaccd8 100644 --- a/app-modules/events/src/Closure/DTOs/OverrideEnrollmentStatusDTO.php +++ b/app-modules/events/src/Closure/DTOs/OverrideEnrollmentStatusDTO.php @@ -4,6 +4,7 @@ namespace He4rt\Events\Closure\DTOs; +use He4rt\Events\Closure\Exceptions\OverrideEnrollmentStatusException; use He4rt\Events\Enrollment\Enums\EnrollmentStatus; use He4rt\Events\Enrollment\Models\Enrollment; @@ -11,8 +12,13 @@ { public function __construct( public Enrollment $enrollment, + public EnrollmentStatus $fromStatus, public EnrollmentStatus $toStatus, public string $actorId, public string $reason, - ) {} + ) { + if (mb_trim($this->reason) === '') { + throw OverrideEnrollmentStatusException::reasonRequired(); + } + } } diff --git a/app-modules/events/src/Closure/Exceptions/OverrideEnrollmentStatusException.php b/app-modules/events/src/Closure/Exceptions/OverrideEnrollmentStatusException.php index 1a47fd6b7..764118bc8 100644 --- a/app-modules/events/src/Closure/Exceptions/OverrideEnrollmentStatusException.php +++ b/app-modules/events/src/Closure/Exceptions/OverrideEnrollmentStatusException.php @@ -25,4 +25,15 @@ public static function overrideNotAllowed(EnrollmentStatus $from, EnrollmentStat Response::HTTP_UNPROCESSABLE_ENTITY, ); } + + public static function statusChanged(EnrollmentStatus $expected, EnrollmentStatus $actual): self + { + return new self( + __('events::exceptions.override_status_changed', [ + 'expected' => $expected->value, + 'actual' => $actual->value, + ]), + Response::HTTP_CONFLICT, + ); + } } diff --git a/app-modules/events/tests/Feature/Closure/OverrideEnrollmentStatusActionTest.php b/app-modules/events/tests/Feature/Closure/OverrideEnrollmentStatusActionTest.php index 3ab7031a9..aac3fec0e 100644 --- a/app-modules/events/tests/Feature/Closure/OverrideEnrollmentStatusActionTest.php +++ b/app-modules/events/tests/Feature/Closure/OverrideEnrollmentStatusActionTest.php @@ -43,6 +43,7 @@ function createPastEvent(): Event $transition = resolve(OverrideEnrollmentStatusAction::class)->handle( new OverrideEnrollmentStatusDTO( enrollment: $enrollment, + fromStatus: EnrollmentStatus::NoShow, toStatus: EnrollmentStatus::Attended, actorId: $organizer->id, reason: 'Participant was actually present', @@ -71,6 +72,7 @@ function createPastEvent(): Event resolve(OverrideEnrollmentStatusAction::class)->handle( new OverrideEnrollmentStatusDTO( enrollment: $enrollment, + fromStatus: EnrollmentStatus::Confirmed, toStatus: EnrollmentStatus::CheckedIn, actorId: $organizer->id, reason: 'Late arrival', @@ -103,6 +105,7 @@ function createPastEvent(): Event expect(fn (): EnrollmentTransition => resolve(OverrideEnrollmentStatusAction::class)->handle( new OverrideEnrollmentStatusDTO( enrollment: $enrollment, + fromStatus: EnrollmentStatus::NoShow, toStatus: EnrollmentStatus::Attended, actorId: User::factory()->create()->id, reason: ' ', @@ -121,6 +124,7 @@ function createPastEvent(): Event expect(fn (): EnrollmentTransition => resolve(OverrideEnrollmentStatusAction::class)->handle( new OverrideEnrollmentStatusDTO( enrollment: $enrollment, + fromStatus: EnrollmentStatus::Cancelled, toStatus: EnrollmentStatus::Attended, actorId: User::factory()->create()->id, reason: 'Should not work', @@ -158,6 +162,7 @@ function createPastEvent(): Event expect(fn (): EnrollmentTransition => resolve(OverrideEnrollmentStatusAction::class)->handle( new OverrideEnrollmentStatusDTO( enrollment: $enrollment, + fromStatus: EnrollmentStatus::NoShow, toStatus: EnrollmentStatus::Confirmed, actorId: User::factory()->create()->id, reason: 'Should not work', @@ -185,11 +190,14 @@ function createPastEvent(): Event expect(fn (): EnrollmentTransition => resolve(OverrideEnrollmentStatusAction::class)->handle( new OverrideEnrollmentStatusDTO( enrollment: $enrollment, + fromStatus: EnrollmentStatus::Confirmed, toStatus: EnrollmentStatus::CheckedIn, actorId: User::factory()->create()->id, reason: 'Late arrival', ), - ))->toThrow(OverrideEnrollmentStatusException::class); + ))->toThrow(function (OverrideEnrollmentStatusException $exception): void { + expect($exception->getCode())->toBe(409); + }); expect($enrollment->fresh()->status)->toBe(EnrollmentStatus::NoShow); }); 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 4815268d9..197e03faa 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 @@ -197,6 +197,7 @@ private function overrideStatusAction(): Action resolve(OverrideEnrollmentStatusAction::class)->handle( new OverrideEnrollmentStatusDTO( enrollment: $record, + fromStatus: $record->status, toStatus: EnrollmentStatus::from($data['to_status']), actorId: (string) auth()->id(), reason: $data['reason'], From 73c62ad4f7694c507c9660ca50b360422c3d28fe Mon Sep 17 00:00:00 2001 From: Davi Castello Branco Tavares de Oliveira Date: Sat, 6 Jun 2026 15:48:51 -0400 Subject: [PATCH 23/24] refactor(events): extract enrollment override action --- ...dmin-status-override-as-separate-action.md | 6 +- .../OverrideEnrollmentStatusAction.php | 9 +-- .../DTOs/OverrideEnrollmentStatusDTO.php | 5 +- .../OverrideEnrollmentStatusAction.php | 62 +++++++++++++++++++ .../EnrollmentsRelationManager.php | 45 +------------- 5 files changed, 76 insertions(+), 51 deletions(-) create mode 100644 app-modules/panel-admin/src/Filament/Resources/Events/RelationManagers/Actions/OverrideEnrollmentStatusAction.php diff --git a/app-modules/events/docs/adr/0008-admin-status-override-as-separate-action.md b/app-modules/events/docs/adr/0008-admin-status-override-as-separate-action.md index 6cac059c3..33df28589 100644 --- a/app-modules/events/docs/adr/0008-admin-status-override-as-separate-action.md +++ b/app-modules/events/docs/adr/0008-admin-status-override-as-separate-action.md @@ -52,9 +52,9 @@ No `ParticipantAttended` or `ParticipantCheckedIn` is dispatched on override. Th If retroactive XP is ever needed, it is a separate decision (likely a `ParticipantManuallyAttended` event, with its own audience in Gamification). -### Filament UI is inline in the EnrollmentsRelationManager +### Filament UI is a dedicated Action class -An `overrideStatusAction()` method is added to `EnrollmentsRelationManager` next to the existing `checkInAction()` method (same private-method pattern, same Action delegation style). It opens a modal with a reason textarea and a status select pre-populated with the allowed targets. The action is visible only when the current status is in the allowlist source set (`no_show`, `confirmed`) — anything else hides the action entirely. +`OverrideEnrollmentStatusAction` lives under the Event relation manager `Actions/` directory, matching the existing `GenerateCheckInCodeAction` / `RevokeCheckInCodeAction` pattern. It opens a modal with a reason textarea and a status select pre-populated with the allowed targets. The action is visible only when the current status is in the allowlist source set (`no_show`, `confirmed`) — anything else hides the action entirely. ### No runtime inconsistency checks @@ -66,4 +66,4 @@ The form and factory enforce that `minimum_days` is set when `attendance_require - **Tightly scoped bypass** — the state machine is still the gatekeeper for all non-override transitions. The override path is the _only_ way to leave a terminal state, and it is one line in one Action. - **No XP duplication risk** — by not re-dispatching domain events, an admin override cannot grant XP twice for the same participant-event pair. - **Trade-off** — overriding a status that has downstream side effects beyond XP (e.g. waitlist promotion triggered by `confirmed → cancelled`) does not replay those side effects. Acceptable for the current scope; flag if a new side-effect is added. -- **Trade-off** — the inline `overrideStatusAction()` method grows `EnrollmentsRelationManager` by ~30 lines. If a third enrollment-related action lands, extract them into a `Actions/` directory inside the relation manager (matching the `GenerateCheckInCodeAction` / `RevokeCheckInCodeAction` pattern already used by `CheckInCodesRelationManager`). +- **Trade-off** — the Filament action is now another class to navigate, but `EnrollmentsRelationManager` stays focused on table composition while action-specific form and callback wiring live next to the other Event relation manager actions. diff --git a/app-modules/events/src/Closure/Actions/OverrideEnrollmentStatusAction.php b/app-modules/events/src/Closure/Actions/OverrideEnrollmentStatusAction.php index 240d90ea9..3b5e09afe 100644 --- a/app-modules/events/src/Closure/Actions/OverrideEnrollmentStatusAction.php +++ b/app-modules/events/src/Closure/Actions/OverrideEnrollmentStatusAction.php @@ -23,10 +23,11 @@ /** @return list */ public static function allowedTargetsFor(EnrollmentStatus $from): array { - return array_values(array_map( - static fn (array $pair): EnrollmentStatus => $pair['to'], - array_filter(self::ALLOWED_OVERRIDES, static fn (array $pair): bool => $pair['from'] === $from), - )); + return collect(self::ALLOWED_OVERRIDES) + ->whereStrict('from', $from) + ->pluck('to') + ->values() + ->all(); } /** diff --git a/app-modules/events/src/Closure/DTOs/OverrideEnrollmentStatusDTO.php b/app-modules/events/src/Closure/DTOs/OverrideEnrollmentStatusDTO.php index cddeaccd8..62ab5948c 100644 --- a/app-modules/events/src/Closure/DTOs/OverrideEnrollmentStatusDTO.php +++ b/app-modules/events/src/Closure/DTOs/OverrideEnrollmentStatusDTO.php @@ -10,6 +10,9 @@ final readonly class OverrideEnrollmentStatusDTO { + /** + * @throws OverrideEnrollmentStatusException + */ public function __construct( public Enrollment $enrollment, public EnrollmentStatus $fromStatus, @@ -17,7 +20,7 @@ public function __construct( public string $actorId, public string $reason, ) { - if (mb_trim($this->reason) === '') { + if (blank($this->reason)) { throw OverrideEnrollmentStatusException::reasonRequired(); } } diff --git a/app-modules/panel-admin/src/Filament/Resources/Events/RelationManagers/Actions/OverrideEnrollmentStatusAction.php b/app-modules/panel-admin/src/Filament/Resources/Events/RelationManagers/Actions/OverrideEnrollmentStatusAction.php new file mode 100644 index 000000000..9d1f7938d --- /dev/null +++ b/app-modules/panel-admin/src/Filament/Resources/Events/RelationManagers/Actions/OverrideEnrollmentStatusAction.php @@ -0,0 +1,62 @@ +label('Override Status') + ->icon(Heroicon::OutlinedPencilSquare) + ->color('warning') + ->visible(fn (Enrollment $record): bool => OverrideEnrollmentStatusDomainAction::allowedTargetsFor($record->status) !== []) + ->schema([ + Select::make('to_status') + ->label('New Status') + ->options(fn (Enrollment $record): array => collect(OverrideEnrollmentStatusDomainAction::allowedTargetsFor($record->status)) + ->mapWithKeys(fn (EnrollmentStatus $s): array => [$s->value => $s->getLabel()]) + ->all()) + ->required(), + Textarea::make('reason') + ->label('Reason') + ->required() + ->minLength(3) + ->rows(3), + ]) + ->action(function (Enrollment $record, array $data): void { + resolve(OverrideEnrollmentStatusDomainAction::class)->handle( + new OverrideEnrollmentStatusDTO( + enrollment: $record, + fromStatus: $record->status, + toStatus: EnrollmentStatus::from($data['to_status']), + actorId: (string) auth()->id(), + reason: $data['reason'], + ), + ); + + Notification::make() + ->success() + ->title('Enrollment status overridden.') + ->send(); + }); + } + + public static function getDefaultName(): string + { + return 'overrideStatus'; + } +} 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 197e03faa..9b322d5d8 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 @@ -10,8 +10,6 @@ use Filament\Actions\DeleteAction; use Filament\Actions\DeleteBulkAction; use Filament\Forms\Components\DatePicker; -use Filament\Forms\Components\Select; -use Filament\Forms\Components\Textarea; use Filament\Notifications\Notification; use Filament\Resources\RelationManagers\RelationManager; use Filament\Support\Icons\Heroicon; @@ -21,11 +19,10 @@ use He4rt\Events\CheckIn\Actions\ManualCheckInAction; use He4rt\Events\CheckIn\DTOs\ManualCheckInDTO; use He4rt\Events\CheckIn\Models\CheckIn; -use He4rt\Events\Closure\Actions\OverrideEnrollmentStatusAction; -use He4rt\Events\Closure\DTOs\OverrideEnrollmentStatusDTO; use He4rt\Events\Enrollment\Enums\EnrollmentStatus; use He4rt\Events\Enrollment\Models\Enrollment; use He4rt\Events\Event\Models\Event; +use He4rt\PanelAdmin\Filament\Resources\Events\RelationManagers\Actions\OverrideEnrollmentStatusAction; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Collection; use Illuminate\Support\Facades\Date; @@ -88,7 +85,7 @@ public function table(Table $table): Table ]) ->recordActions([ $this->checkInAction(), - $this->overrideStatusAction(), + OverrideEnrollmentStatusAction::make(), DeleteAction::make(), ]) ->toolbarActions([ @@ -172,42 +169,4 @@ private function checkIn(Enrollment $enrollment, array $data): CheckIn ), ); } - - private function overrideStatusAction(): Action - { - return Action::make('overrideStatus') - ->label('Override Status') - ->icon(Heroicon::OutlinedPencilSquare) - ->color('warning') - ->visible(fn (Enrollment $record): bool => OverrideEnrollmentStatusAction::allowedTargetsFor($record->status) !== []) - ->schema([ - Select::make('to_status') - ->label('New Status') - ->options(fn (Enrollment $record): array => collect(OverrideEnrollmentStatusAction::allowedTargetsFor($record->status)) - ->mapWithKeys(fn (EnrollmentStatus $s): array => [$s->value => $s->getLabel()]) - ->all()) - ->required(), - Textarea::make('reason') - ->label('Reason') - ->required() - ->minLength(3) - ->rows(3), - ]) - ->action(function (Enrollment $record, array $data): void { - resolve(OverrideEnrollmentStatusAction::class)->handle( - new OverrideEnrollmentStatusDTO( - enrollment: $record, - fromStatus: $record->status, - toStatus: EnrollmentStatus::from($data['to_status']), - actorId: (string) auth()->id(), - reason: $data['reason'], - ), - ); - - Notification::make() - ->success() - ->title('Enrollment status overridden.') - ->send(); - }); - } } From 28243c56c5551c0eb183ecf4f44e967d7df3455a Mon Sep 17 00:00:00 2001 From: Davi Castello Branco Tavares de Oliveira Date: Sat, 6 Jun 2026 16:21:14 -0400 Subject: [PATCH 24/24] perf(events): select only event ids for closure dispatch --- .../events/src/Console/Commands/ClosePendingEventsCommand.php | 1 + 1 file changed, 1 insertion(+) diff --git a/app-modules/events/src/Console/Commands/ClosePendingEventsCommand.php b/app-modules/events/src/Console/Commands/ClosePendingEventsCommand.php index 66316f07b..e1d3aac7f 100644 --- a/app-modules/events/src/Console/Commands/ClosePendingEventsCommand.php +++ b/app-modules/events/src/Console/Commands/ClosePendingEventsCommand.php @@ -25,6 +25,7 @@ public function handle(): int ->whereHas('enrollments', function (Builder $query): void { $query->whereIn('status', [EnrollmentStatus::Confirmed, EnrollmentStatus::CheckedIn]); }) + ->select('id') ->each(function (Event $event) use (&$count): void { dispatch(new ProcessEventClosureJob($event->id)); $count++;