Files
crewli/api/tests/Feature/FormBuilder/Api/FormSubmissionActionFailureResourceShapeTest.php
bert.hausmans 192353f4bc feat(form-builder): admin UI completion — server filters, KPIs, resource expansion (WS-6 sessie 3c)
Closes the four production gaps that emerged from sessie 3b's admin UI.
What we ship here is final: no further rework planned before production.

Backend
- IndexFailuresRequest validates state/search/failed_at_from/failed_at_to/
  listener_class. orgIndex + platformIndex apply them via a single
  applyIndexFilters() helper. Search runs case-insensitive `LIKE` on
  exception_message; SQL wildcards in user input are escaped.
- New /kpis aggregate endpoint per scope (orgKpis, platformKpis) returns
  open / resolved_30d / dismissed_30d / total_submissions in O(1) COUNTs.
  Replaces sessie 3b's client-side bucketing of an oversized list.
- Resource expansion: organisation_name, form_schema_label,
  resolved_by_user_name, dismissed_by_user_name, exception_trace,
  retry_history[]. Eager-loading via indexEagerLoads()/detailEagerLoads()
  prevents N+1 (verified by query-count assertion in test).
- New 2026_04_28_181000 migration adds exception_trace (longtext nullable)
  to form_submission_action_failures. ApplyBindingsOnFormSubmit listener
  now captures $e->getTraceAsString() at failure time.
- New FormSubmissionActionFailureRetryAttemptResource exposes per-attempt
  data (timestamp, actor name, outcome, exception details) inside
  retry_history[]. Index payloads omit the field via whenLoaded() to keep
  list responses lean.

Frontend (apps/app)
- Types updated to mirror the expanded resource shape and the new KPI
  endpoint contract. FormFailuresKpis is now { open, resolved_30d,
  dismissed_30d, total_submissions } (server-aggregate).
- useFormFailures composable forwards all 5 server filters via
  buildIndexParams() (strips empty/whitespace). useFormFailuresKpis hits
  the dedicated /kpis endpoint per scope.
- FormFailuresTable replaces client-side bucketing with server-side
  filtering, adds listener_class + date-range filter inputs, and renames
  the 4th KPI tile to "Submissions" (was "Totaal").
- FormFailureDetail renders organisation_name + form_schema_label in the
  header, surfaces an expandable stack-trace card, names the resolved/
  dismissed actor in the timeline, and replaces the "v1 placeholder"
  retry-history card with a full per-attempt timeline.

ESLint config gap (apps/app)
- New .eslintrc.cjs adapted from the Vuexy reference, minus Vuexy-internal
  rules. `pnpm lint` now runs successfully (was previously broken — the
  package.json script referenced a missing config). The 80 baseline
  violations across the codebase are pre-existing and out of scope for
  this session.

Tests + gates
- 24 new backend tests across filter, kpis, and resource-shape suites.
  Backend: 1462 → 1486 passing, 0 → 0 failing. Larastan clean. Rector
  dry-run unchanged at 354 (pre-Task-1 baseline from f18b55b).
- 3 new vitest tests in apps/app (filter wiring, KPI endpoint, KPI tile
  values from /kpis). Vitest: 38 → 41 passing. tsc clean. Portal
  unchanged (113 vitest, tsc clean).
- 5 backfill rollback tests bumped --step counts +1 for the new migration.
- Ws6FoundationMigrationTest down/up chain now includes exception_trace
  before the parent table is restored.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-29 00:14:20 +02:00

161 lines
6.3 KiB
PHP

<?php
declare(strict_types=1);
namespace Tests\Feature\FormBuilder\Api;
use App\Models\FormBuilder\FormSchema;
use App\Models\FormBuilder\FormSubmission;
use App\Models\FormBuilder\FormSubmissionActionFailure;
use App\Models\FormBuilder\FormSubmissionActionFailureRetryAttempt;
use App\Models\Organisation;
use App\Models\User;
use Database\Seeders\RoleSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Laravel\Sanctum\Sanctum;
use Tests\TestCase;
/**
* Sessie 3c — verifies the expanded admin-UI resource payload
* (denormalized labels, exception_trace, retry_history[]) and the
* eager-loading guarantees that prevent N+1 on index/show.
*/
final class FormSubmissionActionFailureResourceShapeTest extends TestCase
{
use RefreshDatabase;
private Organisation $orgA;
private User $superAdmin;
private FormSchema $schemaA;
private FormSubmission $submissionA;
protected function setUp(): void
{
parent::setUp();
$this->seed(RoleSeeder::class);
$this->orgA = Organisation::factory()->create(['name' => 'Festival X']);
$this->schemaA = FormSchema::factory()->create([
'organisation_id' => $this->orgA->id,
'name' => 'Vrijwilligers aanmelding',
]);
$this->submissionA = FormSubmission::factory()->create([
'form_schema_id' => $this->schemaA->id,
'organisation_id' => $this->orgA->id,
]);
$this->superAdmin = User::factory()->create();
$this->superAdmin->assignRole('super_admin');
}
public function test_show_payload_includes_denormalized_labels_and_trace(): void
{
$resolver = User::factory()->create(['first_name' => 'Maud', 'last_name' => 'Admin']);
$failure = FormSubmissionActionFailure::factory()
->for($this->submissionA, 'submission')
->create([
'exception_trace' => "#0 stack frame\n#1 next frame",
'resolved_at' => now(),
'resolved_by_user_id' => $resolver->id,
'resolved_note' => 'fixed manually',
]);
Sanctum::actingAs($this->superAdmin);
$response = $this->getJson("/api/v1/admin/form-failures/{$failure->id}")->assertOk();
$response
->assertJsonPath('data.id', (string) $failure->id)
->assertJsonPath('data.organisation_id', (string) $this->orgA->id)
->assertJsonPath('data.organisation_name', 'Festival X')
->assertJsonPath('data.form_schema_id', (string) $this->schemaA->id)
->assertJsonPath('data.form_schema_label', 'Vrijwilligers aanmelding')
->assertJsonPath('data.exception_trace', "#0 stack frame\n#1 next frame")
->assertJsonPath('data.resolved_by_user_name', 'Maud Admin')
->assertJsonPath('data.dismissed_by_user_name', null);
}
public function test_show_payload_includes_retry_history_in_chronological_order(): void
{
$failure = FormSubmissionActionFailure::factory()
->for($this->submissionA, 'submission')
->create();
$actor = User::factory()->create(['first_name' => 'Alex', 'last_name' => 'Operator']);
FormSubmissionActionFailureRetryAttempt::factory()->create([
'form_submission_action_failure_id' => $failure->id,
'attempted_at' => now()->subMinutes(10),
'attempted_by_user_id' => $actor->id,
'outcome' => 'failed',
'exception_class' => \RuntimeException::class,
'exception_message' => 'first retry failed',
]);
FormSubmissionActionFailureRetryAttempt::factory()->succeeded()->create([
'form_submission_action_failure_id' => $failure->id,
'attempted_at' => now(),
'attempted_by_user_id' => $actor->id,
]);
Sanctum::actingAs($this->superAdmin);
$response = $this->getJson("/api/v1/admin/form-failures/{$failure->id}")->assertOk();
$history = $response->json('data.retry_history');
$this->assertIsArray($history);
$this->assertCount(2, $history);
// latest('attempted_at') in the relation puts the newest first.
$this->assertSame('succeeded', $history[0]['outcome']);
$this->assertSame('failed', $history[1]['outcome']);
$this->assertSame('Alex Operator', $history[0]['attempted_by_user_name']);
$this->assertSame('first retry failed', $history[1]['exception_message']);
}
public function test_index_payload_omits_retry_history_to_keep_payload_small(): void
{
$failure = FormSubmissionActionFailure::factory()
->for($this->submissionA, 'submission')
->create();
FormSubmissionActionFailureRetryAttempt::factory()->create([
'form_submission_action_failure_id' => $failure->id,
]);
Sanctum::actingAs($this->superAdmin);
$response = $this->getJson('/api/v1/admin/form-failures')->assertOk();
// whenLoaded() => the key resolves to MissingValue and is omitted.
$first = $response->json('data.0');
$this->assertArrayNotHasKey('retry_history', $first);
$this->assertSame('Festival X', $first['organisation_name']);
$this->assertSame('Vrijwilligers aanmelding', $first['form_schema_label']);
}
public function test_index_does_not_n_plus_one_on_relations(): void
{
for ($i = 0; $i < 5; $i++) {
$sub = FormSubmission::factory()->create([
'form_schema_id' => $this->schemaA->id,
'organisation_id' => $this->orgA->id,
]);
FormSubmissionActionFailure::factory()->for($sub, 'submission')->create();
}
Sanctum::actingAs($this->superAdmin);
DB::enableQueryLog();
$this->getJson('/api/v1/admin/form-failures')->assertOk();
$queries = DB::getQueryLog();
DB::disableQueryLog();
// Eager-loading bound: failures + submissions + organisations + schemas
// + resolvedBy + dismissedBy + count = 7 baseline; allow modest headroom
// for auth/sanctum/pagination overhead but reject linear growth in N.
$this->assertLessThanOrEqual(15, count($queries), sprintf(
'Index endpoint may have N+1 (executed %d queries for 5 failures): %s',
count($queries),
implode("\n", array_column($queries, 'query')),
));
}
}