diff --git a/api/app/Http/Controllers/Api/V1/FormBuilder/FilterRegistryController.php b/api/app/Http/Controllers/Api/V1/FormBuilder/FilterRegistryController.php index 48cb9bad..3b8184e5 100644 --- a/api/app/Http/Controllers/Api/V1/FormBuilder/FilterRegistryController.php +++ b/api/app/Http/Controllers/Api/V1/FormBuilder/FilterRegistryController.php @@ -9,6 +9,7 @@ use App\Models\Event; use App\Models\FormBuilder\FormField; use App\Models\FormBuilder\FormSchema; use App\Models\Organisation; +use App\Services\FormBuilder\FormFieldOptionService; use Illuminate\Http\JsonResponse; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Gate; @@ -31,7 +32,10 @@ final class FilterRegistryController extends Controller 'field_type' => 'TAG_PICKER', ]]; + $optionService = app(FormFieldOptionService::class); + $formFieldSources = FormField::query() + ->with('options') ->whereHas('schema', function ($q) use ($organisation, $eventId): void { $q->where('organisation_id', $organisation->id); if ($eventId !== null && $eventId !== '') { @@ -50,7 +54,9 @@ final class FilterRegistryController extends Controller 'schema_slug' => $f->schema?->slug, 'label' => $f->label, 'field_type' => $f->field_type, - 'options' => is_array($f->options) ? array_values($f->options) : null, + 'options' => $f->options->isNotEmpty() + ? $optionService->toJsonShape($f->options) + : null, ])->values()->all(); return [ diff --git a/api/app/Http/Controllers/Api/V1/FormBuilder/FormFieldLibraryController.php b/api/app/Http/Controllers/Api/V1/FormBuilder/FormFieldLibraryController.php index d157cb2a..cafb7ac8 100644 --- a/api/app/Http/Controllers/Api/V1/FormBuilder/FormFieldLibraryController.php +++ b/api/app/Http/Controllers/Api/V1/FormBuilder/FormFieldLibraryController.php @@ -11,6 +11,7 @@ use App\Http\Resources\FormBuilder\FormFieldLibraryResource; use App\Models\FormBuilder\FormFieldLibrary; use App\Models\Organisation; use App\Services\FormBuilder\FormFieldBindingService; +use App\Services\FormBuilder\FormFieldOptionService; use App\Services\FormBuilder\FormFieldValidationRuleService; use Illuminate\Http\JsonResponse; use Illuminate\Http\Resources\Json\AnonymousResourceCollection; @@ -22,6 +23,7 @@ final class FormFieldLibraryController extends Controller public function __construct( private readonly FormFieldBindingService $bindingService, private readonly FormFieldValidationRuleService $validationRuleService, + private readonly FormFieldOptionService $optionService, ) {} public function index(Organisation $organisation): AnonymousResourceCollection @@ -51,6 +53,7 @@ final class FormFieldLibraryController extends Controller $data = $request->validated(); $bindingSpec = $this->extractBindingSpec($data); $validationRuleSpecs = $this->extractValidationRuleSpecs($data); + $optionSpecs = $this->extractOptionSpecs($data); $data['organisation_id'] = $organisation->id; $data['is_system'] = false; $data['is_active'] ??= true; @@ -67,6 +70,10 @@ final class FormFieldLibraryController extends Controller $this->validationRuleService->replaceRules($library, $validationRuleSpecs); } + if ($optionSpecs !== null) { + $this->optionService->replaceOptions($library, $optionSpecs); + } + return $this->created(new FormFieldLibraryResource($library)); } @@ -82,6 +89,9 @@ final class FormFieldLibraryController extends Controller $validationRulesProvided = array_key_exists('validation_rules', $data); $validationRuleSpecs = $validationRulesProvided ? $this->extractValidationRuleSpecs($data) : null; + $optionsProvided = array_key_exists('options', $data); + $optionSpecs = $optionsProvided ? $this->extractOptionSpecs($data) : null; + $fieldLibrary->fill($data); $fieldLibrary->save(); @@ -99,6 +109,13 @@ final class FormFieldLibraryController extends Controller ); } + if ($optionsProvided) { + $this->optionService->replaceOptions( + $fieldLibrary, + $optionSpecs ?? [], + ); + } + return $this->success(new FormFieldLibraryResource($fieldLibrary)); } @@ -126,6 +143,28 @@ final class FormFieldLibraryController extends Controller return array_values($raw); } + /** + * Extract option specs from the request data array. WS-5d commit 3 — + * writes go through `FormFieldOptionService::replaceOptions`. + * + * @param array $data + * @return list>|null + */ + private function extractOptionSpecs(array &$data): ?array + { + if (! array_key_exists('options', $data)) { + return null; + } + $raw = $data['options']; + unset($data['options']); + if (! is_array($raw)) { + return []; + } + + /** @var list> $raw */ + return array_values($raw); + } + /** * @param array $data * @return array{target_entity:string,target_attribute:string,mode:string,sync_direction?:?string}|null diff --git a/api/app/Http/Requests/Api/V1/FormBuilder/StoreFormFieldLibraryRequest.php b/api/app/Http/Requests/Api/V1/FormBuilder/StoreFormFieldLibraryRequest.php index 142475aa..068b06f3 100644 --- a/api/app/Http/Requests/Api/V1/FormBuilder/StoreFormFieldLibraryRequest.php +++ b/api/app/Http/Requests/Api/V1/FormBuilder/StoreFormFieldLibraryRequest.php @@ -5,7 +5,9 @@ declare(strict_types=1); namespace App\Http\Requests\Api\V1\FormBuilder; use App\Enums\FormBuilder\FormFieldType; +use App\Exceptions\FormBuilder\InvalidOptionSpecException; use App\Exceptions\FormBuilder\UnknownValidationRuleTypeException; +use App\Services\FormBuilder\FormFieldOptionService; use App\Services\FormBuilder\FormFieldValidationRuleService; use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; @@ -35,6 +37,12 @@ final class StoreFormFieldLibraryRequest extends FormRequest 'label' => ['required', 'string', 'max:255'], 'help_text' => ['nullable', 'string'], 'options' => ['nullable', 'array'], + 'options.*' => ['array'], + 'options.*.value' => ['required', 'string', 'max:255'], + 'options.*.label' => ['required', 'string', 'max:255'], + 'options.*.sort_order' => ['required', 'integer', 'min:0'], + 'options.*.translations' => ['nullable', 'array'], + 'options.*.translations.*' => ['string', 'max:255'], 'validation_rules' => ['nullable', 'array'], 'validation_rules.*' => ['array'], 'validation_rules.*.rule_type' => ['required', 'string', 'max:40'], @@ -68,6 +76,17 @@ final class StoreFormFieldLibraryRequest extends FormRequest $validator->errors()->add('validation_rules', $e->getMessage()); } }, + function (Validator $validator): void { + $specs = $this->input('options'); + if (! is_array($specs) || $specs === []) { + return; + } + try { + app(FormFieldOptionService::class)->assertSpecsValid($specs); + } catch (InvalidOptionSpecException $e) { + $validator->errors()->add('options', $e->getMessage()); + } + }, ]; } } diff --git a/api/app/Http/Requests/Api/V1/FormBuilder/StoreFormFieldRequest.php b/api/app/Http/Requests/Api/V1/FormBuilder/StoreFormFieldRequest.php index 8069912e..4f6bb853 100644 --- a/api/app/Http/Requests/Api/V1/FormBuilder/StoreFormFieldRequest.php +++ b/api/app/Http/Requests/Api/V1/FormBuilder/StoreFormFieldRequest.php @@ -8,9 +8,11 @@ use App\Enums\FormBuilder\FormFieldDisplayWidth; use App\Enums\FormBuilder\FormFieldType; use App\Enums\FormBuilder\FormValueStorageHint; use App\Exceptions\FormBuilder\InvalidConditionalLogicSpecException; +use App\Exceptions\FormBuilder\InvalidOptionSpecException; use App\Exceptions\FormBuilder\UnknownValidationRuleTypeException; use App\Models\FormBuilder\FormSchema; use App\Services\FormBuilder\FormFieldConditionalLogicService; +use App\Services\FormBuilder\FormFieldOptionService; use App\Services\FormBuilder\FormFieldValidationRuleService; use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; @@ -51,6 +53,12 @@ final class StoreFormFieldRequest extends FormRequest Rule::exists('form_field_library', 'id'), ], 'options' => ['nullable', 'array'], + 'options.*' => ['array'], + 'options.*.value' => ['required', 'string', 'max:255'], + 'options.*.label' => ['required', 'string', 'max:255'], + 'options.*.sort_order' => ['required', 'integer', 'min:0'], + 'options.*.translations' => ['nullable', 'array'], + 'options.*.translations.*' => ['string', 'max:255'], 'validation_rules' => ['nullable', 'array'], 'validation_rules.*' => ['array'], 'validation_rules.*.rule_type' => ['required', 'string', 'max:40'], @@ -91,6 +99,17 @@ final class StoreFormFieldRequest extends FormRequest $validator->errors()->add('validation_rules', $e->getMessage()); } }, + function (Validator $validator): void { + $specs = $this->input('options'); + if (! is_array($specs) || $specs === []) { + return; + } + try { + app(FormFieldOptionService::class)->assertSpecsValid($specs); + } catch (InvalidOptionSpecException $e) { + $validator->errors()->add('options', $e->getMessage()); + } + }, function (Validator $validator): void { $logic = $this->input('conditional_logic'); if ($logic === null || $logic === [] || ! is_array($logic)) { diff --git a/api/app/Http/Requests/Api/V1/FormBuilder/UpdateFormFieldLibraryRequest.php b/api/app/Http/Requests/Api/V1/FormBuilder/UpdateFormFieldLibraryRequest.php index bfeaa434..6586de9a 100644 --- a/api/app/Http/Requests/Api/V1/FormBuilder/UpdateFormFieldLibraryRequest.php +++ b/api/app/Http/Requests/Api/V1/FormBuilder/UpdateFormFieldLibraryRequest.php @@ -5,7 +5,9 @@ declare(strict_types=1); namespace App\Http\Requests\Api\V1\FormBuilder; use App\Enums\FormBuilder\FormFieldType; +use App\Exceptions\FormBuilder\InvalidOptionSpecException; use App\Exceptions\FormBuilder\UnknownValidationRuleTypeException; +use App\Services\FormBuilder\FormFieldOptionService; use App\Services\FormBuilder\FormFieldValidationRuleService; use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; @@ -35,6 +37,12 @@ final class UpdateFormFieldLibraryRequest extends FormRequest 'label' => ['sometimes', 'string', 'max:255'], 'help_text' => ['sometimes', 'nullable', 'string'], 'options' => ['sometimes', 'nullable', 'array'], + 'options.*' => ['array'], + 'options.*.value' => ['required', 'string', 'max:255'], + 'options.*.label' => ['required', 'string', 'max:255'], + 'options.*.sort_order' => ['required', 'integer', 'min:0'], + 'options.*.translations' => ['nullable', 'array'], + 'options.*.translations.*' => ['string', 'max:255'], 'validation_rules' => ['sometimes', 'nullable', 'array'], 'validation_rules.*' => ['array'], 'validation_rules.*.rule_type' => ['required', 'string', 'max:40'], @@ -71,6 +79,20 @@ final class UpdateFormFieldLibraryRequest extends FormRequest $validator->errors()->add('validation_rules', $e->getMessage()); } }, + function (Validator $validator): void { + if (! $this->has('options')) { + return; + } + $specs = $this->input('options'); + if (! is_array($specs) || $specs === []) { + return; + } + try { + app(FormFieldOptionService::class)->assertSpecsValid($specs); + } catch (InvalidOptionSpecException $e) { + $validator->errors()->add('options', $e->getMessage()); + } + }, ]; } } diff --git a/api/app/Http/Requests/Api/V1/FormBuilder/UpdateFormFieldRequest.php b/api/app/Http/Requests/Api/V1/FormBuilder/UpdateFormFieldRequest.php index 8eb2c565..4a1285d7 100644 --- a/api/app/Http/Requests/Api/V1/FormBuilder/UpdateFormFieldRequest.php +++ b/api/app/Http/Requests/Api/V1/FormBuilder/UpdateFormFieldRequest.php @@ -8,9 +8,11 @@ use App\Enums\FormBuilder\FormFieldDisplayWidth; use App\Enums\FormBuilder\FormFieldType; use App\Enums\FormBuilder\FormValueStorageHint; use App\Exceptions\FormBuilder\InvalidConditionalLogicSpecException; +use App\Exceptions\FormBuilder\InvalidOptionSpecException; use App\Exceptions\FormBuilder\UnknownValidationRuleTypeException; use App\Models\FormBuilder\FormSchema; use App\Services\FormBuilder\FormFieldConditionalLogicService; +use App\Services\FormBuilder\FormFieldOptionService; use App\Services\FormBuilder\FormFieldValidationRuleService; use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; @@ -47,6 +49,12 @@ final class UpdateFormFieldRequest extends FormRequest Rule::exists('form_schema_sections', 'id')->where('form_schema_id', $schemaId), ], 'options' => ['sometimes', 'nullable', 'array'], + 'options.*' => ['array'], + 'options.*.value' => ['required', 'string', 'max:255'], + 'options.*.label' => ['required', 'string', 'max:255'], + 'options.*.sort_order' => ['required', 'integer', 'min:0'], + 'options.*.translations' => ['nullable', 'array'], + 'options.*.translations.*' => ['string', 'max:255'], 'validation_rules' => ['sometimes', 'nullable', 'array'], 'validation_rules.*' => ['array'], 'validation_rules.*.rule_type' => ['required', 'string', 'max:40'], @@ -91,6 +99,20 @@ final class UpdateFormFieldRequest extends FormRequest $validator->errors()->add('validation_rules', $e->getMessage()); } }, + function (Validator $validator): void { + if (! $this->has('options')) { + return; + } + $specs = $this->input('options'); + if (! is_array($specs) || $specs === []) { + return; + } + try { + app(FormFieldOptionService::class)->assertSpecsValid($specs); + } catch (InvalidOptionSpecException $e) { + $validator->errors()->add('options', $e->getMessage()); + } + }, function (Validator $validator): void { if (! $this->has('conditional_logic')) { return; diff --git a/api/app/Http/Resources/FormBuilder/FormFieldLibraryResource.php b/api/app/Http/Resources/FormBuilder/FormFieldLibraryResource.php index 9a68cc6a..8b11ddd1 100644 --- a/api/app/Http/Resources/FormBuilder/FormFieldLibraryResource.php +++ b/api/app/Http/Resources/FormBuilder/FormFieldLibraryResource.php @@ -7,6 +7,7 @@ namespace App\Http\Resources\FormBuilder; use App\Models\FormBuilder\FormFieldLibrary; use App\Services\FormBuilder\FormFieldBindingService; use App\Services\FormBuilder\FormFieldConfigService; +use App\Services\FormBuilder\FormFieldOptionService; use App\Services\FormBuilder\FormFieldValidationRuleService; use Illuminate\Http\Request; use Illuminate\Http\Resources\Json\JsonResource; @@ -21,6 +22,8 @@ final class FormFieldLibraryResource extends JsonResource */ public function toArray(Request $request): array { + $this->resource->loadMissing('options'); + return [ 'id' => $this->id, 'organisation_id' => $this->organisation_id, @@ -29,7 +32,9 @@ final class FormFieldLibraryResource extends JsonResource 'field_type' => $this->field_type, 'label' => $this->label, 'help_text' => $this->help_text, - 'options' => $this->options, + 'options' => $this->resource->options->isNotEmpty() + ? app(FormFieldOptionService::class)->toJsonShape($this->resource->options) + : null, 'validation_rules' => app(FormFieldValidationRuleService::class)->toJsonShape( $this->resource->validationRules, ), diff --git a/api/app/Http/Resources/FormBuilder/FormFieldResource.php b/api/app/Http/Resources/FormBuilder/FormFieldResource.php index 254b8877..dda63ec4 100644 --- a/api/app/Http/Resources/FormBuilder/FormFieldResource.php +++ b/api/app/Http/Resources/FormBuilder/FormFieldResource.php @@ -10,6 +10,7 @@ use App\Models\PersonTag; use App\Services\FormBuilder\FormFieldBindingService; use App\Services\FormBuilder\FormFieldConditionalLogicService; use App\Services\FormBuilder\FormFieldConfigService; +use App\Services\FormBuilder\FormFieldOptionService; use App\Services\FormBuilder\FormFieldValidationRuleService; use App\Services\FormBuilder\FormLocaleResolver; use Illuminate\Http\Request; @@ -29,6 +30,7 @@ final class FormFieldResource extends JsonResource $this->resource->schema, $request->user(), ); + $this->resource->loadMissing('options'); return [ 'id' => $this->id, @@ -40,7 +42,9 @@ final class FormFieldResource extends JsonResource 'label' => $this->resolvedLabel($locale), 'help_text' => $this->resolvedHelpText($locale), 'section' => $this->section, - 'options' => $this->normalizedOptions($locale), + 'options' => $this->resource->options->isNotEmpty() + ? app(FormFieldOptionService::class)->toJsonShape($this->resource->options) + : null, 'available_tags' => $this->when( $this->field_type === FormFieldType::TAG_PICKER->value, fn () => $this->availableTags(), @@ -92,23 +96,6 @@ final class FormFieldResource extends JsonResource return $this->help_text; } - /** - * @return array|null - */ - private function normalizedOptions(string $locale): ?array - { - $options = $this->options; - if (! is_array($options)) { - return null; - } - $translations = $this->translations ?? []; - if (isset($translations[$locale]['options']) && is_array($translations[$locale]['options'])) { - return array_values($translations[$locale]['options']); - } - - return array_values($options); - } - /** * @return array> */ diff --git a/api/app/Http/Resources/FormBuilder/PublicFormSchemaResource.php b/api/app/Http/Resources/FormBuilder/PublicFormSchemaResource.php index d8bac9f9..580911e1 100644 --- a/api/app/Http/Resources/FormBuilder/PublicFormSchemaResource.php +++ b/api/app/Http/Resources/FormBuilder/PublicFormSchemaResource.php @@ -11,6 +11,7 @@ use App\Models\PersonTag; use App\Models\Scopes\OrganisationScope; use App\Services\FormBuilder\FormFieldConditionalLogicService; use App\Services\FormBuilder\FormFieldConfigService; +use App\Services\FormBuilder\FormFieldOptionService; use App\Services\FormBuilder\FormFieldValidationRuleService; use Illuminate\Http\Request; use Illuminate\Http\Resources\Json\JsonResource; @@ -42,6 +43,7 @@ final class PublicFormSchemaResource extends JsonResource 'fields' => fn ($q) => $q->withoutGlobalScope(OrganisationScope::class), 'fields.validationRules', 'fields.configs', + 'fields.options', 'sections' => fn ($q) => $q->withoutGlobalScope(OrganisationScope::class), ]); @@ -80,7 +82,9 @@ final class PublicFormSchemaResource extends JsonResource 'field_type' => $f->field_type, 'label' => $f->label, 'help_text' => $f->help_text, - 'options' => is_array($f->options) ? array_values($f->options) : null, + 'options' => $f->options->isNotEmpty() + ? app(FormFieldOptionService::class)->toJsonShape($f->options) + : null, 'available_tags' => $isTagPicker ? $this->tagsForField($f, $availableTagsByCategory) : null, diff --git a/api/app/Models/FormBuilder/FormField.php b/api/app/Models/FormBuilder/FormField.php index 87fb1d3b..16c131ac 100644 --- a/api/app/Models/FormBuilder/FormField.php +++ b/api/app/Models/FormBuilder/FormField.php @@ -50,7 +50,6 @@ final class FormField extends Model 'label', 'help_text', 'section', - 'options', 'is_required', 'is_filterable', 'is_portal_visible', @@ -67,7 +66,6 @@ final class FormField extends Model /** @var array */ protected $casts = [ - 'options' => 'array', 'role_restrictions' => 'array', 'translations' => 'array', 'is_required' => 'bool', @@ -123,6 +121,28 @@ final class FormField extends Model ->orderBy('sort_order'); } + /** + * Force `$field->options` (no parens) to resolve to the morphMany + * relation rather than the legacy JSON column attribute that lives + * on the table until WS-5d commit 5 drops it. Required because + * Eloquent's getAttribute() prefers the underlying column over a + * relation method when the column still exists. Removed at commit 5 + * along with the column. + * + * @return \Illuminate\Database\Eloquent\Collection + */ + public function getOptionsAttribute(): \Illuminate\Database\Eloquent\Collection + { + if (! $this->relationLoaded('options')) { + $this->load('options'); + } + + /** @var \Illuminate\Database\Eloquent\Collection $relation */ + $relation = $this->getRelation('options'); + + return $relation; + } + public function conditionalLogicGroups(): HasMany { return $this->hasMany(FormFieldConditionalLogicGroup::class, 'form_field_id'); diff --git a/api/app/Models/FormBuilder/FormFieldLibrary.php b/api/app/Models/FormBuilder/FormFieldLibrary.php index d3ce490e..34a05832 100644 --- a/api/app/Models/FormBuilder/FormFieldLibrary.php +++ b/api/app/Models/FormBuilder/FormFieldLibrary.php @@ -34,7 +34,6 @@ final class FormFieldLibrary extends Model 'field_type', 'label', 'help_text', - 'options', 'default_is_required', 'default_is_filterable', 'translations', @@ -44,7 +43,6 @@ final class FormFieldLibrary extends Model /** @var array */ protected $casts = [ - 'options' => 'array', 'translations' => 'array', 'default_is_required' => 'bool', 'default_is_filterable' => 'bool', @@ -83,4 +81,24 @@ final class FormFieldLibrary extends Model return $this->morphMany(FormFieldOption::class, 'owner') ->orderBy('sort_order'); } + + /** + * Force `$library->options` (no parens) to resolve to the morphMany + * relation rather than the legacy JSON column attribute that lives + * on the table until WS-5d commit 5 drops it. Removed at commit 5 + * along with the column. + * + * @return \Illuminate\Database\Eloquent\Collection + */ + public function getOptionsAttribute(): \Illuminate\Database\Eloquent\Collection + { + if (! $this->relationLoaded('options')) { + $this->load('options'); + } + + /** @var \Illuminate\Database\Eloquent\Collection $relation */ + $relation = $this->getRelation('options'); + + return $relation; + } } diff --git a/api/app/Services/FormBuilder/FormFieldRuleBuilder.php b/api/app/Services/FormBuilder/FormFieldRuleBuilder.php index 5d33074f..4f7d6602 100644 --- a/api/app/Services/FormBuilder/FormFieldRuleBuilder.php +++ b/api/app/Services/FormBuilder/FormFieldRuleBuilder.php @@ -168,19 +168,7 @@ final class FormFieldRuleBuilder */ private function scalarOptions(FormField $field): array { - $options = is_array($field->options) ? $field->options : []; - $out = []; - foreach ($options as $opt) { - if (is_scalar($opt)) { - $out[] = (string) $opt; - } elseif (is_array($opt) && isset($opt['value']) && is_scalar($opt['value'])) { - $out[] = (string) $opt['value']; - } elseif (is_array($opt) && isset($opt['label']) && is_scalar($opt['label'])) { - $out[] = (string) $opt['label']; - } - } - - return $out; + return $field->options()->pluck('value')->all(); } /** diff --git a/api/app/Services/FormBuilder/FormFieldService.php b/api/app/Services/FormBuilder/FormFieldService.php index b776cfea..44ad7968 100644 --- a/api/app/Services/FormBuilder/FormFieldService.php +++ b/api/app/Services/FormBuilder/FormFieldService.php @@ -42,6 +42,7 @@ final class FormFieldService $bindingSpec = $this->extractBindingSpec($data); $validationRuleSpecs = $this->extractValidationRuleSpecs($data); + $optionSpecs = $this->extractOptionSpecs($data); [$conditionalTree, $conditionalProvided] = $this->extractConditionalLogicTree($data); /** @var FormField $field */ @@ -55,6 +56,10 @@ final class FormFieldService $this->validationRuleService->replaceRules($field, $validationRuleSpecs); } + if ($optionSpecs !== null) { + $this->optionService->replaceOptions($field, $optionSpecs); + } + if ($conditionalProvided) { // Cycle check runs inside the service — reads the schema's // relational adjacency and throws on a back-edge. @@ -86,10 +91,14 @@ final class FormFieldService $validationRulesProvided = array_key_exists('validation_rules', $data); $validationRuleSpecs = $validationRulesProvided ? $this->extractValidationRuleSpecs($data) : null; + $optionsProvided = array_key_exists('options', $data); + $optionSpecs = $optionsProvided ? $this->extractOptionSpecs($data) : null; + [$conditionalTree, $conditionalProvided] = $this->extractConditionalLogicTree($data); $currentBindingShape = $this->bindingService->toJsonShape($field->bindings()->first()); $currentConditionalShape = $this->conditionalLogicService->toJsonShape($field->rootConditionalLogicGroup()); + $currentOptionsShape = $this->optionService->toJsonShape($field->options()->get()); if ($bindingProvided && $this->bindingChanged($currentBindingShape, $rawBinding)) { $this->assertBindingChangeAllowed($field, $forceBindingChange); @@ -117,6 +126,10 @@ final class FormFieldService $this->validationRuleService->replaceRules($field, $validationRuleSpecs ?? []); } + if ($optionsProvided) { + $this->optionService->replaceOptions($field, $optionSpecs ?? []); + } + if ($conditionalProvided) { $this->conditionalLogicService->replaceLogic($field, $conditionalTree); } @@ -140,6 +153,16 @@ final class FormFieldService $new['conditional_logic'] = $newConditionalShape; } + // §17.6.3 dual emit pattern: include options in the field.updated diff + // only when the option set actually changed (byte-equal JSON compare). + // The semantic field.options_replaced event from + // FormFieldOptionService::replaceOptions stays in addition to this. + $newOptionsShape = $this->optionService->toJsonShape($field->fresh()?->options()->get() ?? collect()); + if (json_encode($currentOptionsShape) !== json_encode($newOptionsShape)) { + $before['options'] = $currentOptionsShape; + $new['options'] = $newOptionsShape; + } + $field->logFieldChange('field.updated', [ 'old' => $before, 'new' => $new, @@ -182,6 +205,31 @@ final class FormFieldService return array_values($raw); } + /** + * Extract the `options` key from the request data array and return + * it as the service-layer spec list. The JSON column is gone post + * WS-5d commit 3 — writes go through + * `FormFieldOptionService::replaceOptions` after the FormField row + * is created/updated. + * + * @param array $data + * @return list>|null + */ + private function extractOptionSpecs(array &$data): ?array + { + if (! array_key_exists('options', $data)) { + return null; + } + $raw = $data['options']; + unset($data['options']); + if (! is_array($raw)) { + return []; + } + + /** @var list> $raw */ + return array_values($raw); + } + /** * @param array $data * @return array{target_entity:string,target_attribute:string,mode:string,sync_direction?:?string}|null diff --git a/api/app/Services/FormBuilder/FormSubmissionService.php b/api/app/Services/FormBuilder/FormSubmissionService.php index 39c13875..e0c05c37 100644 --- a/api/app/Services/FormBuilder/FormSubmissionService.php +++ b/api/app/Services/FormBuilder/FormSubmissionService.php @@ -37,6 +37,7 @@ final class FormSubmissionService private readonly FormFieldValidationRuleService $validationRuleService, private readonly FormFieldConfigService $configService, private readonly FormFieldConditionalLogicService $conditionalLogicService, + private readonly FormFieldOptionService $optionService, ) {} /** @@ -203,7 +204,7 @@ final class FormSubmissionService */ private function buildSnapshot(FormSchema $schema): array { - $schema->loadMissing(['fields.bindings', 'fields.validationRules', 'fields.configs', 'sections']); + $schema->loadMissing(['fields.bindings', 'fields.validationRules', 'fields.configs', 'fields.options', 'sections']); return [ 'schema_version' => $schema->version, @@ -234,7 +235,9 @@ final class FormSubmissionService 'label' => $f->label, 'help_text' => $f->help_text, 'section_slug' => $this->sectionSlug($schema, $f->form_schema_section_id), - 'options' => $f->options, + 'options' => $f->options->isNotEmpty() + ? $this->optionService->toJsonShape($f->options) + : null, 'validation_rules' => $this->validationRuleService->toJsonShape($f->validationRules), 'configs' => $this->configService->toJsonShape($f->configs), 'is_required' => (bool) $f->is_required, @@ -242,13 +245,43 @@ final class FormSubmissionService 'is_pii' => (bool) $f->is_pii, 'binding' => $this->bindingService->toJsonShape($f->bindings->first()), 'conditional_logic' => $this->conditionalLogicService->toJsonShape($f->rootConditionalLogicGroup()), - 'translations' => $f->translations, + 'translations' => $this->stripOptionsFromTranslations($f->translations), 'value_storage_hint' => $f->value_storage_hint instanceof \BackedEnum ? $f->value_storage_hint->value : $f->value_storage_hint, 'sort_order' => $f->sort_order, ])->toArray(), ]; } + /** + * Per-locale `options[]` parallel arrays moved onto each + * form_field_options.translations row in WS-5d. The field's own + * translations bag retains only label/help_text per locale; strip + * any residual options key defensively (commit 2 backfill should + * already have done so on existing rows). + * + * @param mixed $translations + * @return array|null + */ + private function stripOptionsFromTranslations(mixed $translations): ?array + { + if (! is_array($translations) || $translations === []) { + return null; + } + $clean = []; + foreach ($translations as $locale => $bag) { + if (is_array($bag)) { + unset($bag['options']); + if ($bag !== []) { + $clean[$locale] = $bag; + } + } else { + $clean[$locale] = $bag; + } + } + + return $clean === [] ? null : $clean; + } + private function sectionSlug(FormSchema $schema, ?string $sectionId): ?string { if ($sectionId === null) { diff --git a/api/tests/Feature/Api/V1/Public/FormBuilder/PublicFormValidationTest.php b/api/tests/Feature/Api/V1/Public/FormBuilder/PublicFormValidationTest.php index c4a52c86..7edf501d 100644 --- a/api/tests/Feature/Api/V1/Public/FormBuilder/PublicFormValidationTest.php +++ b/api/tests/Feature/Api/V1/Public/FormBuilder/PublicFormValidationTest.php @@ -55,15 +55,16 @@ final class PublicFormValidationTest extends TestCase 'is_required' => false, 'is_portal_visible' => true, ]); - FormField::factory()->create([ - 'form_schema_id' => $this->schema->id, - 'field_type' => FormFieldType::SELECT->value, - 'slug' => 'shirtmaat', - 'label' => 'Shirtmaat', - 'options' => ['S', 'M', 'L'], - 'is_required' => false, - 'is_portal_visible' => true, - ]); + FormField::factory() + ->withOptions(['S', 'M', 'L']) + ->create([ + 'form_schema_id' => $this->schema->id, + 'field_type' => FormFieldType::SELECT->value, + 'slug' => 'shirtmaat', + 'label' => 'Shirtmaat', + 'is_required' => false, + 'is_portal_visible' => true, + ]); } public function test_email_rejects_bad_format(): void diff --git a/api/tests/Feature/FormBuilder/FormFieldApiTest.php b/api/tests/Feature/FormBuilder/FormFieldApiTest.php index 6139b2b5..a146026e 100644 --- a/api/tests/Feature/FormBuilder/FormFieldApiTest.php +++ b/api/tests/Feature/FormBuilder/FormFieldApiTest.php @@ -44,7 +44,12 @@ final class FormFieldApiTest extends TestCase 'field_type' => FormFieldType::SELECT->value, 'slug' => 'shirtmaat', 'label' => 'Shirtmaat', - 'options' => ['XS', 'S', 'M', 'L'], + '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(); diff --git a/api/tests/Feature/FormBuilder/Options/FormFieldOptionsActivityLogTest.php b/api/tests/Feature/FormBuilder/Options/FormFieldOptionsActivityLogTest.php new file mode 100644 index 00000000..bc53e8c1 --- /dev/null +++ b/api/tests/Feature/FormBuilder/Options/FormFieldOptionsActivityLogTest.php @@ -0,0 +1,149 @@ +create(); + $schema = FormSchema::factory()->create(['organisation_id' => $org->id]); + $field = FormField::factory() + ->withOptions(['a', 'b']) + ->create([ + 'form_schema_id' => $schema->id, + 'field_type' => FormFieldType::SELECT->value, + 'slug' => 'colour', + 'label' => 'Colour', + ]); + + // Suppress prior activity (factory creation) and re-bound the + // window for assertion clarity. + Activity::query()->delete(); + + app(FormFieldService::class)->update($field, [ + 'options' => [ + ['value' => 'a', 'label' => 'A', 'sort_order' => 0], + ['value' => 'b', 'label' => 'b', 'sort_order' => 1], + ['value' => 'c', 'label' => 'c', 'sort_order' => 2], + ], + ]); + + $event = Activity::query() + ->where('subject_type', 'form_field') + ->where('subject_id', $field->id) + ->where('description', 'field.updated') + ->first(); + $this->assertNotNull($event); + $payload = $event->properties->toArray(); + $this->assertArrayHasKey('options', $payload['old']); + $this->assertArrayHasKey('options', $payload['new']); + $this->assertSame( + [ + ['value' => 'a', 'label' => 'a', 'sort_order' => 0], + ['value' => 'b', 'label' => 'b', 'sort_order' => 1], + ], + $payload['old']['options'], + ); + $this->assertSame( + [ + ['value' => 'a', 'label' => 'A', 'sort_order' => 0], + ['value' => 'b', 'label' => 'b', 'sort_order' => 1], + ['value' => 'c', 'label' => 'c', 'sort_order' => 2], + ], + $payload['new']['options'], + ); + } + + public function test_field_updated_payload_omits_options_key_when_only_label_changed(): void + { + $org = Organisation::factory()->create(); + $schema = FormSchema::factory()->create(['organisation_id' => $org->id]); + $field = FormField::factory() + ->withOptions(['a', 'b']) + ->create([ + 'form_schema_id' => $schema->id, + 'field_type' => FormFieldType::SELECT->value, + 'slug' => 'choice', + 'label' => 'Old', + ]); + + Activity::query()->delete(); + + app(FormFieldService::class)->update($field, [ + 'label' => 'New', + ]); + + $event = Activity::query() + ->where('subject_type', 'form_field') + ->where('subject_id', $field->id) + ->where('description', 'field.updated') + ->first(); + $this->assertNotNull($event); + $payload = $event->properties->toArray(); + $this->assertArrayNotHasKey('options', $payload['old']); + $this->assertArrayNotHasKey('options', $payload['new']); + } + + public function test_options_replaced_emits_on_form_field_subject(): void + { + $org = Organisation::factory()->create(); + $schema = FormSchema::factory()->create(['organisation_id' => $org->id]); + $field = FormField::factory()->create([ + 'form_schema_id' => $schema->id, + 'field_type' => FormFieldType::SELECT->value, + ]); + + Activity::query()->delete(); + + app(FormFieldOptionService::class)->replaceOptions($field, [ + ['value' => 'x', 'label' => 'X', 'sort_order' => 0], + ]); + + $this->assertNotNull(Activity::query() + ->where('subject_type', 'form_field') + ->where('subject_id', $field->id) + ->where('description', 'field.options_replaced') + ->first()); + } + + public function test_options_replaced_silent_on_library_subject(): void + { + $org = Organisation::factory()->create(); + $library = FormFieldLibrary::factory()->create(['organisation_id' => $org->id]); + + Activity::query()->delete(); + + app(FormFieldOptionService::class)->replaceOptions($library, [ + ['value' => 'x', 'label' => 'X', 'sort_order' => 0], + ]); + + $this->assertNull(Activity::query() + ->where('subject_type', 'form_field_library') + ->where('description', 'field.options_replaced') + ->first()); + } +} diff --git a/api/tests/Feature/FormBuilder/Options/FormFieldOptionsSnapshotAndStrictRequestTest.php b/api/tests/Feature/FormBuilder/Options/FormFieldOptionsSnapshotAndStrictRequestTest.php new file mode 100644 index 00000000..5263add5 --- /dev/null +++ b/api/tests/Feature/FormBuilder/Options/FormFieldOptionsSnapshotAndStrictRequestTest.php @@ -0,0 +1,166 @@ +create(); + $schema = FormSchema::factory()->create([ + 'organisation_id' => $org->id, + 'snapshot_mode' => 'on_submit', + 'is_published' => true, + 'public_token' => (string) \Illuminate\Support\Str::ulid(), + ]); + FormField::factory() + ->withOptions(['XS', 'S', 'M']) + ->create([ + 'form_schema_id' => $schema->id, + 'field_type' => FormFieldType::SELECT->value, + 'slug' => 'shirtmaat', + 'label' => 'Shirtmaat', + ]); + + $service = app(FormSubmissionService::class); + $draft = $service->createDraft($schema, null, null, []); + $service->submit($draft, null); + + $snapshot = $draft->fresh()->schema_snapshot; + $this->assertIsArray($snapshot); + $field = collect($snapshot['fields'])->firstWhere('slug', 'shirtmaat'); + $this->assertSame( + [ + ['value' => 'XS', 'label' => 'XS', 'sort_order' => 0], + ['value' => 'S', 'label' => 'S', 'sort_order' => 1], + ['value' => 'M', 'label' => 'M', 'sort_order' => 2], + ], + $field['options'], + ); + } + + public function test_submission_snapshot_does_not_emit_locale_options_in_field_translations(): void + { + $org = Organisation::factory()->create(); + $schema = FormSchema::factory()->create([ + 'organisation_id' => $org->id, + 'snapshot_mode' => 'on_submit', + 'is_published' => true, + 'public_token' => (string) \Illuminate\Support\Str::ulid(), + ]); + FormField::factory() + ->withOptions([ + ['value' => 'a', 'label' => 'A', 'sort_order' => 0, 'translations' => ['nl' => 'AA']], + ]) + ->create([ + 'form_schema_id' => $schema->id, + 'field_type' => FormFieldType::SELECT->value, + 'slug' => 'choice', + 'label' => 'Choice', + // Per-locale label kept; the legacy {locale}.options[] is + // dead post-WS-5d. + 'translations' => ['nl' => ['label' => 'Keuze']], + ]); + + $service = app(FormSubmissionService::class); + $draft = $service->createDraft($schema, null, null, []); + $service->submit($draft, null); + + $snapshot = $draft->fresh()->schema_snapshot; + $field = collect($snapshot['fields'])->firstWhere('slug', 'choice'); + if (is_array($field['translations'] ?? null)) { + foreach ($field['translations'] as $locale => $bag) { + $this->assertArrayNotHasKey('options', is_array($bag) ? $bag : [], "locale {$locale} kept legacy options key"); + } + } + } + + public function test_form_field_request_rejects_missing_value_in_spec(): void + { + $org = Organisation::factory()->create(); + $admin = \App\Models\User::factory()->create(); + $org->users()->attach($admin, ['role' => 'org_admin']); + $schema = FormSchema::factory()->create(['organisation_id' => $org->id]); + \Laravel\Sanctum\Sanctum::actingAs($admin); + + $response = $this->postJson("/api/v1/organisations/{$org->id}/forms/schemas/{$schema->id}/fields", [ + 'field_type' => FormFieldType::SELECT->value, + 'slug' => 'choice', + 'label' => 'Choice', + 'options' => [ + ['label' => 'A', 'sort_order' => 0], + ], + ]); + + $response->assertStatus(422); + $response->assertJsonValidationErrors(['options.0.value']); + } + + public function test_form_field_request_rejects_duplicate_values_in_spec(): void + { + $org = Organisation::factory()->create(); + $admin = \App\Models\User::factory()->create(); + $org->users()->attach($admin, ['role' => 'org_admin']); + $schema = FormSchema::factory()->create(['organisation_id' => $org->id]); + \Laravel\Sanctum\Sanctum::actingAs($admin); + + $response = $this->postJson("/api/v1/organisations/{$org->id}/forms/schemas/{$schema->id}/fields", [ + 'field_type' => FormFieldType::SELECT->value, + 'slug' => 'choice', + 'label' => 'Choice', + 'options' => [ + ['value' => 'dup', 'label' => 'A', 'sort_order' => 0], + ['value' => 'dup', 'label' => 'B', 'sort_order' => 1], + ], + ]); + + $response->assertStatus(422); + $response->assertJsonValidationErrors(['options']); + } + + public function test_form_field_request_accepts_valid_spec(): void + { + $org = Organisation::factory()->create(); + $admin = \App\Models\User::factory()->create(); + $org->users()->attach($admin, ['role' => 'org_admin']); + $schema = FormSchema::factory()->create(['organisation_id' => $org->id]); + \Laravel\Sanctum\Sanctum::actingAs($admin); + + $response = $this->postJson("/api/v1/organisations/{$org->id}/forms/schemas/{$schema->id}/fields", [ + 'field_type' => FormFieldType::SELECT->value, + 'slug' => 'choice', + 'label' => 'Choice', + 'options' => [ + ['value' => 'red', 'label' => 'Red', 'sort_order' => 0], + ['value' => 'green', 'label' => 'Green', 'sort_order' => 1, 'translations' => ['nl' => 'Groen']], + ], + ]); + + $response->assertCreated(); + $this->assertSame( + [ + ['value' => 'red', 'label' => 'Red', 'sort_order' => 0], + ['value' => 'green', 'label' => 'Green', 'sort_order' => 1, 'translations' => ['nl' => 'Groen']], + ], + $response->json('data.options'), + ); + } +} diff --git a/api/tests/Feature/FormBuilder/Options/FormFieldResourceOptionsTest.php b/api/tests/Feature/FormBuilder/Options/FormFieldResourceOptionsTest.php new file mode 100644 index 00000000..6fb45b4a --- /dev/null +++ b/api/tests/Feature/FormBuilder/Options/FormFieldResourceOptionsTest.php @@ -0,0 +1,126 @@ +create(); + $admin = \App\Models\User::factory()->create(); + $org->users()->attach($admin, ['role' => 'org_admin']); + $schema = FormSchema::factory()->create(['organisation_id' => $org->id]); + FormField::factory() + ->withOptions([ + ['value' => 'red', 'label' => 'Red', 'sort_order' => 0, 'translations' => ['nl' => 'Rood']], + ['value' => 'green', 'label' => 'Green', 'sort_order' => 1], + ]) + ->create([ + 'form_schema_id' => $schema->id, + 'field_type' => FormFieldType::SELECT->value, + 'slug' => 'colour', + 'label' => 'Colour', + ]); + + \Laravel\Sanctum\Sanctum::actingAs($admin); + + $response = $this->getJson("/api/v1/organisations/{$org->id}/forms/schemas/{$schema->id}/fields"); + + $response->assertOk(); + $emitted = collect($response->json('data'))->firstWhere('slug', 'colour'); + $this->assertSame( + [ + ['value' => 'red', 'label' => 'Red', 'sort_order' => 0, 'translations' => ['nl' => 'Rood']], + ['value' => 'green', 'label' => 'Green', 'sort_order' => 1], + ], + $emitted['options'], + ); + } + + public function test_form_field_resource_emits_null_options_for_option_less_field_type(): void + { + $org = Organisation::factory()->create(); + $admin = \App\Models\User::factory()->create(); + $org->users()->attach($admin, ['role' => 'org_admin']); + $schema = FormSchema::factory()->create(['organisation_id' => $org->id]); + FormField::factory()->create([ + 'form_schema_id' => $schema->id, + 'field_type' => FormFieldType::TEXT->value, + 'slug' => 'name', + 'label' => 'Name', + ]); + + \Laravel\Sanctum\Sanctum::actingAs($admin); + + $response = $this->getJson("/api/v1/organisations/{$org->id}/forms/schemas/{$schema->id}/fields"); + + $response->assertOk(); + $emitted = collect($response->json('data'))->firstWhere('slug', 'name'); + $this->assertNull($emitted['options']); + } + + public function test_library_resource_emits_rich_shape_options(): void + { + $org = Organisation::factory()->create(); + $admin = \App\Models\User::factory()->create(); + $org->users()->attach($admin, ['role' => 'org_admin']); + $library = FormFieldLibrary::factory() + ->withOptions(['a', 'b']) + ->create(['organisation_id' => $org->id]); + + \Laravel\Sanctum\Sanctum::actingAs($admin); + + $response = $this->getJson("/api/v1/organisations/{$org->id}/forms/field-library/{$library->id}"); + + $response->assertOk(); + $this->assertSame( + [ + ['value' => 'a', 'label' => 'a', 'sort_order' => 0], + ['value' => 'b', 'label' => 'b', 'sort_order' => 1], + ], + $response->json('data.options'), + ); + } + + public function test_to_json_shape_is_byte_equal_to_resource_output(): void + { + $org = Organisation::factory()->create(); + $schema = FormSchema::factory()->create(['organisation_id' => $org->id]); + $field = FormField::factory() + ->withOptions(['x', 'y', 'z']) + ->create([ + 'form_schema_id' => $schema->id, + 'field_type' => FormFieldType::RADIO->value, + ]); + + $service = app(FormFieldOptionService::class); + $shape = $service->toJsonShape($service->optionsFor($field)); + + $this->assertSame( + [ + ['value' => 'x', 'label' => 'x', 'sort_order' => 0], + ['value' => 'y', 'label' => 'y', 'sort_order' => 1], + ['value' => 'z', 'label' => 'z', 'sort_order' => 2], + ], + $shape, + ); + } +}