Files
crewli/api/tests/Feature/FormBuilder/FormFieldApiTest.php
bert.hausmans bb9242fd6e refactor(form-field): resources + snapshot + validator read form_field_options
Atomic reader switch. All call paths that previously read
form_fields.options / form_field_library.options from the JSON column
now read through FormFieldOptionService::toJsonShape() via the
morphMany relation:

  - FormFieldResource + FormFieldLibraryResource +
    PublicFormSchemaResource emit the rich-shape array
  - FilterRegistryController emits rich shape uniformly (no flat-array
    carve-out for filter-UI compatibility — preflight scan confirmed
    zero portal/app consumers, S5 territory)
  - FormFieldRuleBuilder plucks values from the relation for in:options
    rule construction
  - FormSubmissionService::buildSnapshot writes rich-shape options into
    snapshots and strips translations.{locale}.options from each field's
    translations bag (defensive — commit 2 backfill already did the
    bulk strip)
  - Four FormFieldRequest variants accept array-of-spec-objects,
    validate shape in after() via FormFieldOptionService::assertSpecsValid,
    and hand off to FormFieldOptionService::replaceOptions for writes
  - FormFieldService::create + update extract option specs from the
    request data and route through the service after the FormField row
    is persisted

FormField and FormFieldLibrary $casts no longer include 'options'; the
JSON column is no longer cast. Options removed from $fillable on both
models so ::create() / ::fill() / mass assignment can no longer touch
the legacy column. Both models gain a getOptionsAttribute() accessor
that resolves $model->options to the eager-loaded morphMany collection
— required because Eloquent's getAttribute() prefers a real DB column
over a relation method, and the JSON column lives on the table until
WS-5d commit 5 drops it.

Activity log — dual emit per §6.7 / §17.4.2 / §17.6.3:
  - field.updated carries old.options / new.options diff via
    toJsonShape() reconstruction, byte-equal JSON compare to avoid
    cosmetic false positives. Field updates that don't touch options
    omit the key entirely
  - field.options_replaced emits inside replaceOptions() on FormField
    subject only; library subject writes silent (mirrors the WS-5b /
    WS-5c convention)

JSON columns (form_fields.options, form_field_library.options) remain
present but unread — column drops land atomically in commit 5.

Two pre-existing test fixtures that seeded options via the JSON column
(FormFieldApiTest + PublicFormValidationTest) migrated to the
spec-array path: FormField::factory()->withOptions([...]) where the
options live on the field, or explicit spec-array request bodies for
HTTP tests.

Tests: 1193 → 1206 green (+13 tests / +28 assertions).

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

153 lines
5.6 KiB
PHP

<?php
declare(strict_types=1);
namespace Tests\Feature\FormBuilder;
use App\Enums\FormBuilder\FormFieldType;
use App\Enums\FormBuilder\FormSubmissionStatus;
use App\Models\FormBuilder\FormField;
use App\Models\FormBuilder\FormSchema;
use App\Models\FormBuilder\FormSubmission;
use App\Models\Organisation;
use App\Models\User;
use Database\Seeders\RoleSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Laravel\Sanctum\Sanctum;
use Tests\TestCase;
final class FormFieldApiTest extends TestCase
{
use RefreshDatabase;
private Organisation $org;
private User $admin;
private FormSchema $schema;
protected function setUp(): void
{
parent::setUp();
$this->seed(RoleSeeder::class);
$this->org = Organisation::factory()->create();
$this->admin = User::factory()->create();
$this->org->users()->attach($this->admin, ['role' => 'org_admin']);
$this->schema = FormSchema::factory()->create(['organisation_id' => $this->org->id]);
}
public function test_store_creates_field(): void
{
Sanctum::actingAs($this->admin);
$response = $this->postJson("/api/v1/organisations/{$this->org->id}/forms/schemas/{$this->schema->id}/fields", [
'field_type' => FormFieldType::SELECT->value,
'slug' => 'shirtmaat',
'label' => 'Shirtmaat',
'options' => [
['value' => 'XS', 'label' => 'XS', 'sort_order' => 0],
['value' => 'S', 'label' => 'S', 'sort_order' => 1],
['value' => 'M', 'label' => 'M', 'sort_order' => 2],
['value' => 'L', 'label' => 'L', 'sort_order' => 3],
],
]);
$response->assertCreated();
$this->assertSame('Shirtmaat', $response->json('data.label'));
}
public function test_reorder_applies_new_order(): void
{
Sanctum::actingAs($this->admin);
$fieldA = FormField::factory()->create(['form_schema_id' => $this->schema->id, 'sort_order' => 0]);
$fieldB = FormField::factory()->create(['form_schema_id' => $this->schema->id, 'sort_order' => 1]);
$this->postJson(
"/api/v1/organisations/{$this->org->id}/forms/schemas/{$this->schema->id}/fields/reorder",
['field_ids' => [$fieldB->id, $fieldA->id]],
)->assertOk();
$this->assertSame(0, $fieldB->fresh()->sort_order);
$this->assertSame(1, $fieldA->fresh()->sort_order);
}
public function test_binding_change_blocked_without_force_when_submissions_exist(): void
{
Sanctum::actingAs($this->admin);
$field = FormField::factory()->create([
'form_schema_id' => $this->schema->id,
]);
FormSubmission::factory()->create([
'form_schema_id' => $this->schema->id,
'status' => FormSubmissionStatus::SUBMITTED->value,
]);
$response = $this->putJson(
"/api/v1/organisations/{$this->org->id}/forms/schemas/{$this->schema->id}/fields/{$field->id}",
['binding' => ['mode' => 'entity_owned', 'entity' => 'user_profile', 'column' => 'bio']],
);
$response->assertStatus(422);
$this->assertStringContainsString('Binding change blocked', (string) $response->json('message'));
}
public function test_binding_change_with_force_succeeds(): void
{
Sanctum::actingAs($this->admin);
$field = FormField::factory()->create([
'form_schema_id' => $this->schema->id,
]);
FormSubmission::factory()->create([
'form_schema_id' => $this->schema->id,
'status' => FormSubmissionStatus::SUBMITTED->value,
]);
$this->putJson(
"/api/v1/organisations/{$this->org->id}/forms/schemas/{$this->schema->id}/fields/{$field->id}",
[
'binding' => ['mode' => 'entity_owned', 'entity' => 'user_profile', 'column' => 'bio'],
'force_binding_change' => true,
],
)->assertOk();
}
public function test_cyclic_conditional_logic_is_rejected(): void
{
Sanctum::actingAs($this->admin);
// field A depends on field B — relational rows via factory helper
// (WS-5c commit 2 moved cycle detection to the relational-backed
// `FormFieldConditionalLogicService::assertNoCycles`).
$fieldA = FormField::factory()
->withConditionalLogic([
'operator' => 'all',
'children' => [
['field_slug' => 'b', 'operator' => 'equals', 'value' => true],
],
])
->create([
'form_schema_id' => $this->schema->id,
'slug' => 'a',
]);
$fieldB = FormField::factory()->create(['form_schema_id' => $this->schema->id, 'slug' => 'b']);
// Updating fieldB to depend on fieldA would close the A → B → A loop.
$response = $this->putJson(
"/api/v1/organisations/{$this->org->id}/forms/schemas/{$this->schema->id}/fields/{$fieldB->id}",
['conditional_logic' => ['show_when' => ['all' => [['field_slug' => 'a', 'operator' => 'equals', 'value' => true]]]]],
);
$response->assertStatus(422);
$this->assertStringContainsString('Cyclic', (string) $response->json('message'));
}
public function test_unauthenticated_returns_401(): void
{
$this->postJson("/api/v1/organisations/{$this->org->id}/forms/schemas/{$this->schema->id}/fields", [
'field_type' => FormFieldType::TEXT->value,
'slug' => 'x',
'label' => 'X',
])->assertStatus(401);
}
}