Skip to content

Beautiful Open-Source Form Builder

29.1 KB
Raw Blame
<?php

use Illuminate\Testing\Fluent\AssertableJson;
use Illuminate\Support\Facades\Cache;

it('can create a contact form', function () {
    $user = $this->actingAsUser();
    $workspace = $this->createUserWorkspace($user);
    $form = $this->makeForm($user, $workspace);
    $formData = new \App\Http\Resources\FormResource($form);

    $response = $this->postJson(route('open.forms.store', $formData->toArray(request())))
        ->assertSuccessful()
        ->assertJson([
            'type' => 'success',
            'message' => 'Form created.',
            'users_first_form' => true,
        ]);

    expect($workspace->forms()->count())->toBe(1);
    $this->assertDatabaseHas('forms', [
        'id' => $response->json('form.id'),
    ]);
});

it('does not treat a subsequent form as the users first form', function (bool $deletePreviousForm) {
    $user = $this->actingAsUser();
    $workspace = $this->createUserWorkspace($user);
    $previousForm = $this->createForm($user, $workspace);

    if ($deletePreviousForm) {
        $previousForm->delete();
    }

    $form = $this->makeForm($user, $workspace);
    $formData = (new \App\Http\Resources\FormResource($form))->toArray(request());

    $this->postJson(route('open.forms.store'), $formData)
        ->assertSuccessful()
        ->assertJsonPath('users_first_form', false);
})->with([
    'existing form' => [false],
    'deleted form' => [true],
]);

it('can fetch forms', function () {
    $user = $this->actingAsUser();
    $workspace = $this->createUserWorkspace($user);
    $form = $this->createForm($user, $workspace);

    $this->getJson(route('open.workspaces.forms.index', $workspace->id))
        ->assertSuccessful()
        ->assertJsonCount(3)
        ->assertSuccessful()
        ->assertJsonPath('data.0.id', $form->id)
        ->assertJsonPath('data.0.title', $form->title);
});

it('supports a bounded form list page size', function () {
    $user = $this->actingAsUser();
    $workspace = $this->createUserWorkspace($user);

    foreach (range(1, 15) as $index) {
        $this->createForm($user, $workspace, [
            'title' => "Pagination test form {$index}",
        ]);
    }

    $this->getJson(route('open.workspaces.forms.index', [
        'workspace' => $workspace->id,
        'per_page' => 20,
    ]))
        ->assertSuccessful()
        ->assertJsonCount(15, 'data')
        ->assertJsonPath('meta.per_page', 20);

    $this->getJson(route('open.workspaces.forms.index', [
        'workspace' => $workspace->id,
        'per_page' => 5,
    ]))
        ->assertSuccessful()
        ->assertJsonPath('meta.per_page', 5)
        ->assertJsonPath('meta.last_page', 3)
        ->assertJsonPath('links.next', fn (string $url) => str_contains($url, 'per_page=5'));

    $this->getJson(route('open.workspaces.forms.index', [
        'workspace' => $workspace->id,
        'per_page' => 1000,
    ]))
        ->assertSuccessful()
        ->assertJsonCount(15, 'data')
        ->assertJsonPath('meta.per_page', 100);
});

it('returns lightweight form list without properties', function () {
    $user = $this->actingAsUser();
    $workspace = $this->createUserWorkspace($user);
    $form = $this->createForm($user, $workspace);

    $response = $this->getJson(route('open.workspaces.forms.index', $workspace->id))
        ->assertSuccessful();

    // Verify expected FormListResource fields are present
    $response->assertJsonStructure([
        'data' => [
            '*' => [
                'id',
                'slug',
                'title',
                'visibility',
                'tags',
                'views_count',
                'submissions_count',
                'created_at',
                'updated_at',
                'last_edited_human',
                'closes_at',
                'is_closed',
                'max_submissions_count',
                'max_number_of_submissions_reached',
                'plan_tier',
                'workspace_id',
                'share_url',
            ],
        ],
    ]);

    // Verify heavy 'properties' field is NOT included (key optimization)
    $response->assertJsonMissingPath('data.0.properties');
    $response->assertJsonMissingPath('data.0.removed_properties');

    // Verify timestamps are ISO 8601 format
    $formData = $response->json('data.0');
    expect($formData['created_at'])->toMatch('/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\+\d{2}:\d{2}$/');
    expect($formData['updated_at'])->toMatch('/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\+\d{2}:\d{2}$/');
});

it('can fetch a form', function () {
    $user = $this->actingAsProUser();
    $workspace = $this->createUserWorkspace($user);
    $form = $this->createForm($user, $workspace);

    $response = $this->getJson(route('open.forms.show', $form->slug))
        ->assertSuccessful()
        ->assertJson([
            'id' => $form->id,
            'title' => $form->title,
            'viewer_is_form_creator' => true,
        ]);
});

it('returns effective no_branding for form owners on self-hosted', function () {
    config()->set('app.self_hosted', true);
    Cache::flush();

    $user = $this->actingAsUser();
    $workspace = $this->createUserWorkspace($user);
    $form = $this->createForm($user, $workspace, [
        'no_branding' => true,
    ]);

    $formData = (new \App\Http\Resources\FormResource($form))->toArray(request());

    expect($formData['no_branding'])->toBeFalse();
});

it('does not leak workspace details on public form fetch', function () {
    $user = \App\Models\User::factory()->create();
    $workspace = $this->createUserWorkspace($user);
    $form = $this->createForm($user, $workspace);

    $response = $this->getJson(route('forms.show', $form->slug))
        ->assertSuccessful()
        ->assertJsonPath('id', $form->id)
        ->assertJsonPath('viewer_is_form_creator', false)
        ->assertJsonPath('workspace_id', $workspace->id)
        ->assertJsonPath('workspace.id', $workspace->id)
        ->assertJsonPath('workspace.max_file_size', $workspace->max_file_size / 1000000);

    $response->assertJsonMissingPath('workspace.users');
    $response->assertJsonMissingPath('workspace.is_admin');
    $response->assertJsonMissingPath('workspace.is_readonly');
    $response->assertJsonMissingPath('workspace.users_count');
});

it('can update a form', function () {
    $user = $this->actingAsUser();
    $workspace = $this->createUserWorkspace($user);
    $form = $this->createForm($user, $workspace);
    $newFormData = $this->makeForm($user, $workspace);
    $form->fill((new \App\Http\Resources\FormResource($newFormData))->toArray(request()));

    $formData = (new \App\Http\Resources\FormResource($form))->toArray(request());

    $this->putJson(route('open.forms.update', $form->id), $formData)
        ->assertSuccessful()
        ->assertJson([
            'type' => 'success',
            'message' => 'Form updated.',
        ]);

    $this->assertDatabaseHas('forms', [
        'id' => $form->id,
        'title' => $form->title
    ]);
});

it('prevalidates recoverable logic after normalizing it without saving', function () {
    $user = $this->actingAsUser();
    $workspace = $this->createUserWorkspace($user);
    $form = $this->createForm($user, $workspace);
    $formData = (new \App\Http\Resources\FormResource($form))->toArray(request());
    $formData['properties'][1]['logic'] = [
        'conditions' => [
            'operatorIdentifier' => 'and',
            'children' => [[
                'identifier' => 'deleted_field',
                'value' => [
                    'operator' => 'equals',
                    'property_meta' => ['id' => 'deleted_field', 'type' => 'text'],
                    'value' => 'yes',
                ],
            ]],
        ],
        'actions' => ['hide-block'],
    ];

    $this->postJson(route('open.forms.validate-definition', $form), $formData)
        ->assertSuccessful()
        ->assertJsonPath('valid', true);

    expect($form->fresh()->properties[1]['logic'] ?? null)->toBeNull();
});

it('authorizes definition prevalidation before running its validation rules', function () {
    $owner = $this->actingAsUser();
    $workspace = $this->createUserWorkspace($owner);
    $form = $this->createForm($owner, $workspace);
    $otherUser = $this->createUser();
    $this->actingAs($otherUser);

    $this->postJson(route('open.forms.validate-definition', $form), [
        'properties' => 'invalid',
    ])->assertForbidden();
});

it('removes recoverably invalid logic while saving the rest of the form', function () {
    $user = $this->actingAsUser();
    $workspace = $this->createUserWorkspace($user);
    $form = $this->createForm($user, $workspace);
    $formData = (new \App\Http\Resources\FormResource($form))->toArray(request());
    $formData['title'] = 'Persisted after cleanup';
    $formData['properties'][1]['logic'] = [
        'conditions' => [
            'operatorIdentifier' => 'and',
            'children' => [[
                'identifier' => 'missing',
                'value' => [
                    'operator' => 'equals',
                    'property_meta' => ['id' => 'missing', 'type' => 'text'],
                    'value' => 'yes',
                ],
            ]],
        ],
        'actions' => ['hide-block'],
    ];

    $this->putJson(route('open.forms.update', $form), $formData)
        ->assertSuccessful()
        ->assertJsonPath('form.title', 'Persisted after cleanup');

    expect($form->fresh()->title)->toBe('Persisted after cleanup')
        ->and($form->fresh()->properties[1])->not->toHaveKey('logic');
});

it('saves after discarding malformed legacy property entries', function () {
    $user = $this->actingAsUser();
    $workspace = $this->createUserWorkspace($user);
    $form = $this->createForm($user, $workspace);
    $form->forceFill([
        'properties' => [
            'malformed',
            ['id' => 'kept', 'name' => 'Kept', 'type' => 'text'],
        ],
    ])->save();
    $formData = (new \App\Http\Resources\FormResource($form->fresh()))->toArray(request());
    $formData['title'] = 'Saved after cleanup';

    $this->putJson(route('open.forms.update', $form), $formData)
        ->assertSuccessful()
        ->assertJsonPath('form.title', 'Saved after cleanup');

    expect($form->fresh()->properties)->toBe([
        ['id' => 'kept', 'name' => 'Kept', 'type' => 'text'],
    ]);
});

it('still blocks when cleanup would require inventing a select option', function () {
    $user = $this->actingAsUser();
    $workspace = $this->createUserWorkspace($user);
    $form = $this->createForm($user, $workspace);
    $formData = (new \App\Http\Resources\FormResource($form))->toArray(request());
    $formData['properties'][] = [
        'id' => 'empty-choice',
        'name' => 'Choose one',
        'type' => 'select',
        'select' => [
            'options' => [
                ['id' => null, 'name' => null],
            ],
        ],
    ];

    $this->putJson(route('open.forms.update', $form), $formData)
        ->assertUnprocessable()
        ->assertJsonValidationErrors(['properties.14.select.options'])
        ->assertJsonPath('issues.0.code', 'invalid_definition');
});

it('applies the shared field count limit to human form saves', function () {
    $user = $this->actingAsUser();
    $workspace = $this->createUserWorkspace($user);
    $form = $this->createForm($user, $workspace);
    $formData = (new \App\Http\Resources\FormResource($form))->toArray(request());
    $formData['properties'] = collect(range(1, \App\Service\Forms\FormStructureValidator::MAX_PROPERTY_COUNT + 1))
        ->map(fn (int $index) => [
            'id' => "field-{$index}",
            'name' => "Field {$index}",
            'type' => 'text',
        ])
        ->all();

    $this->putJson(route('open.forms.update', $form), $formData)
        ->assertUnprocessable()
        ->assertJsonValidationErrors(['properties'])
        ->assertJsonPath('issues.0.path', 'properties');
});

it('preserves strikethrough formatting when updating field help text', function () {
    $user = $this->actingAsUser();
    $workspace = $this->createUserWorkspace($user);
    $form = $this->createForm($user, $workspace);

    $formData = (new \App\Http\Resources\FormResource($form))->toArray(request());
    $formData['properties'][0]['help'] = '<p><s onclick="alert(1)">Unavailable option</s></p>';

    $this->putJson(route('open.forms.update', $form->id), $formData)
        ->assertSuccessful()
        ->assertJsonPath('form.properties.0.help', '<p><s>Unavailable option</s></p>');

    expect($form->fresh()->properties[0]['help'])
        ->toBe('<p><s>Unavailable option</s></p>');
});

it('truncates form titles longer than the database limit when updating a form', function () {
    $user = $this->actingAsUser();
    $workspace = $this->createUserWorkspace($user);
    $form = $this->createForm($user, $workspace);

    $formData = (new \App\Http\Resources\FormResource($form))->toArray(request());
    $formData['title'] = str_repeat('a', 300);

    $this->putJson(route('open.forms.update', $form->id), $formData)
        ->assertSuccessful()
        ->assertJsonPath('form.title', str_repeat('a', 255));

    $this->assertDatabaseHas('forms', [
        'id' => $form->id,
        'title' => str_repeat('a', 255),
    ]);
});

it('backfills missing select option ids when creating a form', function () {
    $user = $this->actingAsUser();
    $workspace = $this->createUserWorkspace($user);
    $form = $this->makeForm($user, $workspace);

    $form->properties = array_merge($form->properties, [
        [
            'id' => 'legacy_select',
            'name' => 'Legacy Select',
            'type' => 'select',
            'required' => false,
            'select' => [
                'options' => [
                    ['name' => 'First legacy option'],
                    ['name' => 'Second legacy option', 'id' => 'existing-option-id'],
                ],
            ],
        ],
    ]);

    $formData = (new \App\Http\Resources\FormResource($form))->toArray(request());

    $response = $this->postJson(route('open.forms.store', $formData))
        ->assertSuccessful()
        ->assertJson([
            'type' => 'success',
            'message' => 'Form created.',
        ]);

    $createdForm = \App\Models\Forms\Form::find($response->json('form.id'));
    $legacySelect = collect($createdForm->properties)->firstWhere('id', 'legacy_select');

    expect($legacySelect['select']['options'][0]['id'])->toBe('First legacy option');
    expect($legacySelect['select']['options'][1]['id'])->toBe('existing-option-id');
});

it('backfills missing multi select option ids when updating a form', function () {
    $user = $this->actingAsUser();
    $workspace = $this->createUserWorkspace($user);
    $form = $this->createForm($user, $workspace);

    $form->properties = array_merge($form->properties, [
        [
            'id' => 'legacy_multi_select',
            'name' => 'Legacy Multi Select',
            'type' => 'multi_select',
            'required' => false,
            'multi_select' => [
                'options' => [
                    ['name' => 'Legacy choice'],
                    ['name' => 'Existing choice', 'id' => 'existing-choice-id'],
                ],
            ],
        ],
    ]);

    $formData = (new \App\Http\Resources\FormResource($form))->toArray(request());

    $this->putJson(route('open.forms.update', $form->id), $formData)
        ->assertSuccessful()
        ->assertJson([
            'type' => 'success',
            'message' => 'Form updated.',
        ]);

    $form->refresh();
    $legacyMultiSelect = collect($form->properties)->firstWhere('id', 'legacy_multi_select');

    expect($legacyMultiSelect['multi_select']['options'][0]['id'])->toBe('Legacy choice');
    expect($legacyMultiSelect['multi_select']['options'][1]['id'])->toBe('existing-choice-id');
});

it('can regenerate a form url', function () {
    $user = $this->actingAsUser();
    $workspace = $this->createUserWorkspace($user);
    $form = $this->createForm($user, $workspace);
    $newFormData = $this->makeForm($user, $workspace);
    $form->update([
        'title' => $newFormData->title,
    ]);
    $form->generateSlug();
    $newSlug = $form->slug;

    $this->putJson(route('open.forms.regenerate-link', [$form->id, 'uuid']))
        ->assertSuccessful()
        ->assertJson(function (AssertableJson $json) {
            return $json->where('type', 'success')
                ->where('form.slug', function ($value) {
                    if (!is_string($value) || (preg_match(
                        '/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/',
                        $value
                    ) !== 1)) {
                        return false;
                    }

                    return true;
                })
                ->etc();
        });

    $this->putJson(route('open.forms.regenerate-link', [$form->id, 'slug']))
        ->assertSuccessful()
        ->assertJson(function (AssertableJson $json) use ($newSlug) {
            return $json->where('type', 'success')
                ->where('form.slug', function ($slug) use ($newSlug) {
                    return substr($slug, 0, -6) == substr($newSlug, 0, -6);
                })
                ->etc();
        });
});

it('can duplicate a form', function () {
    $user = $this->actingAsUser();
    $workspace = $this->createUserWorkspace($user);
    $form = $this->createForm($user, $workspace);

    $response = $this->postJson(route('open.forms.duplicate', $form->id))
        ->assertSuccessful()
        ->assertJson([
            'type' => 'success',
            'message' => 'Form successfully duplicated. You are now editing the duplicated version of the form.',
        ]);

    expect($user->forms()->count())->toBe(2);
    expect($workspace->forms()->count())->toBe(2);
    $this->assertDatabaseHas('forms', [
        'id' => $response->json('new_form.id'),
        'title' => 'Copy of ' . $form->title
    ]);
});

it('normalizes recoverable logic while duplicating without changing the source form', function () {
    $user = $this->actingAsUser();
    $workspace = $this->createUserWorkspace($user);
    $form = $this->createForm($user, $workspace);
    $properties = $form->properties;
    $properties[1]['logic'] = [
        'conditions' => [
            'operatorIdentifier' => 'and',
            'children' => [[
                'identifier' => 'deleted_field',
                'value' => [
                    'operator' => 'equals',
                    'property_meta' => ['id' => 'deleted_field', 'type' => 'text'],
                    'value' => 'yes',
                ],
            ]],
        ],
        'actions' => ['hide-block'],
    ];
    $form->forceFill(['properties' => $properties])->save();

    $response = $this->postJson(route('open.forms.duplicate', $form))
        ->assertSuccessful();

    $copy = \App\Models\Forms\Form::query()->findOrFail($response->json('new_form.id'));
    expect($workspace->forms()->count())->toBe(2)
        ->and($copy->properties[1])->not->toHaveKey('logic')
        ->and($form->fresh()->properties[1])->toHaveKey('logic');
});

it('can delete a form', function () {
    $user = $this->actingAsUser();
    $workspace = $this->createUserWorkspace($user);
    $form = $this->createForm($user, $workspace);

    $this->deleteJson(route('open.forms.destroy', $form->id))
        ->assertSuccessful()
        ->assertJson([
            'type' => 'success',
            'message' => 'Form was deleted.',
        ]);
    expect($user->forms()->count())->toBe(0);
    expect($workspace->forms()->count())->toBe(0);
});

it('can create form with dark mode', function () {
    $user = $this->actingAsUser();
    $workspace = $this->createUserWorkspace($user);
    $form = $this->createForm($user, $workspace, [
        'dark_mode' => 'dark',
    ]);
    $formData = (new \App\Http\Resources\FormResource($form))->toArray(request());

    $this->postJson(route('open.forms.store', $formData))
        ->assertSuccessful()
        ->assertJson([
            'type' => 'success',
            'message' => 'Form created.',
        ]);

    $this->getJson(route('forms.show', $form->slug))
        ->assertSuccessful()
        ->assertJson(function (AssertableJson $json) use ($form) {
            return $json->where('id', $form->id)
                ->where('dark_mode', 'dark')
                ->etc();
        });
});

it('can create form with custom scripts', function () {
    $user = $this->actingAsTrialingUser();
    $workspace = $this->createUserWorkspace($user);
    $form = $this->createForm($user, $workspace, [
        'custom_code' => "<script>console.log('Hello')</script>",
    ]);
    $formData = (new \App\Http\Resources\FormResource($form))->toArray(request());
    $this->postJson(route('open.forms.store', $formData))
        ->assertSuccessful()
        ->assertJson([
            'type' => 'success',
            'message' => 'Form successfully created, but the Non-trial features you used will be disabled when sharing your form:',
            'form' => ['custom_code' => null]
        ]);

    $this->getJson(route('forms.show', $form->slug))
        ->assertSuccessful()->assertJson([
            'id' => $form->id,
            'title' => $form->title,
            'custom_code'  => null
        ]);
})->skip(true, 'Trialing custom script form cleaning disabled for now.');

it('can not set custom slug when not self hosted', function () {
    config(['app.self_hosted' => false]);

    $user = $this->actingAsUser();
    $workspace = $this->createUserWorkspace($user);
    $form = $this->makeForm($user, $workspace);
    $form->slug = 'my-custom-slug-123';
    $formData = (new \App\Http\Resources\FormResource($form))->toArray(request());

    $response = $this->postJson(route('open.forms.store', $formData))
        ->assertSuccessful()
        ->assertJson([
            'type' => 'success',
            'message' => 'Form created.'
        ]);
    $this->assertNotEquals($response->json('form.slug'), 'my-custom-slug-123');
});

it('can set custom slug when self hosted', function () {
    config(['app.self_hosted' => true]);

    $user = $this->actingAsUser();
    $workspace = $this->createUserWorkspace($user);
    $form = $this->makeForm($user, $workspace);
    $form->slug = 'my-custom-slug-123';
    $formData = (new \App\Http\Resources\FormResource($form))->toArray(request());

    $response = $this->postJson(route('open.forms.store', $formData))
        ->assertSuccessful()
        ->assertJson([
            'type' => 'success',
            'message' => 'Form created.'
        ]);
    $this->assertEquals($response->json('form.slug'), 'my-custom-slug-123');
});

it('rejects invalid custom slug format when self hosted', function () {
    config(['app.self_hosted' => true]);

    $user = $this->actingAsUser();
    $workspace = $this->createUserWorkspace($user);
    $form = $this->makeForm($user, $workspace);
    $form->slug = 'Invalid Slug!@#';
    $formData = (new \App\Http\Resources\FormResource($form))->toArray(request());

    $this->postJson(route('open.forms.store', $formData))
        ->assertUnprocessable()
        ->assertJsonValidationErrors(['slug']);
});

it('rejects duplicate custom slug when self hosted', function () {
    config(['app.self_hosted' => true]);

    $user = $this->actingAsUser();
    $workspace = $this->createUserWorkspace($user);

    // Create first form with custom slug
    $form1 = $this->createForm($user, $workspace);
    $form1->update(['slug' => 'duplicate-slug']);

    // Try to create second form with same slug
    $form2 = $this->makeForm($user, $workspace);
    $form2->slug = $form1->slug;
    $formData = (new \App\Http\Resources\FormResource($form2))->toArray(request());

    $this->postJson(route('open.forms.store', $formData))
        ->assertUnprocessable()
        ->assertJsonValidationErrors(['slug']);
});

it('allows empty custom slug when self hosted', function () {
    config(['app.self_hosted' => true]);

    $user = $this->actingAsUser();
    $workspace = $this->createUserWorkspace($user);
    $form = $this->makeForm($user, $workspace);
    $form->slug = null;
    $formData = (new \App\Http\Resources\FormResource($form))->toArray(request());

    $this->postJson(route('open.forms.store', $formData))
        ->assertSuccessful()
        ->assertJson([
            'type' => 'success',
            'message' => 'Form created.',
        ]);
});

it('can update form with custom slug when self hosted', function () {
    config(['app.self_hosted' => true]);

    $user = $this->actingAsUser();
    $workspace = $this->createUserWorkspace($user);
    $form = $this->createForm($user, $workspace);
    $form->slug = 'updated-custom-slug';
    $formData = (new \App\Http\Resources\FormResource($form))->toArray(request());

    $this->putJson(route('open.forms.update', $form->id), $formData)
        ->assertSuccessful()
        ->assertJson([
            'type' => 'success',
            'message' => 'Form updated.',
        ]);

    $this->assertDatabaseHas('forms', [
        'id' => $form->id,
        'slug' => 'updated-custom-slug'
    ]);
});

it('can create form with multi select min/max selection constraints', function () {
    $user = $this->actingAsUser();
    $workspace = $this->createUserWorkspace($user);
    $form = $this->makeForm($user, $workspace);

    // Add multi_select field with min/max constraints
    $form->properties = array_merge($form->properties, [
        [
            'id' => 'multi_select_field',
            'name' => 'Multi Select Field',
            'type' => 'multi_select',
            'required' => true,
            'min_selection' => 2,
            'max_selection' => 4,
            'multi_select' => [
                'options' => [
                    ['id' => 'option1', 'name' => 'Option 1'],
                    ['id' => 'option2', 'name' => 'Option 2'],
                    ['id' => 'option3', 'name' => 'Option 3'],
                    ['id' => 'option4', 'name' => 'Option 4'],
                    ['id' => 'option5', 'name' => 'Option 5'],
                ]
            ]
        ]
    ]);

    $formData = (new \App\Http\Resources\FormResource($form))->toArray(request());

    $response = $this->postJson(route('open.forms.store', $formData))
        ->assertSuccessful()
        ->assertJson([
            'type' => 'success',
            'message' => 'Form created.',
        ]);

    // Verify the constraints are saved
    $createdForm = \App\Models\Forms\Form::find($response->json('form.id'));
    $multiSelectField = collect($createdForm->properties)->firstWhere('id', 'multi_select_field');

    expect($multiSelectField)->not->toBeNull('Multi select field should exist');
    expect($multiSelectField)->toHaveKey('min_selection');
    expect($multiSelectField)->toHaveKey('max_selection');
    expect($multiSelectField['min_selection'])->toBe('2');
    expect($multiSelectField['max_selection'])->toBe('4');
});

it('can update form with multi select min/max selection constraints', function () {
    $user = $this->actingAsUser();
    $workspace = $this->createUserWorkspace($user);
    $form = $this->createForm($user, $workspace);

    // Update form to add multi_select field with constraints
    $form->properties = array_merge($form->properties, [
        [
            'id' => 'updated_multi_select',
            'name' => 'Updated Multi Select',
            'type' => 'multi_select',
            'required' => false,
            'min_selection' => 1,
            'max_selection' => 3,
            'multi_select' => [
                'options' => [
                    ['id' => 'opt1', 'name' => 'Choice 1'],
                    ['id' => 'opt2', 'name' => 'Choice 2'],
                    ['id' => 'opt3', 'name' => 'Choice 3'],
                ]
            ]
        ]
    ]);

    $formData = (new \App\Http\Resources\FormResource($form))->toArray(request());

    $this->putJson(route('open.forms.update', $form->id), $formData)
        ->assertSuccessful()
        ->assertJson([
            'type' => 'success',
            'message' => 'Form updated.',
        ]);

    // Verify the constraints are updated correctly
    $form->refresh();
    $multiSelectField = collect($form->properties)->firstWhere('id', 'updated_multi_select');

    expect($multiSelectField['min_selection'])->toBe(1);
    expect($multiSelectField['max_selection'])->toBe(3);
});

it('clears invalid optional selection constraints during form creation', function () {
    $user = $this->actingAsUser();
    $workspace = $this->createUserWorkspace($user);
    $form = $this->makeForm($user, $workspace);

    // Add invalid constraints (negative min, zero max)
    $form->properties = array_merge($form->properties, [
        [
            'id' => 'invalid_field',
            'name' => 'Invalid Field',
            'type' => 'multi_select',
            'min_selection' => -1,  // Invalid: negative
            'max_selection' => 0,   // Invalid: zero
            'multi_select' => [
                'options' => [
                    ['id' => 'option1', 'name' => 'Option 1'],
                ]
            ]
        ]
    ]);

    $formData = (new \App\Http\Resources\FormResource($form))->toArray(request());

    $response = $this->postJson(route('open.forms.store', $formData))
        ->assertSuccessful();

    $savedForm = \App\Models\Forms\Form::query()->findOrFail($response->json('form.id'));
    $savedField = collect($savedForm->properties)->firstWhere('id', 'invalid_field');

    expect($savedField)->not->toHaveKeys(['min_selection', 'max_selection']);
});