diff --git a/app-modules/events/database/factories/EnrollmentPolicyFactory.php b/app-modules/events/database/factories/EnrollmentPolicyFactory.php
index b4b771f71..96f1ab197 100644
--- a/app-modules/events/database/factories/EnrollmentPolicyFactory.php
+++ b/app-modules/events/database/factories/EnrollmentPolicyFactory.php
@@ -42,4 +42,12 @@ public function rsvp(): static
'enrollment_method' => EnrollmentMethod::Rsvp,
]);
}
+
+ public function application(?array $schema = null): static
+ {
+ return $this->state(fn (): array => [
+ 'enrollment_method' => EnrollmentMethod::Application,
+ 'application_schema' => $schema,
+ ]);
+ }
}
diff --git a/app-modules/events/database/seeders/EventsSeeder.php b/app-modules/events/database/seeders/EventsSeeder.php
index 592f58748..0f57c2ced 100644
--- a/app-modules/events/database/seeders/EventsSeeder.php
+++ b/app-modules/events/database/seeders/EventsSeeder.php
@@ -166,6 +166,12 @@ private function matrix(): array
'minimum_days' => 2,
'cancellation_deadline_hours' => 48,
'xp' => [200, 300, 1000],
+ 'application_schema' => [
+ ['type' => 'text', 'label' => 'Por que quer participar da He4rt Conf?', 'required' => true],
+ ['type' => 'select', 'label' => 'Nível de experiência em desenvolvimento', 'required' => true, 'options' => ['Iniciante', 'Intermediário', 'Avançado']],
+ ['type' => 'textarea', 'label' => 'Descreva um projeto pessoal ou open source relevante', 'required' => false],
+ ['type' => 'checkbox', 'label' => 'Em quais dias você pode comparecer?', 'required' => false, 'options' => ['Dia 1', 'Dia 2', 'Dia 3']],
+ ],
'enrollments' => [
EnrollmentStatus::Pending->value => 6,
EnrollmentStatus::Confirmed->value => 12,
@@ -258,6 +264,10 @@ private function matrix(): array
'minimum_days' => null,
'cancellation_deadline_hours' => 48,
'xp' => [100, 200, 800],
+ 'application_schema' => [
+ ['type' => 'text', 'label' => 'Qual ideia de projeto você traria para o hackathon?', 'required' => true],
+ ['type' => 'select', 'label' => 'Stack principal', 'required' => true, 'options' => ['PHP', 'JavaScript', 'Python', 'Go', 'Rust', 'Outra']],
+ ],
'enrollments' => [
EnrollmentStatus::Cancelled->value => 8,
],
@@ -279,6 +289,7 @@ private function seedPolicy(Event $event, array $spec): void
'xp_on_confirmed' => $spec['xp'][0],
'xp_on_checked_in' => $spec['xp'][1],
'xp_on_attended' => $spec['xp'][2],
+ 'application_schema' => $spec['application_schema'] ?? null,
]);
}
@@ -307,6 +318,7 @@ private function seedEnrollments(Event $event, array $spec, Collection $particip
'status' => $status,
'waitlist_position' => $status === EnrollmentStatus::Waitlisted ? $waitlistPosition++ : null,
'rejection_reason' => $status === EnrollmentStatus::Rejected ? 'Vagas esgotadas.' : null,
+ 'application_data' => $this->fakeApplicationData($spec['application_schema'] ?? null),
...$this->enrollmentTimestamps($status),
]);
}
@@ -407,6 +419,30 @@ private function enrollmentTimestamps(EnrollmentStatus $status): array
};
}
+ /**
+ * @param array>|null $schema
+ * @return array|null
+ */
+ private function fakeApplicationData(?array $schema): ?array
+ {
+ if ($schema === null) {
+ return null;
+ }
+
+ $data = [];
+
+ foreach ($schema as $index => $field) {
+ $data[$index] = match ($field['type'] ?? 'text') {
+ 'select' => fake()->randomElement($field['options'] ?? ['Opção A']),
+ 'checkbox' => blank($field['options']) ? [] : fake()->randomElements($field['options'], fake()->numberBetween(1, count($field['options']))),
+ 'textarea' => fake()->paragraph(),
+ default => fake()->sentence(),
+ };
+ }
+
+ return $data;
+ }
+
private function resolveTenant(): Tenant
{
return Tenant::query()->where('slug', 'he4rt')->first()
diff --git a/app-modules/events/lang/en/exceptions.php b/app-modules/events/lang/en/exceptions.php
index 116dd963b..b3f40e330 100644
--- a/app-modules/events/lang/en/exceptions.php
+++ b/app-modules/events/lang/en/exceptions.php
@@ -13,4 +13,6 @@
'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.',
+ 'enrollment_not_pending' => 'This enrollment is not pending and cannot be approved or rejected.',
+ 'application_data_invalid' => 'The submitted application data is invalid or missing required answers.',
];
diff --git a/app-modules/events/lang/en/pages.php b/app-modules/events/lang/en/pages.php
index 0368bf5d5..a45bb3d2a 100644
--- a/app-modules/events/lang/en/pages.php
+++ b/app-modules/events/lang/en/pages.php
@@ -28,4 +28,23 @@
'no_check_ins_yet' => 'No check-ins recorded yet.',
'enter_check_in_code_hint' => 'Enter the check-in code announced by the organizer.',
'check_in' => 'Check In',
+ 'apply_hint' => 'Fill in the form below to apply for this event.',
+ 'apply_submit' => 'Submit Application',
+ 'application_submitted' => 'Your application has been submitted and is pending review.',
+ 'application_pending_hint' => 'Your application is under review. You will be notified once it is evaluated.',
+ 'application_your_answers' => 'Your Answers',
+ 'application_rejected_hint' => 'Your application was not accepted.',
+ 'application_rejection_reason' => 'Reason: :reason',
+ 'apply_select_option_placeholder' => 'Select an option',
+ 'admin_approve_application' => 'Approve',
+ 'admin_approve_application_modal_heading' => 'Approve Application',
+ 'admin_approve_application_modal_description' => 'Approve the application from :name?',
+ 'admin_approve_application_success' => 'Application approved.',
+ 'admin_reject_application' => 'Reject',
+ 'admin_reject_application_reason_label' => 'Rejection Reason',
+ 'admin_reject_application_success' => 'Application rejected.',
+ 'admin_application_no_data' => 'No application data available.',
+ 'admin_application_answer_yes' => 'Yes',
+ 'admin_application_answer_no' => 'No',
+ 'admin_application_no_answer' => 'No answer',
];
diff --git a/app-modules/events/lang/pt_BR/exceptions.php b/app-modules/events/lang/pt_BR/exceptions.php
index f2a6eaefc..9742ca094 100644
--- a/app-modules/events/lang/pt_BR/exceptions.php
+++ b/app-modules/events/lang/pt_BR/exceptions.php
@@ -13,4 +13,6 @@
'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.',
+ 'enrollment_not_pending' => 'Esta inscrição não está pendente e não pode ser aprovada ou rejeitada.',
+ 'application_data_invalid' => 'Os dados enviados na candidatura são inválidos ou faltam respostas obrigatórias.',
];
diff --git a/app-modules/events/lang/pt_BR/pages.php b/app-modules/events/lang/pt_BR/pages.php
index abec54537..a26e43e59 100644
--- a/app-modules/events/lang/pt_BR/pages.php
+++ b/app-modules/events/lang/pt_BR/pages.php
@@ -28,4 +28,23 @@
'no_check_ins_yet' => 'Nenhum check-in registrado ainda.',
'enter_check_in_code_hint' => 'Insira o código de check-in informado pelo organizador.',
'check_in' => 'Fazer Check-in',
+ 'apply_hint' => 'Preencha o formulário abaixo para se candidatar a este evento.',
+ 'apply_submit' => 'Enviar Candidatura',
+ 'application_submitted' => 'Sua candidatura foi enviada e está aguardando avaliação.',
+ 'application_pending_hint' => 'Sua candidatura está em análise. Você será notificado quando for avaliada.',
+ 'application_your_answers' => 'Suas Respostas',
+ 'application_rejected_hint' => 'Sua candidatura não foi aceita.',
+ 'application_rejection_reason' => 'Motivo: :reason',
+ 'apply_select_option_placeholder' => 'Selecione uma opção',
+ 'admin_approve_application' => 'Aprovar',
+ 'admin_approve_application_modal_heading' => 'Aprovar Candidatura',
+ 'admin_approve_application_modal_description' => 'Aprovar a candidatura de :name?',
+ 'admin_approve_application_success' => 'Candidatura aprovada.',
+ 'admin_reject_application' => 'Rejeitar',
+ 'admin_reject_application_reason_label' => 'Motivo da Rejeição',
+ 'admin_reject_application_success' => 'Candidatura rejeitada.',
+ 'admin_application_no_data' => 'Nenhum dado de candidatura disponível.',
+ 'admin_application_answer_yes' => 'Sim',
+ 'admin_application_answer_no' => 'Não',
+ 'admin_application_no_answer' => 'Sem resposta',
];
diff --git a/app-modules/events/src/Enrollment/Actions/ApproveApplicationAction.php b/app-modules/events/src/Enrollment/Actions/ApproveApplicationAction.php
new file mode 100644
index 000000000..c83ff2e57
--- /dev/null
+++ b/app-modules/events/src/Enrollment/Actions/ApproveApplicationAction.php
@@ -0,0 +1,106 @@
+whereKey($dto->enrollmentId)
+ ->lockForUpdate()
+ ->firstOrFail();
+
+ throw_unless(
+ $enrollment->status === EnrollmentStatus::Pending,
+ EnrollmentException::enrollmentNotPending(),
+ );
+
+ $policy = EnrollmentPolicy::query()
+ ->where('event_id', $enrollment->event_id)
+ ->lockForUpdate()
+ ->firstOrFail();
+
+ $toStatus = $this->resolveApprovalStatus($enrollment->event_id, $policy);
+
+ $waitlistPosition = null;
+ if ($toStatus === EnrollmentStatus::Waitlisted) {
+ $waitlistPosition = (int) Enrollment::query()
+ ->where('event_id', $enrollment->event_id)
+ ->waitlisted()
+ ->max('waitlist_position') + 1;
+
+ $enrollment->update(['waitlist_position' => $waitlistPosition]);
+ }
+
+ $this->transitionEnrollment->handle(new TransitionEnrollmentDTO(
+ enrollment: $enrollment,
+ toStatus: $toStatus,
+ triggeredBy: TriggeredBy::Admin,
+ actorId: $dto->actorId,
+ ));
+
+ if ($toStatus->isConfirmed()) {
+ event(new EnrollmentConfirmed(
+ enrollmentId: $enrollment->id,
+ eventId: $enrollment->event_id,
+ userId: $enrollment->user_id,
+ xpRewardOnConfirmed: $policy->xp_on_confirmed ?? 0,
+ ));
+ }
+
+ if ($toStatus->isWaitlisted()) {
+ event(new EnrollmentWaitlisted(
+ enrollmentId: $enrollment->id,
+ eventId: $enrollment->event_id,
+ userId: $enrollment->user_id,
+ waitlistPosition: $waitlistPosition,
+ ));
+ }
+
+ return $enrollment->fresh(['event.enrollmentPolicy']);
+ });
+ }
+
+ private function resolveApprovalStatus(string $eventId, EnrollmentPolicy $policy): EnrollmentStatus
+ {
+ $capacity = $policy->capacity;
+
+ if ($capacity === null) {
+ return EnrollmentStatus::Confirmed;
+ }
+
+ $occupiedCount = Enrollment::query()
+ ->where('event_id', $eventId)
+ ->active()
+ ->count();
+
+ if ($occupiedCount < $capacity) {
+ return EnrollmentStatus::Confirmed;
+ }
+
+ if ($policy->has_waitlist) {
+ return EnrollmentStatus::Waitlisted;
+ }
+
+ throw EnrollmentException::eventFull();
+ }
+}
diff --git a/app-modules/events/src/Enrollment/Actions/EnrollUserAction.php b/app-modules/events/src/Enrollment/Actions/EnrollUserAction.php
index 255e73199..915a16668 100644
--- a/app-modules/events/src/Enrollment/Actions/EnrollUserAction.php
+++ b/app-modules/events/src/Enrollment/Actions/EnrollUserAction.php
@@ -27,7 +27,7 @@ public function handle(EnrollUserDTO $dto): Enrollment
return DB::transaction(function () use ($dto): Enrollment {
[$event, $policy] = $this->loadLockedEnrollmentContext($dto->eventId);
- $this->validate($event, $policy, $dto->userId);
+ $this->validate($event, $policy, $dto->userId, $dto->applicationData);
$initial = $this->resolveInitialEnrollment($dto->eventId, $policy);
@@ -39,6 +39,7 @@ public function handle(EnrollUserDTO $dto): Enrollment
'enrolled_at' => now(),
'confirmed_at' => $initial['confirmedAt'],
'waitlist_position' => $initial['waitlistPosition'],
+ 'application_data' => $dto->applicationData,
]);
EnrollmentTransition::query()->create([
@@ -103,6 +104,14 @@ private function loadLockedEnrollmentContext(string $eventId): array
*/
private function resolveInitialEnrollment(string $eventId, ?EnrollmentPolicy $policy): array
{
+ if ($policy?->enrollment_method === EnrollmentMethod::Application) {
+ return [
+ 'status' => EnrollmentStatus::Pending,
+ 'waitlistPosition' => null,
+ 'confirmedAt' => null,
+ ];
+ }
+
$capacity = $policy?->capacity;
if ($capacity === null) {
@@ -142,7 +151,10 @@ private function resolveInitialEnrollment(string $eventId, ?EnrollmentPolicy $po
throw EnrollmentException::eventFull();
}
- private function validate(Event $event, ?EnrollmentPolicy $policy, string $userId): void
+ /**
+ * @param array|null $applicationData
+ */
+ private function validate(Event $event, ?EnrollmentPolicy $policy, string $userId, ?array $applicationData): void
{
throw_unless(
$event->status === EventStatus::Published,
@@ -154,10 +166,12 @@ private function validate(Event $event, ?EnrollmentPolicy $policy, string $userI
EnrollmentException::eventPast(),
);
+ $method = $policy?->enrollment_method;
+
throw_unless(
in_array(
- $policy?->enrollment_method,
- [EnrollmentMethod::Rsvp, EnrollmentMethod::RsvpCheckin],
+ $method,
+ [EnrollmentMethod::Rsvp, EnrollmentMethod::RsvpCheckin, EnrollmentMethod::Application],
strict: true,
),
EnrollmentException::invalidEnrollmentMethod(),
@@ -170,5 +184,56 @@ private function validate(Event $event, ?EnrollmentPolicy $policy, string $userI
->exists(),
EnrollmentException::alreadyEnrolled(),
);
+
+ if ($method === EnrollmentMethod::Application) {
+ throw_if(
+ $applicationData === null,
+ EnrollmentException::applicationDataInvalid(),
+ );
+
+ $this->validateApplicationData($applicationData, $policy->application_schema ?? []);
+ }
+ }
+
+ /**
+ * @param array $data
+ * @param array> $schema
+ */
+ private function validateApplicationData(array $data, array $schema): void
+ {
+ foreach ($schema as $index => $field) {
+ $value = $data[$index] ?? null;
+ $type = $field['type'] ?? '';
+
+ if ($type === 'checkbox') {
+ $selected = is_array($value) ? $value : [];
+
+ throw_if(
+ ($field['required'] ?? false) && $selected === [],
+ EnrollmentException::applicationDataInvalid(),
+ );
+
+ $options = $field['options'] ?? [];
+ foreach ($selected as $option) {
+ throw_unless(
+ in_array($option, $options, strict: true),
+ EnrollmentException::applicationDataInvalid(),
+ );
+ }
+
+ continue;
+ }
+
+ if (($field['required'] ?? false) && (in_array($value, [null, '', false], true))) {
+ throw EnrollmentException::applicationDataInvalid();
+ }
+
+ if ($type === 'select' && $value !== null) {
+ $options = $field['options'] ?? [];
+ if (!in_array($value, $options, strict: true)) {
+ throw EnrollmentException::applicationDataInvalid();
+ }
+ }
+ }
}
}
diff --git a/app-modules/events/src/Enrollment/Actions/RejectApplicationAction.php b/app-modules/events/src/Enrollment/Actions/RejectApplicationAction.php
new file mode 100644
index 000000000..0511347c7
--- /dev/null
+++ b/app-modules/events/src/Enrollment/Actions/RejectApplicationAction.php
@@ -0,0 +1,47 @@
+whereKey($dto->enrollmentId)
+ ->lockForUpdate()
+ ->firstOrFail();
+
+ throw_unless(
+ $enrollment->status === EnrollmentStatus::Pending,
+ EnrollmentException::enrollmentNotPending(),
+ );
+
+ $enrollment->update(['rejection_reason' => $dto->reason]);
+
+ $this->transitionEnrollment->handle(new TransitionEnrollmentDTO(
+ enrollment: $enrollment,
+ toStatus: EnrollmentStatus::Rejected,
+ triggeredBy: TriggeredBy::Admin,
+ actorId: $dto->actorId,
+ reason: $dto->reason,
+ ));
+
+ return $enrollment->fresh();
+ });
+ }
+}
diff --git a/app-modules/events/src/Enrollment/DTOs/ApproveApplicationDTO.php b/app-modules/events/src/Enrollment/DTOs/ApproveApplicationDTO.php
new file mode 100644
index 000000000..ca7f83e82
--- /dev/null
+++ b/app-modules/events/src/Enrollment/DTOs/ApproveApplicationDTO.php
@@ -0,0 +1,13 @@
+|null $applicationData
+ */
public function __construct(
public string $eventId,
public string $userId,
+ public ?array $applicationData = null,
) {}
public static function fromModels(Event $event, User $user): self
diff --git a/app-modules/events/src/Enrollment/DTOs/RejectApplicationDTO.php b/app-modules/events/src/Enrollment/DTOs/RejectApplicationDTO.php
new file mode 100644
index 000000000..9364973a7
--- /dev/null
+++ b/app-modules/events/src/Enrollment/DTOs/RejectApplicationDTO.php
@@ -0,0 +1,14 @@
+|null $application_data
+ * @property array|null $application_data
* @property string|null $rejection_reason
* @property Carbon|null $enrolled_at
* @property Carbon|null $confirmed_at
diff --git a/app-modules/events/src/Enrollment/Models/EnrollmentPolicy.php b/app-modules/events/src/Enrollment/Models/EnrollmentPolicy.php
index 297cbf6db..00d95fd14 100644
--- a/app-modules/events/src/Enrollment/Models/EnrollmentPolicy.php
+++ b/app-modules/events/src/Enrollment/Models/EnrollmentPolicy.php
@@ -30,7 +30,7 @@
* @property int $xp_on_confirmed
* @property int $xp_on_checked_in
* @property int $xp_on_attended
- * @property array|null $application_schema
+ * @property array>|null $application_schema
* @property Carbon $created_at
* @property Carbon $updated_at
*/
diff --git a/app-modules/events/tests/Feature/EnrollUserActionTest.php b/app-modules/events/tests/Feature/EnrollUserActionTest.php
index 1be9dff4e..15391701b 100644
--- a/app-modules/events/tests/Feature/EnrollUserActionTest.php
+++ b/app-modules/events/tests/Feature/EnrollUserActionTest.php
@@ -333,3 +333,117 @@ function createRsvpEvent(Tenant $tenant, array $eventAttributes = [], array $pol
expect(Enrollment::query()->where('event_id', $event->id)->where('user_id', $user->id)->count())->toBe(1);
});
+
+// ── Application enrollment ────────────────────────────────────────────────────
+
+test('when a user submits an application, then enrollment is pending with application_data and audit trail', function (): void {
+ EventFacade::fake([EnrollmentConfirmed::class]);
+
+ $user = User::factory()->create();
+ $tenant = Tenant::factory()->create();
+ $event = Event::factory()
+ ->published()
+ ->upcoming()
+ ->for($tenant)
+ ->has(EnrollmentPolicy::factory()->application([
+ ['type' => 'text', 'label' => 'Why do you want to join?', 'required' => true],
+ ]), 'enrollmentPolicy')
+ ->create();
+
+ $dto = new EnrollUserDTO(
+ eventId: $event->id,
+ userId: $user->id,
+ applicationData: [0 => 'I love PHP!'],
+ );
+
+ $enrollment = resolve(EnrollUserAction::class)->handle($dto);
+
+ expect($enrollment->status)->toBe(EnrollmentStatus::Pending)
+ ->and($enrollment->confirmed_at)->toBeNull()
+ ->and($enrollment->application_data)->toBe([0 => 'I love PHP!']);
+
+ $transition = EnrollmentTransition::query()
+ ->where('enrollment_id', $enrollment->id)
+ ->first();
+
+ expect($transition)->not->toBeNull()
+ ->and($transition->from_status)->toBeNull()
+ ->and($transition->to_status)->toBe(EnrollmentStatus::Pending)
+ ->and($transition->triggered_by)->toBe(TriggeredBy::User);
+
+ EventFacade::assertNotDispatched(EnrollmentConfirmed::class);
+});
+
+test('when application is submitted without applicationData, then exception is thrown', function (): void {
+ $user = User::factory()->create();
+ $tenant = Tenant::factory()->create();
+ $event = Event::factory()
+ ->published()
+ ->upcoming()
+ ->for($tenant)
+ ->has(EnrollmentPolicy::factory()->application(), 'enrollmentPolicy')
+ ->create();
+
+ resolve(EnrollUserAction::class)->handle(EnrollUserDTO::fromModels($event, $user));
+})->throws(EnrollmentException::class);
+
+test('when application is missing a required field, then exception is thrown', function (): void {
+ $user = User::factory()->create();
+ $tenant = Tenant::factory()->create();
+ $event = Event::factory()
+ ->published()
+ ->upcoming()
+ ->for($tenant)
+ ->has(EnrollmentPolicy::factory()->application([
+ ['type' => 'text', 'label' => 'Why?', 'required' => true],
+ ]), 'enrollmentPolicy')
+ ->create();
+
+ $dto = new EnrollUserDTO(
+ eventId: $event->id,
+ userId: $user->id,
+ applicationData: [0 => ''],
+ );
+
+ resolve(EnrollUserAction::class)->handle($dto);
+})->throws(EnrollmentException::class);
+
+test('when application is submitted with no schema defined, then enrollment is pending', function (): void {
+ $user = User::factory()->create();
+ $tenant = Tenant::factory()->create();
+ $event = Event::factory()
+ ->published()
+ ->upcoming()
+ ->for($tenant)
+ ->has(EnrollmentPolicy::factory()->application(), 'enrollmentPolicy')
+ ->create();
+
+ $dto = new EnrollUserDTO(
+ eventId: $event->id,
+ userId: $user->id,
+ applicationData: [],
+ );
+
+ $enrollment = resolve(EnrollUserAction::class)->handle($dto);
+
+ expect($enrollment->status)->toBe(EnrollmentStatus::Pending);
+});
+
+test('when application event is past, then application enrollment is rejected', function (): void {
+ $user = User::factory()->create();
+ $tenant = Tenant::factory()->create();
+ $event = Event::factory()
+ ->published()
+ ->past()
+ ->for($tenant)
+ ->has(EnrollmentPolicy::factory()->application(), 'enrollmentPolicy')
+ ->create();
+
+ $dto = new EnrollUserDTO(
+ eventId: $event->id,
+ userId: $user->id,
+ applicationData: [],
+ );
+
+ resolve(EnrollUserAction::class)->handle($dto);
+})->throws(EnrollmentException::class);
diff --git a/app-modules/events/tests/Feature/Enrollment/ApproveApplicationActionTest.php b/app-modules/events/tests/Feature/Enrollment/ApproveApplicationActionTest.php
new file mode 100644
index 000000000..15c359cf2
--- /dev/null
+++ b/app-modules/events/tests/Feature/Enrollment/ApproveApplicationActionTest.php
@@ -0,0 +1,160 @@
+create();
+
+ return Enrollment::factory()->create([
+ 'event_id' => $event->id,
+ 'user_id' => $user->id,
+ 'status' => EnrollmentStatus::Pending,
+ 'enrolled_at' => now(),
+ 'application_data' => [0 => 'My answer'],
+ ]);
+}
+
+function createApplicationEvent(Tenant $tenant, array $policyAttributes = []): Event
+{
+ return Event::factory()
+ ->published()
+ ->upcoming()
+ ->for($tenant)
+ ->has(EnrollmentPolicy::factory()->application()->state($policyAttributes), 'enrollmentPolicy')
+ ->create();
+}
+
+test('when an application is approved, then enrollment transitions to confirmed with audit trail', function (): void {
+ EventFacade::fake([EnrollmentConfirmed::class]);
+
+ $organizer = User::factory()->create();
+ $tenant = Tenant::factory()->create();
+ $event = createApplicationEvent($tenant, ['xp_on_confirmed' => 100]);
+ $enrollment = createPendingApplicationEnrollment($event);
+
+ $result = resolve(ApproveApplicationAction::class)->handle(
+ new ApproveApplicationDTO(enrollmentId: $enrollment->id, actorId: $organizer->id),
+ );
+
+ expect($result->status)->toBe(EnrollmentStatus::Confirmed)
+ ->and($result->confirmed_at)->not->toBeNull();
+
+ $transition = EnrollmentTransition::query()
+ ->where('enrollment_id', $enrollment->id)
+ ->latest()
+ ->first();
+
+ expect($transition->from_status)->toBe(EnrollmentStatus::Pending)
+ ->and($transition->to_status)->toBe(EnrollmentStatus::Confirmed)
+ ->and($transition->triggered_by)->toBe(TriggeredBy::Admin)
+ ->and($transition->actor_id)->toBe($organizer->id);
+
+ EventFacade::assertDispatched(fn (EnrollmentConfirmed $e): bool => $e->enrollmentId === $enrollment->id
+ && $e->xpRewardOnConfirmed === 100);
+});
+
+test('when event is at capacity and has waitlist, then approval results in waitlisted', function (): void {
+ EventFacade::fake([EnrollmentConfirmed::class, EnrollmentWaitlisted::class]);
+
+ $organizer = User::factory()->create();
+ $tenant = Tenant::factory()->create();
+ $event = createApplicationEvent($tenant, ['capacity' => 1, 'has_waitlist' => true]);
+
+ $existingUser = User::factory()->create();
+ Enrollment::factory()->create([
+ 'event_id' => $event->id,
+ 'user_id' => $existingUser->id,
+ 'status' => EnrollmentStatus::Confirmed,
+ 'enrolled_at' => now(),
+ 'confirmed_at' => now(),
+ ]);
+
+ $enrollment = createPendingApplicationEnrollment($event);
+
+ $result = resolve(ApproveApplicationAction::class)->handle(
+ new ApproveApplicationDTO(enrollmentId: $enrollment->id, actorId: $organizer->id),
+ );
+
+ expect($result->status)->toBe(EnrollmentStatus::Waitlisted)
+ ->and($result->waitlist_position)->toBe(1);
+
+ EventFacade::assertNotDispatched(EnrollmentConfirmed::class);
+ EventFacade::assertDispatched(fn (EnrollmentWaitlisted $e): bool => $e->enrollmentId === $enrollment->id
+ && $e->waitlistPosition === 1);
+});
+
+test('when event is at capacity without waitlist, then approval throws event full exception', function (): void {
+ $organizer = User::factory()->create();
+ $tenant = Tenant::factory()->create();
+ $event = createApplicationEvent($tenant, ['capacity' => 1, 'has_waitlist' => false]);
+
+ $existingUser = User::factory()->create();
+ Enrollment::factory()->create([
+ 'event_id' => $event->id,
+ 'user_id' => $existingUser->id,
+ 'status' => EnrollmentStatus::Confirmed,
+ 'enrolled_at' => now(),
+ 'confirmed_at' => now(),
+ ]);
+
+ $enrollment = createPendingApplicationEnrollment($event);
+
+ resolve(ApproveApplicationAction::class)->handle(
+ new ApproveApplicationDTO(enrollmentId: $enrollment->id, actorId: $organizer->id),
+ );
+})->throws(EnrollmentException::class);
+
+test('when approving a non-pending enrollment, then exception is thrown', function (): void {
+ $organizer = User::factory()->create();
+ $tenant = Tenant::factory()->create();
+ $event = createApplicationEvent($tenant);
+
+ $enrollment = Enrollment::factory()->create([
+ 'event_id' => $event->id,
+ 'user_id' => User::factory()->create()->id,
+ 'status' => EnrollmentStatus::Confirmed,
+ 'enrolled_at' => now(),
+ 'confirmed_at' => now(),
+ ]);
+
+ resolve(ApproveApplicationAction::class)->handle(
+ new ApproveApplicationDTO(enrollmentId: $enrollment->id, actorId: $organizer->id),
+ );
+})->throws(EnrollmentException::class);
+
+test('when event has no capacity limit, then approval always confirms', function (): void {
+ EventFacade::fake([EnrollmentConfirmed::class]);
+
+ $organizer = User::factory()->create();
+ $tenant = Tenant::factory()->create();
+ $event = createApplicationEvent($tenant, ['capacity' => null]);
+
+ $enrollments = collect(range(1, 3))->map(
+ fn (): Enrollment => createPendingApplicationEnrollment($event),
+ );
+
+ foreach ($enrollments as $enrollment) {
+ $result = resolve(ApproveApplicationAction::class)->handle(
+ new ApproveApplicationDTO(enrollmentId: $enrollment->id, actorId: $organizer->id),
+ );
+ expect($result->status)->toBe(EnrollmentStatus::Confirmed);
+ }
+
+ EventFacade::assertDispatchedTimes(EnrollmentConfirmed::class, 3);
+});
diff --git a/app-modules/events/tests/Feature/Enrollment/RejectApplicationActionTest.php b/app-modules/events/tests/Feature/Enrollment/RejectApplicationActionTest.php
new file mode 100644
index 000000000..1dc647382
--- /dev/null
+++ b/app-modules/events/tests/Feature/Enrollment/RejectApplicationActionTest.php
@@ -0,0 +1,112 @@
+create();
+ $tenant = Tenant::factory()->create();
+ $event = Event::factory()
+ ->published()
+ ->upcoming()
+ ->for($tenant)
+ ->has(EnrollmentPolicy::factory()->application(), 'enrollmentPolicy')
+ ->create();
+
+ $enrollment = Enrollment::factory()->create([
+ 'event_id' => $event->id,
+ 'user_id' => User::factory()->create()->id,
+ 'status' => EnrollmentStatus::Pending,
+ 'enrolled_at' => now(),
+ 'application_data' => [0 => 'My answer'],
+ ]);
+
+ $result = resolve(RejectApplicationAction::class)->handle(
+ new RejectApplicationDTO(
+ enrollmentId: $enrollment->id,
+ actorId: $organizer->id,
+ reason: 'Not enough experience.',
+ ),
+ );
+
+ expect($result->status)->toBe(EnrollmentStatus::Rejected)
+ ->and($result->rejection_reason)->toBe('Not enough experience.');
+
+ $transition = EnrollmentTransition::query()
+ ->where('enrollment_id', $enrollment->id)
+ ->latest()
+ ->first();
+
+ expect($transition->from_status)->toBe(EnrollmentStatus::Pending)
+ ->and($transition->to_status)->toBe(EnrollmentStatus::Rejected)
+ ->and($transition->triggered_by)->toBe(TriggeredBy::Admin)
+ ->and($transition->actor_id)->toBe($organizer->id)
+ ->and($transition->reason)->toBe('Not enough experience.');
+});
+
+test('when rejecting a non-pending enrollment, then exception is thrown', function (): void {
+ $organizer = User::factory()->create();
+ $tenant = Tenant::factory()->create();
+ $event = Event::factory()
+ ->published()
+ ->upcoming()
+ ->for($tenant)
+ ->has(EnrollmentPolicy::factory()->application(), 'enrollmentPolicy')
+ ->create();
+
+ $enrollment = Enrollment::factory()->create([
+ 'event_id' => $event->id,
+ 'user_id' => User::factory()->create()->id,
+ 'status' => EnrollmentStatus::Confirmed,
+ 'enrolled_at' => now(),
+ 'confirmed_at' => now(),
+ ]);
+
+ resolve(RejectApplicationAction::class)->handle(
+ new RejectApplicationDTO(
+ enrollmentId: $enrollment->id,
+ actorId: $organizer->id,
+ reason: 'Test reason.',
+ ),
+ );
+})->throws(EnrollmentException::class);
+
+test('when application is rejected, then application_data is preserved', function (): void {
+ $organizer = User::factory()->create();
+ $tenant = Tenant::factory()->create();
+ $event = Event::factory()
+ ->published()
+ ->upcoming()
+ ->for($tenant)
+ ->has(EnrollmentPolicy::factory()->application(), 'enrollmentPolicy')
+ ->create();
+
+ $enrollment = Enrollment::factory()->create([
+ 'event_id' => $event->id,
+ 'user_id' => User::factory()->create()->id,
+ 'status' => EnrollmentStatus::Pending,
+ 'enrolled_at' => now(),
+ 'application_data' => [0 => 'Original answer'],
+ ]);
+
+ $result = resolve(RejectApplicationAction::class)->handle(
+ new RejectApplicationDTO(
+ enrollmentId: $enrollment->id,
+ actorId: $organizer->id,
+ reason: 'Rejected.',
+ ),
+ );
+
+ expect($result->application_data)->toBe([0 => 'Original answer']);
+});
diff --git a/app-modules/panel-admin/resources/views/enrollments/application-data.blade.php b/app-modules/panel-admin/resources/views/enrollments/application-data.blade.php
new file mode 100644
index 000000000..2ee884dfb
--- /dev/null
+++ b/app-modules/panel-admin/resources/views/enrollments/application-data.blade.php
@@ -0,0 +1,51 @@
+
+ @if ($record->rejection_reason)
+
+
{{
+ __(
+ 'events::pages.admin_reject_application_reason_label',
+ )
+ }}
+
{{ $record->rejection_reason }}
+
+ @endif
+
+ @if (count($answers) > 0)
+
+ @foreach ($answers as $answer)
+
+
-
+ {{ $answer['label'] }}
+
+ -
+ @if (is_bool($answer['value']))
+ {{
+ $answer['value']
+ ? __('events::pages.admin_application_answer_yes')
+ : __('events::pages.admin_application_answer_no')
+ }}
+ @elseif (is_array($answer['value']))
+ @if ($answer['value'] === [])
+ {{ __('events::pages.admin_application_no_answer') }}
+ @else
+ {{ implode(', ', $answer['value']) }}
+ @endif
+ @elseif ($answer['value'] === '—' || $answer['value'] === null || $answer['value'] === '')
+ {{ __('events::pages.admin_application_no_answer') }}
+ @else
+ {{ $answer['value'] }}
+ @endif
+
+
+ @endforeach
+
+ @else
+
{{ __('events::pages.admin_application_no_data') }}
+ @endif
+
diff --git a/app-modules/panel-admin/src/Filament/Resources/Events/RelationManagers/Actions/ApproveApplicationAction.php b/app-modules/panel-admin/src/Filament/Resources/Events/RelationManagers/Actions/ApproveApplicationAction.php
new file mode 100644
index 000000000..b75cfa5a9
--- /dev/null
+++ b/app-modules/panel-admin/src/Filament/Resources/Events/RelationManagers/Actions/ApproveApplicationAction.php
@@ -0,0 +1,55 @@
+label(__('events::pages.admin_approve_application'))
+ ->icon(Heroicon::OutlinedCheckCircle)
+ ->color('success')
+ ->visible(fn (Enrollment $record): bool => $record->status === EnrollmentStatus::Pending)
+ ->requiresConfirmation()
+ ->modalHeading(__('events::pages.admin_approve_application_modal_heading'))
+ ->modalDescription(fn (Enrollment $record): string => __('events::pages.admin_approve_application_modal_description', ['name' => $record->user?->name]))
+ ->action(function (Enrollment $record): void {
+ try {
+ resolve(ApproveApplicationDomainAction::class)->handle(
+ new ApproveApplicationDTO(
+ enrollmentId: $record->id,
+ actorId: (string) auth()->id(),
+ ),
+ );
+
+ Notification::make()
+ ->success()
+ ->title(__('events::pages.admin_approve_application_success'))
+ ->send();
+ } catch (EnrollmentException $enrollmentException) {
+ Notification::make()
+ ->danger()
+ ->title($enrollmentException->getMessage())
+ ->send();
+ }
+ });
+ }
+
+ public static function getDefaultName(): string
+ {
+ return 'approveApplication';
+ }
+}
diff --git a/app-modules/panel-admin/src/Filament/Resources/Events/RelationManagers/Actions/RejectApplicationAction.php b/app-modules/panel-admin/src/Filament/Resources/Events/RelationManagers/Actions/RejectApplicationAction.php
new file mode 100644
index 000000000..4360f8ae5
--- /dev/null
+++ b/app-modules/panel-admin/src/Filament/Resources/Events/RelationManagers/Actions/RejectApplicationAction.php
@@ -0,0 +1,62 @@
+label(__('events::pages.admin_reject_application'))
+ ->icon(Heroicon::OutlinedXCircle)
+ ->color('danger')
+ ->visible(fn (Enrollment $record): bool => $record->status === EnrollmentStatus::Pending)
+ ->schema([
+ Textarea::make('reason')
+ ->label(__('events::pages.admin_reject_application_reason_label'))
+ ->required()
+ ->minLength(3)
+ ->maxLength(500)
+ ->rows(3),
+ ])
+ ->action(function (Enrollment $record, array $data): void {
+ try {
+ resolve(RejectApplicationDomainAction::class)->handle(
+ new RejectApplicationDTO(
+ enrollmentId: $record->id,
+ actorId: (string) auth()->id(),
+ reason: $data['reason'],
+ ),
+ );
+
+ Notification::make()
+ ->success()
+ ->title(__('events::pages.admin_reject_application_success'))
+ ->send();
+ } catch (EnrollmentException $enrollmentException) {
+ Notification::make()
+ ->danger()
+ ->title($enrollmentException->getMessage())
+ ->send();
+ }
+ });
+ }
+
+ public static function getDefaultName(): string
+ {
+ return 'rejectApplication';
+ }
+}
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 c6a462328..f7442fb9e 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,7 +22,10 @@
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\ApproveApplicationAction;
use He4rt\PanelAdmin\Filament\Resources\Events\RelationManagers\Actions\OverrideEnrollmentStatusAction;
+use He4rt\PanelAdmin\Filament\Resources\Events\RelationManagers\Actions\RejectApplicationAction;
+use Illuminate\Contracts\View\View;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
@@ -40,7 +43,7 @@ public static function getTitle(Model $ownerRecord, string $pageClass): string
public function table(Table $table): Table
{
return $table
- ->recordTitleAttribute('id')
+ ->recordTitle(fn (Enrollment $record): string => $record->user?->name ?? $record->id)
->modifyQueryUsing(fn (Builder $query): Builder => $query->with(['checkIns', 'user']))
->columns([
TextColumn::make('user.name')
@@ -90,6 +93,9 @@ public function table(Table $table): Table
->options(EnrollmentStatus::class),
])
->recordActions([
+ $this->viewApplicationAction(),
+ ApproveApplicationAction::make(),
+ RejectApplicationAction::make(),
$this->checkInAction(),
OverrideEnrollmentStatusAction::make(),
DeleteAction::make(),
@@ -102,6 +108,33 @@ public function table(Table $table): Table
]);
}
+ private function viewApplicationAction(): Action
+ {
+ return Action::make('viewApplication')
+ ->label('View Application')
+ ->icon(Heroicon::OutlinedDocumentText)
+ ->color('gray')
+ ->visible(fn (Enrollment $record): bool => $record->application_data !== null)
+ ->modalContent(function (Enrollment $record): View {
+ $schema = $record->event?->enrollmentPolicy?->application_schema ?? [];
+ $data = $record->application_data ?? [];
+
+ $answers = collect($schema)
+ ->map(fn (array $field, int $index): array => [
+ 'label' => $field['label'] ?? 'Question '.$index,
+ 'value' => $data[$index] ?? '—',
+ ])
+ ->values()
+ ->all();
+
+ return view('panel-admin::enrollments.application-data', [
+ 'answers' => $answers,
+ 'record' => $record,
+ ]);
+ })
+ ->modalSubmitAction(false);
+ }
+
private function checkInAction(): Action
{
return Action::make('checkIn')
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 47ae0b0a2..da6800187 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
@@ -5,8 +5,9 @@
namespace He4rt\PanelAdmin\Filament\Resources\Events\Schemas;
use Filament\Forms\Components\DateTimePicker;
-use Filament\Forms\Components\KeyValue;
+use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\Select;
+use Filament\Forms\Components\TagsInput;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
@@ -153,13 +154,38 @@ public static function configure(Schema $schema): Schema
->minValue(0)
->default(0),
- KeyValue::make('application_schema')
- ->label(__('panel-admin::events.form.application_form_schema'))
- ->keyLabel(__('panel-admin::events.form.application_schema_key'))
- ->valueLabel(__('panel-admin::events.form.application_schema_value'))
+ Repeater::make('application_schema')
+ ->label('Application Form Questions')
->nullable()
->columnSpanFull()
- ->visible(fn (Get $get): bool => $get('enrollment_method') === EnrollmentMethod::Application->value),
+ ->visible(fn (Get $get): bool => $get('enrollment_method') === EnrollmentMethod::Application)
+ ->addActionLabel('Add question')
+ ->reorderable()
+ ->collapsible()
+ ->schema([
+ Select::make('type')
+ ->label('Type')
+ ->options([
+ 'text' => 'Short text',
+ 'textarea' => 'Long text',
+ 'select' => 'Single choice',
+ 'checkbox' => 'Multiple choice',
+ ])
+ ->required()
+ ->live(),
+ TextInput::make('label')
+ ->label('Question')
+ ->required()
+ ->maxLength(255),
+ Toggle::make('required')
+ ->label('Required')
+ ->default(false),
+ TagsInput::make('options')
+ ->label('Options')
+ ->placeholder('Type an option and press Enter')
+ ->visible(fn (Get $get): bool => in_array($get('type'), ['select', 'checkbox'], strict: true))
+ ->required(fn (Get $get): bool => in_array($get('type'), ['select', 'checkbox'], strict: true)),
+ ]),
]),
]);
}
diff --git a/app-modules/panel-app/resources/views/livewire/events/event-detail.blade.php b/app-modules/panel-app/resources/views/livewire/events/event-detail.blade.php
index 6dbe8929e..5b5644cf5 100644
--- a/app-modules/panel-app/resources/views/livewire/events/event-detail.blade.php
+++ b/app-modules/panel-app/resources/views/livewire/events/event-detail.blade.php
@@ -46,6 +46,47 @@
}}
@endif
+
+ @if ($this->enrollment->status === \He4rt\Events\Enrollment\Enums\EnrollmentStatus::Pending)
+
+ {{ __('events::pages.application_pending_hint') }}
+
+ @if ($this->enrollment->application_data && $this->event->enrollmentPolicy?->application_schema)
+
+
+ {{ __('events::pages.application_your_answers') }}
+
+ @foreach ($this->event->enrollmentPolicy->application_schema as $index => $field)
+
+
{{ $field['label'] ?? '' }}
+
+ @php $answer = $this->enrollment->application_data[$index] ?? null; @endphp
+ @if (is_array($answer))
+ {{ $answer !== [] ? implode(', ', $answer) : '—' }}
+ @else
+ {{ $answer ?? '—' }}
+ @endif
+
+
+ @endforeach
+
+ @endif
+ @endif
+
+ @if ($this->enrollment->status === \He4rt\Events\Enrollment\Enums\EnrollmentStatus::Rejected)
+
+ {{ __('events::pages.application_rejected_hint') }}
+
+ @if ($this->enrollment->rejection_reason)
+
+ {{
+ __('events::pages.application_rejection_reason', [
+ 'reason' => $this->enrollment->rejection_reason,
+ ])
+ }}
+
+ @endif
+ @endif
@if ($this->qrToken)
@@ -123,6 +164,68 @@ class="text-success-500 h-4 w-4 shrink-0"
@endif
+ @elseif ($this->canApply)
+
+
{{ __('events::pages.apply_hint') }}
+
+
+
@elseif ($this->canConfirmPresence)
{{ __('events::pages.confirm_presence_hint') }}
diff --git a/app-modules/panel-app/src/Livewire/Events/EventDetail.php b/app-modules/panel-app/src/Livewire/Events/EventDetail.php
index 20df4f220..5ad2fab72 100644
--- a/app-modules/panel-app/src/Livewire/Events/EventDetail.php
+++ b/app-modules/panel-app/src/Livewire/Events/EventDetail.php
@@ -34,15 +34,25 @@
* @property-read Collection
$checkIns
* @property-read bool $hasCheckedInToday
* @property-read bool $canConfirmPresence
+ * @property-read bool $canApply
* @property-read bool $isEventFull
*/
final class EventDetail extends Component
{
public string $eventId;
+ /** @var array */
+ public array $applicationFormData = [];
+
public function mount(string $eventId): void
{
$this->eventId = $eventId;
+
+ foreach ($this->event->enrollmentPolicy?->application_schema ?? [] as $index => $field) {
+ if (($field['type'] ?? null) === 'checkbox') {
+ $this->applicationFormData[$index] = [];
+ }
+ }
}
#[Computed]
@@ -155,6 +165,24 @@ public function canConfirmPresence(): bool
return $policy->has_waitlist;
}
+ #[Computed]
+ public function canApply(): bool
+ {
+ if ($this->event->status !== EventStatus::Published) {
+ return false;
+ }
+
+ if ($this->enrollment !== null) {
+ return false;
+ }
+
+ if ($this->event->enrollmentPolicy?->enrollment_method !== EnrollmentMethod::Application) {
+ return false;
+ }
+
+ return $this->event->starts_at->isFuture();
+ }
+
#[Computed]
public function isEventFull(): bool
{
@@ -186,7 +214,7 @@ public function confirmPresence(): void
EnrollUserDTO::fromModels($this->event, $user),
);
- unset($this->enrollment, $this->canConfirmPresence, $this->isEventFull);
+ unset($this->enrollment, $this->canConfirmPresence, $this->canApply, $this->isEventFull);
Notification::make()
->success()
@@ -200,6 +228,35 @@ public function confirmPresence(): void
}
}
+ public function apply(): void
+ {
+ /** @var User $user */
+ $user = auth()->user();
+
+ try {
+ resolve(EnrollUserAction::class)->handle(
+ new EnrollUserDTO(
+ eventId: $this->event->id,
+ userId: $user->id,
+ applicationData: $this->applicationFormData,
+ ),
+ );
+
+ unset($this->enrollment, $this->canApply);
+ $this->applicationFormData = [];
+
+ Notification::make()
+ ->success()
+ ->title(__('events::pages.application_submitted'))
+ ->send();
+ } catch (EnrollmentException $enrollmentException) {
+ Notification::make()
+ ->danger()
+ ->title($enrollmentException->getMessage())
+ ->send();
+ }
+ }
+
public function render(): View
{
return view('panel-app::livewire.events.event-detail');
diff --git a/app-modules/panel-app/tests/Feature/Events/ApplicationEnrollmentTest.php b/app-modules/panel-app/tests/Feature/Events/ApplicationEnrollmentTest.php
new file mode 100644
index 000000000..0dc33371f
--- /dev/null
+++ b/app-modules/panel-app/tests/Feature/Events/ApplicationEnrollmentTest.php
@@ -0,0 +1,121 @@
+user = User::factory()->create();
+ $this->tenant = Tenant::factory()->create(['slug' => 'test-tenant']);
+ $this->tenant->members()->attach($this->user);
+
+ $this->actingAs($this->user);
+
+ Filament::setCurrentPanel(Filament::getPanel('app'));
+ Filament::setTenant($this->tenant);
+
+ $this->schema = [
+ ['type' => 'text', 'label' => 'Why do you want to join?', 'required' => true],
+ ['type' => 'select', 'label' => 'Experience level', 'required' => false, 'options' => ['Beginner', 'Intermediate', 'Advanced']],
+ ];
+
+ $this->event = Event::factory()
+ ->published()
+ ->upcoming()
+ ->for($this->tenant)
+ ->has(EnrollmentPolicy::factory()->application($this->schema), 'enrollmentPolicy')
+ ->create(['title' => 'He4rt Conf Application']);
+});
+
+test('event page renders apply button for application event', function (): void {
+ $this->get(EventPage::getUrl(['record' => $this->event->id]))
+ ->assertSuccessful()
+ ->assertSee('He4rt Conf Application')
+ ->assertSee(__('events::pages.apply_submit'));
+});
+
+test('event detail shows canApply true and canConfirmPresence false for application event', function (): void {
+ livewire(EventDetail::class, ['eventId' => $this->event->id])
+ ->assertSet('canApply', true)
+ ->assertSet('canConfirmPresence', false);
+});
+
+test('when user submits application, then enrollment is created as pending', function (): void {
+ livewire(EventDetail::class, ['eventId' => $this->event->id])
+ ->set('applicationFormData', [0 => 'I love Laravel!', 1 => 'Intermediate'])
+ ->call('apply')
+ ->assertHasNoErrors()
+ ->assertNotified();
+
+ $enrollment = Enrollment::query()
+ ->where('event_id', $this->event->id)
+ ->where('user_id', $this->user->id)
+ ->first();
+
+ expect($enrollment)->not->toBeNull()
+ ->and($enrollment->status)->toBe(EnrollmentStatus::Pending)
+ ->and($enrollment->confirmed_at)->toBeNull()
+ ->and($enrollment->application_data[0])->toBe('I love Laravel!');
+});
+
+test('after submitting application, event detail shows pending status with answers', function (): void {
+ livewire(EventDetail::class, ['eventId' => $this->event->id])
+ ->set('applicationFormData', [0 => 'I love Laravel!', 1 => 'Intermediate'])
+ ->call('apply');
+
+ livewire(EventDetail::class, ['eventId' => $this->event->id])
+ ->assertSet('canApply', false)
+ ->assertSee(EnrollmentStatus::Pending->getLabel())
+ ->assertSee(__('events::pages.application_pending_hint'))
+ ->assertSee('I love Laravel!');
+});
+
+test('when application is rejected, then rejection reason is shown', function (): void {
+ Enrollment::factory()->create([
+ 'event_id' => $this->event->id,
+ 'user_id' => $this->user->id,
+ 'status' => EnrollmentStatus::Rejected,
+ 'enrolled_at' => now(),
+ 'rejection_reason' => 'Not enough experience.',
+ 'application_data' => [0 => 'I am new'],
+ ]);
+
+ livewire(EventDetail::class, ['eventId' => $this->event->id])
+ ->assertSet('canApply', false)
+ ->assertSee(EnrollmentStatus::Rejected->getLabel())
+ ->assertSee(__('events::pages.application_rejected_hint'))
+ ->assertSee('Not enough experience.');
+});
+
+test('when user has already applied, then apply button is not shown', function (): void {
+ Enrollment::factory()->create([
+ 'event_id' => $this->event->id,
+ 'user_id' => $this->user->id,
+ 'status' => EnrollmentStatus::Pending,
+ 'enrolled_at' => now(),
+ 'application_data' => [0 => 'My answer'],
+ ]);
+
+ livewire(EventDetail::class, ['eventId' => $this->event->id])
+ ->assertSet('canApply', false)
+ ->assertDontSee(__('events::pages.apply_submit'));
+});
+
+test('when application data is missing required field, then error notification is shown', function (): void {
+ livewire(EventDetail::class, ['eventId' => $this->event->id])
+ ->set('applicationFormData', [0 => '', 1 => 'Beginner'])
+ ->call('apply')
+ ->assertNotified();
+
+ expect(Enrollment::query()->where('event_id', $this->event->id)->count())->toBe(0);
+});