feat(form-builder): form_field_configs relational table + non-validation key split + drop validation_rules JSON columns

This commit is contained in:
2026-04-24 22:42:35 +02:00
parent 9d2758a42c
commit d494478c08
31 changed files with 1233 additions and 60 deletions

View File

@@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
namespace App\Enums\FormBuilder;
/**
* Non-validation field configuration (ARCH-FORM-BUILDER §17.5). Tag
* picker option filtering + upload disk selection live here because
* they are per-field rendering / storage configuration, not validation
* rules splitting them out of `form_field_validation_rules` preserves
* the semantic integrity of that table's name (strict-enterprise
* decision on WS-5b, addendum Q3 Uitvoering).
*
* Per-case parameter shape is enforced at the service layer
* (`FormFieldConfigService::assertSpecValid`), not in the enum or DB.
*/
enum FormFieldConfigType: string
{
case TagCategories = 'tag_categories';
case StorageDisk = 'storage_disk';
}

View File

@@ -6,6 +6,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\FormFieldValidationRuleService;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
@@ -32,6 +33,9 @@ final class FormFieldLibraryResource extends JsonResource
'validation_rules' => app(FormFieldValidationRuleService::class)->toJsonShape(
$this->resource->validationRules,
),
'configs' => app(FormFieldConfigService::class)->toJsonShape(
$this->resource->configs,
),
'default_is_required' => (bool) $this->default_is_required,
'default_is_filterable' => (bool) $this->default_is_filterable,
'default_binding' => app(FormFieldBindingService::class)->toJsonShape(

View File

@@ -8,6 +8,7 @@ use App\Enums\FormBuilder\FormFieldType;
use App\Models\FormBuilder\FormField;
use App\Models\PersonTag;
use App\Services\FormBuilder\FormFieldBindingService;
use App\Services\FormBuilder\FormFieldConfigService;
use App\Services\FormBuilder\FormFieldValidationRuleService;
use App\Services\FormBuilder\FormLocaleResolver;
use Illuminate\Http\Request;
@@ -46,6 +47,9 @@ final class FormFieldResource extends JsonResource
'validation_rules' => app(FormFieldValidationRuleService::class)->toJsonShape(
$this->resource->validationRules,
),
'configs' => app(FormFieldConfigService::class)->toJsonShape(
$this->resource->configs,
),
'is_required' => (bool) $this->is_required,
'is_filterable' => (bool) $this->is_filterable,
'is_portal_visible' => (bool) $this->is_portal_visible,
@@ -112,7 +116,8 @@ final class FormFieldResource extends JsonResource
return [];
}
$categoryFilter = (array) (($this->validation_rules['tag_categories'] ?? null) ?: []);
$configs = app(FormFieldConfigService::class)->toJsonShape($this->resource->configs);
$categoryFilter = (array) ($configs['tag_categories']['categories'] ?? []);
$query = PersonTag::withoutGlobalScopes()
->where('organisation_id', $organisationId)

View File

@@ -9,6 +9,7 @@ use App\Models\FormBuilder\FormField;
use App\Models\FormBuilder\FormSchema;
use App\Models\PersonTag;
use App\Models\Scopes\OrganisationScope;
use App\Services\FormBuilder\FormFieldConfigService;
use App\Services\FormBuilder\FormFieldValidationRuleService;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
@@ -39,6 +40,7 @@ final class PublicFormSchemaResource extends JsonResource
$this->resource->loadMissing([
'fields' => fn ($q) => $q->withoutGlobalScope(OrganisationScope::class),
'fields.validationRules',
'fields.configs',
'sections' => fn ($q) => $q->withoutGlobalScope(OrganisationScope::class),
]);
@@ -84,6 +86,7 @@ final class PublicFormSchemaResource extends JsonResource
'validation_rules' => app(FormFieldValidationRuleService::class)->toJsonShape(
$f->validationRules,
),
'configs' => app(FormFieldConfigService::class)->toJsonShape($f->configs),
'is_required' => (bool) $f->is_required,
'display_width' => $f->display_width instanceof \BackedEnum ? $f->display_width->value : $f->display_width,
'conditional_logic' => $f->conditional_logic,
@@ -141,7 +144,8 @@ final class PublicFormSchemaResource extends JsonResource
*/
private function tagsForField(FormField $field, array $byCategory): array
{
$filter = (array) (($field->validation_rules['tag_categories'] ?? null) ?: []);
$configs = app(FormFieldConfigService::class)->toJsonShape($field->configs);
$filter = (array) ($configs['tag_categories']['categories'] ?? []);
if ($filter === []) {
$out = [];

View File

@@ -51,7 +51,6 @@ final class FormField extends Model
'help_text',
'section',
'options',
'validation_rules',
'is_required',
'is_filterable',
'is_portal_visible',
@@ -70,7 +69,6 @@ final class FormField extends Model
/** @var array<string, string> */
protected $casts = [
'options' => 'array',
'validation_rules' => 'array',
'conditional_logic' => 'array',
'role_restrictions' => 'array',
'translations' => 'array',
@@ -116,6 +114,11 @@ final class FormField extends Model
return $this->morphMany(FormFieldValidationRule::class, 'owner');
}
public function configs(): MorphMany
{
return $this->morphMany(FormFieldConfig::class, 'owner');
}
/**
* Nuanced activity log (ARCH §17.1; S1 Phase 4b). Callers choose which
* events are worth logging e.g. created/deleted/restored, field_type

View File

@@ -0,0 +1,52 @@
<?php
declare(strict_types=1);
namespace App\Models\FormBuilder;
use App\Enums\FormBuilder\FormFieldConfigType;
use App\Models\Scopes\FormFieldConfigScope;
use Illuminate\Database\Eloquent\Concerns\HasUlids;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphTo;
/**
* Relational home for non-validation field configuration. See
* ARCH-FORM-BUILDER §17.5 and ARCH-CONSOLIDATION-ADDENDUM-2026-04-24
* §Q3 WS-5b Uitvoering.
*
* Polymorphic owner (`form_field` / `form_field_library` aliases, reused
* from WS-5a). One row per (owner, config_type). Parameter shape
* validated at the service layer.
*/
final class FormFieldConfig extends Model
{
use HasFactory;
use HasUlids;
protected $table = 'form_field_configs';
protected static function booted(): void
{
static::addGlobalScope(new FormFieldConfigScope());
}
protected $fillable = [
'owner_type',
'owner_id',
'config_type',
'parameters',
];
/** @var array<string, string> */
protected $casts = [
'config_type' => FormFieldConfigType::class,
'parameters' => 'array',
];
public function owner(): MorphTo
{
return $this->morphTo('owner', 'owner_type', 'owner_id');
}
}

View File

@@ -35,7 +35,6 @@ final class FormFieldLibrary extends Model
'label',
'help_text',
'options',
'validation_rules',
'default_is_required',
'default_is_filterable',
'translations',
@@ -46,7 +45,6 @@ final class FormFieldLibrary extends Model
/** @var array<string, string> */
protected $casts = [
'options' => 'array',
'validation_rules' => 'array',
'translations' => 'array',
'default_is_required' => 'bool',
'default_is_filterable' => 'bool',
@@ -74,4 +72,9 @@ final class FormFieldLibrary extends Model
{
return $this->morphMany(FormFieldValidationRule::class, 'owner');
}
public function configs(): MorphMany
{
return $this->morphMany(FormFieldConfig::class, 'owner');
}
}

View File

@@ -0,0 +1,102 @@
<?php
declare(strict_types=1);
namespace App\Models\Scopes;
use App\Models\FormBuilder\FormField;
use App\Models\FormBuilder\FormFieldLibrary;
use App\Models\FormBuilder\FormSchema;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;
/**
* Third sibling in the form-field-child-table scope family, after
* `FormFieldBindingScope` (WS-5a) and `FormFieldValidationRuleScope`
* (WS-5b commit 1). Identical UNION-over-two-owner-chains shape:
*
* owner_id (
* SELECT id FROM form_fields
* WHERE form_schema_id (SELECT id FROM form_schemas WHERE organisation_id = ?)
* UNION
* SELECT id FROM form_field_library
* WHERE organisation_id = ?
* )
*
* Base-class extraction between the three siblings is deliberately
* deferred to WS-5d (where `form_field_options` lands and the fourth
* concrete implementation may clarify what truly varies). Premature
* abstraction from three is still premature.
*/
final class FormFieldConfigScope implements Scope
{
public function __construct(
private readonly ?string $organisationId = null,
) {}
public function apply(Builder $builder, Model $model): void
{
$orgId = $this->resolveOrganisationId();
if ($orgId === null) {
return;
}
$fieldIds = FormField::query()
->withoutGlobalScope(OrganisationScope::class)
->whereIn(
'form_schema_id',
FormSchema::query()
->withoutGlobalScope(OrganisationScope::class)
->where('organisation_id', $orgId)
->select('id'),
)
->select('id');
$libraryIds = FormFieldLibrary::query()
->withoutGlobalScope(OrganisationScope::class)
->where('organisation_id', $orgId)
->select('id');
$table = $model->getTable();
$builder->where(function (Builder $outer) use ($table, $fieldIds, $libraryIds): void {
$outer->where(function (Builder $q) use ($table, $fieldIds): void {
$q->where("$table.owner_type", 'form_field')
->whereIn("$table.owner_id", $fieldIds);
})->orWhere(function (Builder $q) use ($table, $libraryIds): void {
$q->where("$table.owner_type", 'form_field_library')
->whereIn("$table.owner_id", $libraryIds);
});
});
}
private function resolveOrganisationId(): ?string
{
if ($this->organisationId !== null) {
return $this->organisationId;
}
$route = request()->route();
if ($route === null) {
return null;
}
$org = $route->parameter('organisation');
if ($org instanceof \App\Models\Organisation) {
return $org->id;
}
if (is_string($org) && $org !== '') {
return $org;
}
$event = $route->parameter('event');
if ($event instanceof \App\Models\Event) {
return $event->organisation_id;
}
return null;
}
}

View File

@@ -45,5 +45,12 @@ final class FormFieldChildTablesCascadeObserver
->where('owner_id', $ownerId)
->delete();
}
if (Schema::hasTable('form_field_configs')) {
DB::table('form_field_configs')
->where('owner_type', $ownerType)
->where('owner_id', $ownerId)
->delete();
}
}
}

View File

@@ -0,0 +1,187 @@
<?php
declare(strict_types=1);
namespace App\Services\FormBuilder;
use App\Enums\FormBuilder\FormFieldConfigType;
use App\Exceptions\FormBuilder\UnknownValidationRuleTypeException;
use App\Models\FormBuilder\FormField;
use App\Models\FormBuilder\FormFieldConfig;
use App\Models\FormBuilder\FormFieldLibrary;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
/**
* Owns writes to `form_field_configs` non-validation per-field
* configuration (ARCH-FORM-BUILDER §17.5; addendum Q3 WS-5b Uitvoering).
*
* Mirrors `FormFieldValidationRuleService` exactly: same service-layer
* contract (`configsFor`, `replaceConfigs`, `copyConfigs`,
* `toJsonShape`, `assertSpecsValid`), same activity-log convention
* (emit `field.configs_replaced` on FormField only, silent for library
* matches §6.7 WS-5a pattern).
*
* Re-uses the `UnknownValidationRuleTypeException` for parameter-shape
* violations; the two services share a failure mode (caller supplied a
* spec that does not match the registered type's schema) and adding a
* second exception class for the same semantic would be noise.
*/
final class FormFieldConfigService
{
/**
* @return Collection<int, FormFieldConfig>
*/
public function configsFor(FormField|FormFieldLibrary $owner): Collection
{
$type = $this->ownerTypeFor($owner);
return FormFieldConfig::query()
->where('owner_type', $type)
->where('owner_id', $owner->getKey())
->get();
}
/**
* @param list<array{config_type:string,parameters?:array<string,mixed>}> $specs
*/
public function replaceConfigs(FormField|FormFieldLibrary $owner, array $specs): void
{
$this->assertSpecsValid($specs);
$ownerType = $this->ownerTypeFor($owner);
DB::transaction(function () use ($owner, $ownerType, $specs): void {
FormFieldConfig::query()
->withoutGlobalScopes()
->where('owner_type', $ownerType)
->where('owner_id', $owner->getKey())
->delete();
foreach ($specs as $spec) {
FormFieldConfig::query()->withoutGlobalScopes()->create([
'owner_type' => $ownerType,
'owner_id' => $owner->getKey(),
'config_type' => $spec['config_type'],
'parameters' => $spec['parameters'] ?? [],
]);
}
if ($owner instanceof FormField) {
$owner->logFieldChange('field.configs_replaced', [
'count' => count($specs),
]);
}
});
}
public function copyConfigs(FormFieldLibrary $from, FormField $to): void
{
$configs = $this->configsFor($from);
if ($configs->isEmpty()) {
return;
}
DB::transaction(function () use ($configs, $to): void {
foreach ($configs as $config) {
FormFieldConfig::query()->withoutGlobalScopes()->create([
'owner_type' => 'form_field',
'owner_id' => $to->id,
'config_type' => $config->config_type instanceof FormFieldConfigType
? $config->config_type->value
: (string) $config->config_type,
'parameters' => (array) $config->parameters,
]);
}
});
}
/**
* Serialise a config collection into the nested-object JSON shape
* consumed by snapshot writer and API resources. Returns `null` on
* empty (matches the contract pattern WS-5b introduced on the
* validation-rules service).
*
* Shape per config_type:
* - tag_categories `{"categories": [string]}`
* - storage_disk `{"disk": string}`
*
* The external envelope is `{<config_type>: <parameters>}`:
* `{"tag_categories": {"categories": ["Veiligheid"]},
* "storage_disk": {"disk": "local"}}`
*
* @param Collection<int, FormFieldConfig> $configs
* @return array<string, array<string, mixed>>|null
*/
public function toJsonShape(Collection $configs): ?array
{
if ($configs->isEmpty()) {
return null;
}
$out = [];
foreach ($configs as $config) {
$type = $config->config_type instanceof FormFieldConfigType
? $config->config_type->value
: (string) $config->config_type;
$out[$type] = (array) $config->parameters;
}
return $out;
}
/** @param list<array<string, mixed>> $specs */
public function assertSpecsValid(array $specs): void
{
foreach ($specs as $spec) {
$this->assertSpecValid($spec);
}
}
private function ownerTypeFor(FormField|FormFieldLibrary $owner): string
{
return $owner instanceof FormField ? 'form_field' : 'form_field_library';
}
/** @param array<string, mixed> $spec */
private function assertSpecValid(array $spec): void
{
$raw = (string) ($spec['config_type'] ?? '');
$enum = FormFieldConfigType::tryFrom($raw);
if ($enum === null) {
throw new UnknownValidationRuleTypeException(
"Config config_type '{$raw}' is not a registered FormFieldConfigType case.",
);
}
$params = (array) ($spec['parameters'] ?? []);
switch ($enum) {
case FormFieldConfigType::TagCategories:
if (! isset($params['categories']) || ! is_array($params['categories'])) {
throw new UnknownValidationRuleTypeException(
"Config 'tag_categories' requires parameters.categories (array of strings).",
);
}
foreach ($params['categories'] as $cat) {
if (! is_string($cat) || $cat === '') {
throw new UnknownValidationRuleTypeException(
"Config 'tag_categories' parameters.categories must be non-empty strings.",
);
}
}
return;
case FormFieldConfigType::StorageDisk:
if (! isset($params['disk']) || ! is_string($params['disk']) || $params['disk'] === '') {
throw new UnknownValidationRuleTypeException(
"Config 'storage_disk' requires non-empty string parameters.disk.",
);
}
return;
}
}
}

View File

@@ -28,6 +28,7 @@ final class FormFieldService
private readonly FormSchemaService $schemaService,
private readonly FormFieldBindingService $bindingService,
private readonly FormFieldValidationRuleService $validationRuleService,
private readonly FormFieldConfigService $configService,
) {}
public function create(FormSchema $schema, array $data): FormField
@@ -242,7 +243,6 @@ final class FormFieldService
'label' => $library->label,
'help_text' => $library->help_text,
'options' => $library->options,
'validation_rules' => $library->validation_rules,
'is_required' => (bool) $library->default_is_required,
'is_filterable' => (bool) $library->default_is_filterable,
'translations' => $library->translations,
@@ -260,6 +260,7 @@ final class FormFieldService
$this->bindingService->copyBindings($library, $field);
$this->validationRuleService->copyRules($library, $field);
$this->configService->copyConfigs($library, $field);
FormFieldLibrary::query()->whereKey($library->id)->increment('usage_count');

View File

@@ -35,6 +35,7 @@ final class FormSubmissionService
private readonly FormValueService $valueService,
private readonly FormFieldBindingService $bindingService,
private readonly FormFieldValidationRuleService $validationRuleService,
private readonly FormFieldConfigService $configService,
) {}
/**
@@ -201,7 +202,7 @@ final class FormSubmissionService
*/
private function buildSnapshot(FormSchema $schema): array
{
$schema->loadMissing(['fields.bindings', 'fields.validationRules', 'sections']);
$schema->loadMissing(['fields.bindings', 'fields.validationRules', 'fields.configs', 'sections']);
return [
'schema_version' => $schema->version,
@@ -234,6 +235,7 @@ final class FormSubmissionService
'section_slug' => $this->sectionSlug($schema, $f->form_schema_section_id),
'options' => $f->options,
'validation_rules' => $this->validationRuleService->toJsonShape($f->validationRules),
'configs' => $this->configService->toJsonShape($f->configs),
'is_required' => (bool) $f->is_required,
'is_filterable' => (bool) $f->is_filterable,
'is_pii' => (bool) $f->is_pii,