Files
crewli/api/tests/Feature/FormBuilder/Schema/Ws6FoundationMigrationTest.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

172 lines
6.8 KiB
PHP

<?php
declare(strict_types=1);
namespace Tests\Feature\FormBuilder\Schema;
use App\Models\FormBuilder\FormSchema;
use App\Models\FormBuilder\FormSubmission;
use App\Models\Organisation;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Tests\TestCase;
/**
* Migration rehearsal for WS-6 foundation:
* - 2026_04_25_140000_extend_form_submissions_with_apply_status
* - 2026_04_25_140100_create_form_submission_action_failures
*
* Verifies columns + indexes land, no DB-level default on apply_status
* (RFC O1: legacy rows stay NULL), and the down() methods clean up.
*/
final class Ws6FoundationMigrationTest extends TestCase
{
use RefreshDatabase;
public function test_apply_status_columns_and_indexes_present_after_migration(): void
{
$this->assertTrue(Schema::hasColumn('form_submissions', 'apply_status'));
$this->assertTrue(Schema::hasColumn('form_submissions', 'apply_completed_at'));
$indexes = $this->indexNamesFor('form_submissions');
$this->assertContains('fs_schema_apply_status_idx', $indexes);
$this->assertContains('fs_org_apply_status_idx', $indexes);
}
public function test_apply_status_has_no_database_default_so_legacy_rows_remain_null(): void
{
$organisation = Organisation::factory()->create();
$schema = FormSchema::factory()->for($organisation)->create();
// Direct DB insert simulating a legacy row written before the
// applicator existed: nothing writes apply_status.
$id = (string) \Illuminate\Support\Str::ulid();
DB::table('form_submissions')->insert([
'id' => $id,
'form_schema_id' => $schema->id,
'organisation_id' => $organisation->id,
'status' => 'submitted',
'is_test' => false,
'auto_save_count' => 0,
'created_at' => now(),
'updated_at' => now(),
]);
$row = DB::table('form_submissions')->where('id', $id)->first();
$this->assertNotNull($row);
$this->assertNull($row->apply_status);
$this->assertNull($row->apply_completed_at);
}
public function test_form_submission_action_failures_table_has_expected_columns_and_indexes(): void
{
$this->assertTrue(Schema::hasTable('form_submission_action_failures'));
$expected = [
'id', 'form_submission_id', 'listener_class', 'binding_id',
'failed_at', 'exception_class', 'exception_message', 'context',
'retry_count',
'resolved_at', 'resolved_by_user_id', 'resolved_note',
'dismissed_at', 'dismissed_by_user_id',
'dismissed_reason_type', 'dismissed_reason_note',
'created_at', 'updated_at',
];
foreach ($expected as $column) {
$this->assertTrue(
Schema::hasColumn('form_submission_action_failures', $column),
"Missing column: {$column}",
);
}
// RFC V3 — table intentionally has NO denormalized organisation_id.
$this->assertFalse(
Schema::hasColumn('form_submission_action_failures', 'organisation_id'),
'form_submission_action_failures must not carry organisation_id (FK-chain tenancy per RFC V3)',
);
$indexes = $this->indexNamesFor('form_submission_action_failures');
foreach ([
'fsaf_submission_idx',
'fsaf_listener_failed_idx',
'fsaf_resolved_idx',
'fsaf_dismissed_idx',
'fsaf_binding_idx',
'fsaf_reason_type_idx',
] as $idx) {
$this->assertContains($idx, $indexes, "Missing index: {$idx}");
}
}
public function test_down_methods_clean_up_columns_and_table(): void
{
// The two WS-6 foundation migrations sit chronologically between
// 2026_04_25_100000 (WS-5a) and 2026_04_26_100000 (WS-5c) — they
// are NOT the last batch, so `migrate:rollback --step=N` would
// target unrelated migrations. Invoke the down() methods directly.
$createFailures = require database_path(
'migrations/2026_04_25_140100_create_form_submission_action_failures.php',
);
$applyStatus = require database_path(
'migrations/2026_04_25_140000_extend_form_submissions_with_apply_status.php',
);
// Sessie 3c added a child table referencing form_submission_action_failures
// via FK; we must drop the child before downing the parent.
$retryAttempts = require database_path(
'migrations/2026_04_28_180000_create_form_submission_action_failure_retry_attempts_table.php',
);
// Sessie 3c also adds exception_trace to the parent table — chain
// its down() before the parent's drop so the column ordering on
// restore matches the production migration order.
$exceptionTrace = require database_path(
'migrations/2026_04_28_181000_add_exception_trace_to_form_submission_action_failures.php',
);
$retryAttempts->down();
$exceptionTrace->down();
$createFailures->down();
$applyStatus->down();
try {
$this->assertFalse(Schema::hasColumn('form_submissions', 'apply_status'));
$this->assertFalse(Schema::hasColumn('form_submissions', 'apply_completed_at'));
$this->assertFalse(Schema::hasTable('form_submission_action_failures'));
$this->assertFalse(Schema::hasTable('form_submission_action_failure_retry_attempts'));
$indexes = $this->indexNamesFor('form_submissions');
$this->assertNotContains('fs_schema_apply_status_idx', $indexes);
$this->assertNotContains('fs_org_apply_status_idx', $indexes);
} finally {
// Restore state for any subsequent tests in this class.
$applyStatus->up();
$createFailures->up();
$exceptionTrace->up();
$retryAttempts->up();
}
}
/**
* @return list<string>
*/
private function indexNamesFor(string $table): array
{
$driver = DB::connection()->getDriverName();
if ($driver === 'mysql' || $driver === 'mariadb') {
return collect(DB::select("SHOW INDEX FROM {$table}"))
->pluck('Key_name')
->unique()
->values()
->all();
}
if ($driver === 'sqlite') {
return collect(DB::select("SELECT name FROM sqlite_master WHERE type='index' AND tbl_name = ?", [$table]))
->pluck('name')
->all();
}
return Schema::getIndexes($table)
? collect(Schema::getIndexes($table))->pluck('name')->all()
: [];
}
}