Skip to content
Merged
Show file tree
Hide file tree
Changes from 22 commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
022f471
feat(enrollment): `resolveAttendance()` method to validate the checki…
davicbtoliveira Jun 4, 2026
da47e5c
feat(panel_admin): override EnrollmentStatus on the admin panel.
davicbtoliveira Jun 4, 2026
747dc31
feat(events): schedule `ClosePendingEventsCommand`
davicbtoliveira Jun 5, 2026
4f6c111
chore(exceptions): new exceptions translations
davicbtoliveira Jun 5, 2026
d47fe97
docs(adr): ADRs for issue #247
davicbtoliveira Jun 5, 2026
36ca23b
feat(events): closure pending events command `events:close-pending`
davicbtoliveira Jun 5, 2026
325d284
feat(panel-admin): added attendance requirements on `EventForm`
davicbtoliveira Jun 5, 2026
5d38951
feat(events): added attendance_requirements and minimun_days to `Enro…
davicbtoliveira Jun 5, 2026
0fdf456
feat(events): Close event implementation
davicbtoliveira Jun 5, 2026
87e959a
feat(events): Admin override logic
davicbtoliveira Jun 5, 2026
821ef13
feat(events): Admin `OverrideEnrollment` DTO
davicbtoliveira Jun 5, 2026
534a284
feat(events): Close event job
davicbtoliveira Jun 5, 2026
ed4b5b6
feat(events): OverrideEnrollment exceptions
davicbtoliveira Jun 5, 2026
f9dfa7f
feat(events): add ParticipantAttended event and closure tests
davicbtoliveira Jun 5, 2026
601efcc
chore(deps): update package-lock.json metadata
davicbtoliveira Jun 5, 2026
2e5f05f
test(events): read job config from PHP 8 attributes via reflection
davicbtoliveira Jun 5, 2026
4000f2e
refactor(events): expose override allowlist as queryable method
davicbtoliveira Jun 5, 2026
06703c7
chore(events): remove unused getIcon() from EnrollmentStatus enum
davicbtoliveira Jun 5, 2026
62ea0af
fix(events): close all enrollments across chunks
davicbtoliveira Jun 5, 2026
b0e18d1
fix(events): enforce current status on overrides
davicbtoliveira Jun 5, 2026
5ca451a
fix(events): read parent dates for attendance policy
davicbtoliveira Jun 5, 2026
285d541
feat(events): handle stale enrollment overrides
davicbtoliveira Jun 6, 2026
73c62ad
refactor(events): extract enrollment override action
davicbtoliveira Jun 6, 2026
28243c5
perf(events): select only event ids for closure dispatch
davicbtoliveira Jun 6, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
52 changes: 52 additions & 0 deletions app-modules/events/docs/adr/0007-event-closure-as-scheduled-job.md
Original file line number Diff line number Diff line change
@@ -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).
Original file line number Diff line number Diff line change
@@ -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 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`).
3 changes: 3 additions & 0 deletions app-modules/events/lang/en/exceptions.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.',
];
3 changes: 3 additions & 0 deletions app-modules/events/lang/pt_BR/exceptions.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.',
];
76 changes: 76 additions & 0 deletions app-modules/events/src/Closure/Actions/CloseEventAction.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
<?php

declare(strict_types=1);

namespace He4rt\Events\Closure\Actions;

use He4rt\Events\Closure\Events\ParticipantAttended;
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;
use He4rt\Events\Event\Models\Event;
use Illuminate\Support\Facades\DB;
use Throwable;

final readonly class CloseEventAction
{
public function handle(Event $event): int
{
$attendances = 0;

$event->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;
});
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
<?php

declare(strict_types=1);

namespace He4rt\Events\Closure\Actions;

use He4rt\Events\Closure\DTOs\OverrideEnrollmentStatusDTO;
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;

final readonly class OverrideEnrollmentStatusAction
{
private const array ALLOWED_OVERRIDES = [
['from' => EnrollmentStatus::NoShow, 'to' => EnrollmentStatus::Attended],
['from' => EnrollmentStatus::Confirmed, 'to' => EnrollmentStatus::CheckedIn],
];

/** @return list<EnrollmentStatus> */
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),
));
Comment thread
davicbtoliveira marked this conversation as resolved.
Resolved
}

/**
* @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;
Comment thread
davicbtoliveira marked this conversation as resolved.
Resolved

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);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php

declare(strict_types=1);

namespace He4rt\Events\Closure\DTOs;

use He4rt\Events\Closure\Exceptions\OverrideEnrollmentStatusException;
use He4rt\Events\Enrollment\Enums\EnrollmentStatus;
use He4rt\Events\Enrollment\Models\Enrollment;

final readonly class OverrideEnrollmentStatusDTO
{
public function __construct(
public Enrollment $enrollment,
public EnrollmentStatus $fromStatus,
public EnrollmentStatus $toStatus,
public string $actorId,
public string $reason,
) {
if (mb_trim($this->reason) === '') {
Comment thread
davicbtoliveira marked this conversation as resolved.
Resolved
throw OverrideEnrollmentStatusException::reasonRequired();
}
}
}
21 changes: 21 additions & 0 deletions app-modules/events/src/Closure/Events/ParticipantAttended.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

declare(strict_types=1);

namespace He4rt\Events\Closure\Events;

use Illuminate\Contracts\Events\ShouldDispatchAfterCommit;
use Illuminate\Foundation\Events\Dispatchable;

final readonly class ParticipantAttended implements ShouldDispatchAfterCommit
{
use Dispatchable;

// To be consumed by the gamification module
public function __construct(
public string $enrollmentId,
public string $eventId,
public string $userId,
public int $xpRewardOnAttended,
) {}
}
Loading