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, 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..33df28589 --- /dev/null +++ b/app-modules/events/docs/adr/0008-admin-status-override-as-separate-action.md @@ -0,0 +1,69 @@ +# 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 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 + +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 a dedicated Action class + +`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 + +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 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/lang/en/exceptions.php b/app-modules/events/lang/en/exceptions.php index 58511678b..116dd963b 100644 --- a/app-modules/events/lang/en/exceptions.php +++ b/app-modules/events/lang/en/exceptions.php @@ -10,4 +10,7 @@ '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.', + '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 fdd707908..f2a6eaefc 100644 --- a/app-modules/events/lang/pt_BR/exceptions.php +++ b/app-modules/events/lang/pt_BR/exceptions.php @@ -10,4 +10,7 @@ '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.', + '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/CloseEventAction.php b/app-modules/events/src/Closure/Actions/CloseEventAction.php new file mode 100644 index 000000000..ed104df33 --- /dev/null +++ b/app-modules/events/src/Closure/Actions/CloseEventAction.php @@ -0,0 +1,76 @@ +enrollments() + ->whereIn('status', [EnrollmentStatus::Confirmed, EnrollmentStatus::CheckedIn]) + ->eachById(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; + }); + } +} 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..3b5e09afe --- /dev/null +++ b/app-modules/events/src/Closure/Actions/OverrideEnrollmentStatusAction.php @@ -0,0 +1,80 @@ + EnrollmentStatus::NoShow, 'to' => EnrollmentStatus::Attended], + ['from' => EnrollmentStatus::Confirmed, 'to' => EnrollmentStatus::CheckedIn], + ]; + + /** @return list */ + public static function allowedTargetsFor(EnrollmentStatus $from): array + { + return collect(self::ALLOWED_OVERRIDES) + ->whereStrict('from', $from) + ->pluck('to') + ->values() + ->all(); + } + + /** + * @throws OverrideEnrollmentStatusException + * @throws Throwable + */ + public function handle(OverrideEnrollmentStatusDTO $dto): EnrollmentTransition + { + return DB::transaction(function () use ($dto): EnrollmentTransition { + $enrollment = Enrollment::query() + ->whereKey($dto->enrollment->id) + ->lockForUpdate() + ->firstOrFail(); + + $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), + ); + + $attributes = ['status' => $dto->toStatus]; + + if ($timestampColumn = $dto->toStatus->timestampColumn()) { + $attributes[$timestampColumn] = now(); + } + + $enrollment->update($attributes); + + return EnrollmentTransition::query()->create([ + 'enrollment_id' => $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); + } +} 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..62ab5948c --- /dev/null +++ b/app-modules/events/src/Closure/DTOs/OverrideEnrollmentStatusDTO.php @@ -0,0 +1,27 @@ +reason)) { + throw OverrideEnrollmentStatusException::reasonRequired(); + } + } +} 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 @@ + $from->value, 'to' => $to->value]), + 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/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(), + ]); + } +} 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..e1d3aac7f --- /dev/null +++ b/app-modules/events/src/Console/Commands/ClosePendingEventsCommand.php @@ -0,0 +1,38 @@ +where('ends_at', '<', now()) + ->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++; + }); + + $this->info(sprintf('Dispatched %d closure job(s).', $count)); + + return self::SUCCESS; + } +} 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) { 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(); 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(); + } } } diff --git a/app-modules/events/tests/Feature/Closure/CloseEventActionTest.php b/app-modules/events/tests/Feature/Closure/CloseEventActionTest.php new file mode 100644 index 000000000..61aa2f298 --- /dev/null +++ b/app-modules/events/tests/Feature/Closure/CloseEventActionTest.php @@ -0,0 +1,247 @@ +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); + } +}); + +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); +}); 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..aac3fec0e --- /dev/null +++ b/app-modules/events/tests/Feature/Closure/OverrideEnrollmentStatusActionTest.php @@ -0,0 +1,203 @@ +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, + fromStatus: EnrollmentStatus::NoShow, + 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, + fromStatus: EnrollmentStatus::Confirmed, + 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, + fromStatus: EnrollmentStatus::NoShow, + 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, + fromStatus: EnrollmentStatus::Cancelled, + toStatus: EnrollmentStatus::Attended, + actorId: User::factory()->create()->id, + reason: 'Should not work', + ), + ))->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([ + 'event_id' => $event->id, + 'user_id' => User::factory()->create()->id, + 'status' => EnrollmentStatus::NoShow, + ]); + + 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', + ), + ))->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, + fromStatus: EnrollmentStatus::Confirmed, + toStatus: EnrollmentStatus::CheckedIn, + actorId: User::factory()->create()->id, + reason: 'Late arrival', + ), + ))->toThrow(function (OverrideEnrollmentStatusException $exception): void { + expect($exception->getCode())->toBe(409); + }); + + expect($enrollment->fresh()->status)->toBe(EnrollmentStatus::NoShow); +}); 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..7eb8e8242 --- /dev/null +++ b/app-modules/events/tests/Feature/Closure/ProcessEventClosureJobTest.php @@ -0,0 +1,102 @@ +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 { + $ref = new ReflectionClass(ProcessEventClosureJob::class); + + $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); +}); 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); +}); 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/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 e87498d5b..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 @@ -22,6 +22,7 @@ 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; @@ -84,6 +85,7 @@ public function table(Table $table): Table ]) ->recordActions([ $this->checkInAction(), + OverrideEnrollmentStatusAction::make(), DeleteAction::make(), ]) ->toolbarActions([ 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..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 @@ -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,48 @@ 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'), + ]; + + $eventDays = self::eventDays($get); + + if ($eventDays === null) { + return $all; + } + + if ($eventDays === 1) { + return [AttendanceRequirement::AnyDay->value => $all[AttendanceRequirement::AnyDay->value]]; + } + + return $all; + } + + private static function minimumDaysMaxValue(Get $get): ?int + { + 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; + } + + $startsDay = Date::parse($startsAt)->startOfDay(); + $endsDay = Date::parse($endsAt)->startOfDay(); + + return (int) $startsDay->diffInDays($endsDay) + 1; + } } 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",