feat(form-builder): form_field_configs relational table + non-validation key split + drop validation_rules JSON columns
This commit is contained in:
22
api/app/Enums/FormBuilder/FormFieldConfigType.php
Normal file
22
api/app/Enums/FormBuilder/FormFieldConfigType.php
Normal 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';
|
||||
}
|
||||
@@ -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(
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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 = [];
|
||||
|
||||
@@ -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
|
||||
|
||||
52
api/app/Models/FormBuilder/FormFieldConfig.php
Normal file
52
api/app/Models/FormBuilder/FormFieldConfig.php
Normal 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');
|
||||
}
|
||||
}
|
||||
@@ -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');
|
||||
}
|
||||
}
|
||||
|
||||
102
api/app/Models/Scopes/FormFieldConfigScope.php
Normal file
102
api/app/Models/Scopes/FormFieldConfigScope.php
Normal 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;
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
187
api/app/Services/FormBuilder/FormFieldConfigService.php
Normal file
187
api/app/Services/FormBuilder/FormFieldConfigService.php
Normal 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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');
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database\Factories\FormBuilder;
|
||||
|
||||
use App\Enums\FormBuilder\FormFieldConfigType;
|
||||
use App\Models\FormBuilder\FormField;
|
||||
use App\Models\FormBuilder\FormFieldConfig;
|
||||
use App\Models\FormBuilder\FormFieldLibrary;
|
||||
use Illuminate\Database\Eloquent\Factories\Factory;
|
||||
|
||||
/** @extends Factory<FormFieldConfig> */
|
||||
final class FormFieldConfigFactory extends Factory
|
||||
{
|
||||
protected $model = FormFieldConfig::class;
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
public function definition(): array
|
||||
{
|
||||
return [
|
||||
'owner_type' => 'form_field',
|
||||
'owner_id' => FormField::factory(),
|
||||
'config_type' => FormFieldConfigType::TagCategories->value,
|
||||
'parameters' => ['categories' => ['Veiligheid']],
|
||||
];
|
||||
}
|
||||
|
||||
public function forField(FormField $field): static
|
||||
{
|
||||
return $this->state(fn () => [
|
||||
'owner_type' => 'form_field',
|
||||
'owner_id' => $field->id,
|
||||
]);
|
||||
}
|
||||
|
||||
public function forLibrary(FormFieldLibrary $library): static
|
||||
{
|
||||
return $this->state(fn () => [
|
||||
'owner_type' => 'form_field_library',
|
||||
'owner_id' => $library->id,
|
||||
]);
|
||||
}
|
||||
|
||||
/** @param array<string, mixed> $parameters */
|
||||
public function ofType(FormFieldConfigType $type, array $parameters): static
|
||||
{
|
||||
return $this->state(fn () => [
|
||||
'config_type' => $type->value,
|
||||
'parameters' => $parameters,
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -47,7 +47,6 @@ final class FormFieldFactory extends Factory
|
||||
'options' => $fieldType === FormFieldType::SELECT
|
||||
? ['Optie A', 'Optie B', 'Optie C']
|
||||
: null,
|
||||
'validation_rules' => null,
|
||||
'is_required' => fake()->boolean(40),
|
||||
'is_filterable' => false,
|
||||
'is_portal_visible' => true,
|
||||
|
||||
@@ -35,7 +35,6 @@ final class FormFieldLibraryFactory extends Factory
|
||||
'label' => fake('nl_NL')->words(2, true),
|
||||
'help_text' => null,
|
||||
'options' => null,
|
||||
'validation_rules' => null,
|
||||
'default_is_required' => false,
|
||||
'default_is_filterable' => false,
|
||||
'translations' => null,
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
/**
|
||||
* WS-5b commit 5 of 5 — parallel relational table to
|
||||
* `form_field_validation_rules` that holds non-validation field
|
||||
* configuration (tag_categories, storage_disk). Same polymorphic
|
||||
* owner pattern; semantically distinct concern (ARCH-FORM-BUILDER
|
||||
* §17.5; addendum Q3 WS-5b Uitvoering).
|
||||
*/
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('form_field_configs', function (Blueprint $table) {
|
||||
$table->ulid('id')->primary();
|
||||
$table->string('owner_type', 40);
|
||||
$table->ulid('owner_id');
|
||||
$table->string('config_type', 40);
|
||||
$table->json('parameters');
|
||||
$table->timestamps();
|
||||
|
||||
$table->unique(
|
||||
['owner_type', 'owner_id', 'config_type'],
|
||||
'ffc_owner_config_unique',
|
||||
);
|
||||
$table->index('config_type', 'ffc_config_idx');
|
||||
$table->index(['owner_type', 'owner_id'], 'ffc_owner_idx');
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('form_field_configs');
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,148 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use App\Enums\FormBuilder\FormFieldConfigType;
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
/**
|
||||
* WS-5b commit 5 — translates the non-validation keys that WS-5b
|
||||
* commit 2's backfill deliberately skipped (`tag_categories`,
|
||||
* `storage_disk`) into rows in `form_field_configs`.
|
||||
*
|
||||
* Reads from the pre-drop JSON columns (`form_fields.validation_rules`,
|
||||
* `form_field_library.validation_rules`). The sibling drop-migration
|
||||
* (`2026_04_25_120002`) runs after this one; rolling back WS-5b
|
||||
* commits 1–5 as a unit reconstructs source JSON on the source tables
|
||||
* using canonical keys before the table is dropped.
|
||||
*/
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
DB::transaction(function (): void {
|
||||
$this->backfill('form_fields', 'form_field');
|
||||
$this->backfill('form_field_library', 'form_field_library');
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
if (! Schema::hasTable('form_field_configs')) {
|
||||
return;
|
||||
}
|
||||
|
||||
DB::transaction(function (): void {
|
||||
$this->reconstructJson('form_fields', 'form_field');
|
||||
$this->reconstructJson('form_field_library', 'form_field_library');
|
||||
});
|
||||
}
|
||||
|
||||
private function backfill(string $table, string $ownerType): void
|
||||
{
|
||||
if (! Schema::hasTable($table) || ! Schema::hasColumn($table, 'validation_rules')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$rows = DB::table($table)
|
||||
->whereNotNull('validation_rules')
|
||||
->orderBy('id')
|
||||
->get(['id', 'validation_rules']);
|
||||
|
||||
if ($rows->isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$now = now();
|
||||
$inserts = [];
|
||||
|
||||
foreach ($rows as $row) {
|
||||
$decoded = is_string($row->validation_rules)
|
||||
? json_decode((string) $row->validation_rules, true)
|
||||
: $row->validation_rules;
|
||||
if (! is_array($decoded) || $decoded === []) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (isset($decoded['tag_categories']) && is_array($decoded['tag_categories'])) {
|
||||
$inserts[] = [
|
||||
'id' => (string) Str::ulid(),
|
||||
'owner_type' => $ownerType,
|
||||
'owner_id' => (string) $row->id,
|
||||
'config_type' => FormFieldConfigType::TagCategories->value,
|
||||
'parameters' => json_encode([
|
||||
'categories' => array_values(array_map(
|
||||
static fn ($c): string => (string) $c,
|
||||
$decoded['tag_categories'],
|
||||
)),
|
||||
]),
|
||||
'created_at' => $now,
|
||||
'updated_at' => $now,
|
||||
];
|
||||
}
|
||||
|
||||
if (isset($decoded['storage_disk']) && is_string($decoded['storage_disk']) && $decoded['storage_disk'] !== '') {
|
||||
$inserts[] = [
|
||||
'id' => (string) Str::ulid(),
|
||||
'owner_type' => $ownerType,
|
||||
'owner_id' => (string) $row->id,
|
||||
'config_type' => FormFieldConfigType::StorageDisk->value,
|
||||
'parameters' => json_encode(['disk' => $decoded['storage_disk']]),
|
||||
'created_at' => $now,
|
||||
'updated_at' => $now,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
if ($inserts === []) {
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (array_chunk($inserts, 500) as $batch) {
|
||||
DB::table('form_field_configs')->insert($batch);
|
||||
}
|
||||
}
|
||||
|
||||
private function reconstructJson(string $table, string $ownerType): void
|
||||
{
|
||||
if (! Schema::hasTable($table) || ! Schema::hasColumn($table, 'validation_rules')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$rows = DB::table('form_field_configs')
|
||||
->where('owner_type', $ownerType)
|
||||
->orderBy('owner_id')
|
||||
->get();
|
||||
|
||||
if ($rows->isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$grouped = [];
|
||||
foreach ($rows as $row) {
|
||||
$ownerId = (string) $row->owner_id;
|
||||
$grouped[$ownerId] ??= [];
|
||||
$params = json_decode((string) $row->parameters, true);
|
||||
$params = is_array($params) ? $params : [];
|
||||
|
||||
if ($row->config_type === FormFieldConfigType::TagCategories->value) {
|
||||
$grouped[$ownerId]['tag_categories'] = $params['categories'] ?? [];
|
||||
} elseif ($row->config_type === FormFieldConfigType::StorageDisk->value) {
|
||||
$grouped[$ownerId]['storage_disk'] = $params['disk'] ?? '';
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($grouped as $ownerId => $configs) {
|
||||
$existing = DB::table($table)->where('id', $ownerId)->value('validation_rules');
|
||||
$existingBag = is_string($existing) ? (json_decode($existing, true) ?: []) : [];
|
||||
$merged = array_merge(is_array($existingBag) ? $existingBag : [], $configs);
|
||||
|
||||
DB::table($table)->where('id', $ownerId)->update([
|
||||
'validation_rules' => json_encode($merged),
|
||||
]);
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
/**
|
||||
* WS-5b commit 5 — drops the `validation_rules` JSON columns on
|
||||
* `form_fields` and `form_field_library`. By this point both WS-5b
|
||||
* backfills (validation-rules in commit 2, configs in commit 5) have
|
||||
* populated their respective relational tables from the source JSON.
|
||||
*
|
||||
* Rollback re-adds the columns as `json nullable` **without** backfilling
|
||||
* — the rollback path is "roll back WS-5b commits 1–5 together". After
|
||||
* this migration's `down()` the two backfill migrations' `down()` hooks
|
||||
* reconstruct the source JSON bags.
|
||||
*/
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
if (Schema::hasColumn('form_fields', 'validation_rules')) {
|
||||
Schema::table('form_fields', function (Blueprint $table): void {
|
||||
$table->dropColumn('validation_rules');
|
||||
});
|
||||
}
|
||||
if (Schema::hasColumn('form_field_library', 'validation_rules')) {
|
||||
Schema::table('form_field_library', function (Blueprint $table): void {
|
||||
$table->dropColumn('validation_rules');
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
if (! Schema::hasColumn('form_fields', 'validation_rules')) {
|
||||
Schema::table('form_fields', function (Blueprint $table): void {
|
||||
$table->json('validation_rules')->nullable()->after('options');
|
||||
});
|
||||
}
|
||||
if (! Schema::hasColumn('form_field_library', 'validation_rules')) {
|
||||
Schema::table('form_field_library', function (Blueprint $table): void {
|
||||
$table->json('validation_rules')->nullable()->after('options');
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -284,10 +284,9 @@ final class FormBuilderDevSeeder
|
||||
'type' => FormFieldType::TAG_PICKER,
|
||||
'slug' => 'vaardigheden',
|
||||
'label' => 'Vaardigheden en certificaten',
|
||||
// validation_rules.tag_categories = [] means "all active
|
||||
// person_tags for this org" — the FormFieldResource picks
|
||||
// up every active tag when no category filter is set.
|
||||
'validation_rules' => null,
|
||||
// No config_type = tag_categories row → FormFieldResource
|
||||
// emits every active person_tag for the org (no category
|
||||
// filter). See ARCH-FORM-BUILDER §17.5.
|
||||
'is_required' => false,
|
||||
'is_filterable' => true,
|
||||
'display_width' => 'full',
|
||||
@@ -370,7 +369,6 @@ final class FormBuilderDevSeeder
|
||||
'label' => $def['label'],
|
||||
'help_text' => $def['help_text'] ?? null,
|
||||
'options' => $def['options'] ?? null,
|
||||
'validation_rules' => $def['validation_rules'] ?? null,
|
||||
'is_required' => $def['is_required'] ?? false,
|
||||
'is_filterable' => $def['is_filterable'] ?? false,
|
||||
'is_portal_visible' => true,
|
||||
|
||||
@@ -4,9 +4,11 @@ declare(strict_types=1);
|
||||
|
||||
namespace Tests\Feature\Api\V1\Public\FormBuilder;
|
||||
|
||||
use App\Enums\FormBuilder\FormFieldConfigType;
|
||||
use App\Enums\FormBuilder\FormFieldType;
|
||||
use App\Enums\FormBuilder\FormPurpose;
|
||||
use App\Models\FormBuilder\FormField;
|
||||
use App\Models\FormBuilder\FormFieldConfig;
|
||||
use App\Models\FormBuilder\FormSchema;
|
||||
use App\Models\Organisation;
|
||||
use App\Models\PersonTag;
|
||||
@@ -63,13 +65,15 @@ final class PublicFormSchemaResourceTest extends TestCase
|
||||
'is_published' => true,
|
||||
'public_token' => (string) Str::ulid(),
|
||||
]);
|
||||
FormField::factory()->create([
|
||||
$field = FormField::factory()->create([
|
||||
'form_schema_id' => $schema->id,
|
||||
'field_type' => FormFieldType::TAG_PICKER->value,
|
||||
'slug' => 'veiligheid',
|
||||
'validation_rules' => ['tag_categories' => ['Veiligheid']],
|
||||
'is_portal_visible' => true,
|
||||
]);
|
||||
FormFieldConfig::factory()->forField($field)
|
||||
->ofType(FormFieldConfigType::TagCategories, ['categories' => ['Veiligheid']])
|
||||
->create();
|
||||
|
||||
$response = $this->getJson("/api/v1/public/forms/{$schema->public_token}");
|
||||
$field = collect($response->json('data.fields'))->firstWhere('slug', 'veiligheid');
|
||||
|
||||
@@ -33,10 +33,11 @@ final class FormFieldBindingMigrationTest extends TestCase
|
||||
|
||||
public function test_forward_migrations_backfill_rows_from_both_json_sources(): void
|
||||
{
|
||||
// Roll back, newest first: backfill_form_field_validation_rules
|
||||
// → create_form_field_validation_rules_table (both WS-5b commit 1+2)
|
||||
// → drop_binding_json_columns → create_form_field_bindings.
|
||||
$this->artisan('migrate:rollback', ['--step' => 4])->assertSuccessful();
|
||||
// Roll back to pre-WS-5a state: 5 WS-5b migrations
|
||||
// (drop-validation-cols, configs-backfill, create-configs,
|
||||
// validation-rules-backfill, create-validation-rules) +
|
||||
// 2 WS-5a migrations (drop-binding-cols, create-bindings) = 7.
|
||||
$this->artisan('migrate:rollback', ['--step' => 7])->assertSuccessful();
|
||||
$this->assertFalse(Schema::hasTable('form_field_bindings'));
|
||||
$this->assertTrue(Schema::hasColumn('form_fields', 'binding'));
|
||||
$this->assertTrue(Schema::hasColumn('form_field_library', 'default_binding'));
|
||||
@@ -97,23 +98,24 @@ final class FormFieldBindingMigrationTest extends TestCase
|
||||
|
||||
public function test_rollback_reconstructs_json_and_drops_table(): void
|
||||
{
|
||||
// Walk back the full WS-5b + WS-5a stack: backfill (validation rules)
|
||||
// → create (validation rules table) → drop (binding columns) →
|
||||
// create (bindings table).
|
||||
$this->artisan('migrate:rollback', ['--step' => 4])->assertSuccessful();
|
||||
// Walk back the full WS-5b + WS-5a stack (7 migrations).
|
||||
$this->artisan('migrate:rollback', ['--step' => 7])->assertSuccessful();
|
||||
[$fieldAId, , ] = $this->seedFieldsWithBindingJson();
|
||||
[$libAId, ] = $this->seedLibraryWithBindingJson();
|
||||
|
||||
$this->artisan('migrate')->assertSuccessful();
|
||||
|
||||
// Fully-forward state: columns gone, rows in form_field_bindings.
|
||||
// Fully-forward state: binding columns gone, rows in form_field_bindings.
|
||||
$this->assertFalse(Schema::hasColumn('form_fields', 'binding'));
|
||||
$this->assertSame(5, DB::table('form_field_bindings')->count());
|
||||
|
||||
// Step back over the two WS-5b migrations → restores the pre-WS-5b
|
||||
// state (validation-rules table gone; binding contract intact).
|
||||
$this->artisan('migrate:rollback', ['--step' => 2])->assertSuccessful();
|
||||
// Step back over all five WS-5b migrations in one go → restores the
|
||||
// pre-WS-5b state (validation-rules and configs tables gone,
|
||||
// validation_rules JSON columns reappear on source tables; binding
|
||||
// contract intact).
|
||||
$this->artisan('migrate:rollback', ['--step' => 5])->assertSuccessful();
|
||||
$this->assertFalse(Schema::hasTable('form_field_validation_rules'));
|
||||
$this->assertFalse(Schema::hasTable('form_field_configs'));
|
||||
$this->assertTrue(Schema::hasTable('form_field_bindings'));
|
||||
|
||||
// Step back over drop_binding_json_columns → columns reappear empty.
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tests\Feature\FormBuilder\Configs;
|
||||
|
||||
use App\Models\FormBuilder\FormSchema;
|
||||
use App\Models\Organisation;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Str;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* WS-5b commit 5 — verifies the configs backfill + column drop pair.
|
||||
*
|
||||
* - `tag_categories` + `storage_disk` keys in the pre-WS-5b JSON bag
|
||||
* become rows in `form_field_configs` (not in
|
||||
* `form_field_validation_rules`).
|
||||
* - After the full forward-migration, `form_fields.validation_rules`
|
||||
* and `form_field_library.validation_rules` columns are gone.
|
||||
*/
|
||||
final class FormFieldConfigBackfillAndDropTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
public function test_backfill_translates_tag_categories_and_storage_disk(): void
|
||||
{
|
||||
// Roll back 5 WS-5b migrations to get the pre-WS-5b state where
|
||||
// the JSON column still exists on form_fields / form_field_library.
|
||||
$this->artisan('migrate:rollback', ['--step' => 5])->assertSuccessful();
|
||||
$this->assertTrue(Schema::hasColumn('form_fields', 'validation_rules'));
|
||||
|
||||
$fieldId = $this->seedField([
|
||||
'field_type' => 'TAG_PICKER',
|
||||
'validation_rules' => [
|
||||
'tag_categories' => ['Veiligheid', 'Horeca'],
|
||||
'storage_disk' => 's3',
|
||||
],
|
||||
]);
|
||||
|
||||
$this->artisan('migrate')->assertSuccessful();
|
||||
|
||||
$rows = DB::table('form_field_configs')
|
||||
->where('owner_id', $fieldId)
|
||||
->get()->keyBy('config_type');
|
||||
|
||||
$this->assertTrue($rows->has('tag_categories'));
|
||||
$this->assertSame(
|
||||
['Veiligheid', 'Horeca'],
|
||||
json_decode((string) $rows['tag_categories']->parameters, true)['categories'],
|
||||
);
|
||||
$this->assertTrue($rows->has('storage_disk'));
|
||||
$this->assertSame(
|
||||
's3',
|
||||
json_decode((string) $rows['storage_disk']->parameters, true)['disk'],
|
||||
);
|
||||
}
|
||||
|
||||
public function test_validation_rules_json_columns_are_dropped_after_migrations(): void
|
||||
{
|
||||
// Default state after RefreshDatabase: full migration applied.
|
||||
$this->assertFalse(Schema::hasColumn('form_fields', 'validation_rules'));
|
||||
$this->assertFalse(Schema::hasColumn('form_field_library', 'validation_rules'));
|
||||
}
|
||||
|
||||
public function test_cascade_observer_cleans_up_configs_on_owner_delete(): void
|
||||
{
|
||||
// Integration-level: confirms the renamed cascade observer covers
|
||||
// the configs table too.
|
||||
$org = Organisation::factory()->create();
|
||||
$schema = FormSchema::factory()->create(['organisation_id' => $org->id]);
|
||||
$field = \App\Models\FormBuilder\FormField::factory()->create(['form_schema_id' => $schema->id]);
|
||||
\App\Models\FormBuilder\FormFieldConfig::factory()->forField($field)->create();
|
||||
|
||||
$this->assertSame(1, \App\Models\FormBuilder\FormFieldConfig::query()
|
||||
->withoutGlobalScopes()
|
||||
->where('owner_id', $field->id)
|
||||
->count());
|
||||
|
||||
$field->delete();
|
||||
|
||||
$this->assertSame(0, \App\Models\FormBuilder\FormFieldConfig::query()
|
||||
->withoutGlobalScopes()
|
||||
->where('owner_id', $field->id)
|
||||
->count());
|
||||
}
|
||||
|
||||
/** @param array<string, mixed> $attrs */
|
||||
private function seedField(array $attrs): string
|
||||
{
|
||||
$org = Organisation::factory()->create();
|
||||
$schema = FormSchema::factory()->create(['organisation_id' => $org->id]);
|
||||
|
||||
$id = (string) Str::ulid();
|
||||
DB::table('form_fields')->insert([[
|
||||
'id' => $id,
|
||||
'form_schema_id' => $schema->id,
|
||||
'field_type' => $attrs['field_type'],
|
||||
'slug' => 'f-'.Str::lower(Str::random(4)),
|
||||
'label' => 'field',
|
||||
'validation_rules' => json_encode($attrs['validation_rules']),
|
||||
'value_storage_hint' => 'json',
|
||||
'sort_order' => 0,
|
||||
'created_at' => now(),
|
||||
'updated_at' => now(),
|
||||
]]);
|
||||
|
||||
return $id;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tests\Feature\FormBuilder\Configs;
|
||||
|
||||
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 App\Models\FormBuilder\FormSchema;
|
||||
use App\Models\Organisation;
|
||||
use App\Models\Scopes\FormFieldConfigScope;
|
||||
use App\Services\FormBuilder\FormFieldConfigService;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Routing\Route;
|
||||
use Spatie\Activitylog\Models\Activity;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* Consolidated coverage for `form_field_configs` — relation round-trip,
|
||||
* scope isolation, cascade, and service-layer contract (replace, copy,
|
||||
* toJsonShape). Mirrors the structure of the validation-rules test suite.
|
||||
*/
|
||||
final class FormFieldConfigServiceAndScopeTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
public function test_field_morph_many_configs_and_owner_morphto_roundtrip(): void
|
||||
{
|
||||
$org = Organisation::factory()->create();
|
||||
$schema = FormSchema::factory()->create(['organisation_id' => $org->id]);
|
||||
$field = FormField::factory()->create(['form_schema_id' => $schema->id]);
|
||||
|
||||
FormFieldConfig::factory()->forField($field)
|
||||
->ofType(FormFieldConfigType::TagCategories, ['categories' => ['Veiligheid']])->create();
|
||||
FormFieldConfig::factory()->forField($field)
|
||||
->ofType(FormFieldConfigType::StorageDisk, ['disk' => 'local'])->create();
|
||||
|
||||
$configs = $field->fresh()->configs;
|
||||
$this->assertCount(2, $configs);
|
||||
$first = $configs->firstWhere('config_type', FormFieldConfigType::TagCategories);
|
||||
$this->assertSame(FormField::class, $first->fresh()->owner::class);
|
||||
}
|
||||
|
||||
public function test_scope_isolates_configs_per_organisation_both_owner_types(): void
|
||||
{
|
||||
[$orgA, $fieldA, $libraryA] = $this->seedOrgWithConfigs();
|
||||
[$orgB, $fieldB, $libraryB] = $this->seedOrgWithConfigs();
|
||||
|
||||
$this->withOrgRoute($orgA);
|
||||
$ids = FormFieldConfig::query()->pluck('owner_id')->sort()->values()->all();
|
||||
$expected = collect([$fieldA->id, $libraryA->id])->sort()->values()->all();
|
||||
$this->assertSame($expected, $ids);
|
||||
|
||||
// Escape hatch.
|
||||
$this->assertSame(
|
||||
4,
|
||||
FormFieldConfig::query()->withoutGlobalScope(FormFieldConfigScope::class)->count(),
|
||||
);
|
||||
$this->assertSame(2, FormFieldConfig::query()->count());
|
||||
}
|
||||
|
||||
public function test_cascade_deletes_configs_on_owner_delete(): void
|
||||
{
|
||||
$org = Organisation::factory()->create();
|
||||
$schema = FormSchema::factory()->create(['organisation_id' => $org->id]);
|
||||
$field = FormField::factory()->create(['form_schema_id' => $schema->id]);
|
||||
FormFieldConfig::factory()->forField($field)->create();
|
||||
|
||||
$this->assertSame(1, FormFieldConfig::query()->withoutGlobalScopes()
|
||||
->where('owner_id', $field->id)->count());
|
||||
|
||||
$field->delete();
|
||||
$this->assertSame(0, FormFieldConfig::query()->withoutGlobalScopes()
|
||||
->where('owner_id', $field->id)->count());
|
||||
}
|
||||
|
||||
public function test_replace_configs_enum_and_parameter_shape_enforced(): void
|
||||
{
|
||||
$org = Organisation::factory()->create();
|
||||
$schema = FormSchema::factory()->create(['organisation_id' => $org->id]);
|
||||
$field = FormField::factory()->create(['form_schema_id' => $schema->id]);
|
||||
$service = app(FormFieldConfigService::class);
|
||||
|
||||
$this->expectException(UnknownValidationRuleTypeException::class);
|
||||
$service->replaceConfigs($field, [
|
||||
['config_type' => 'not_a_thing', 'parameters' => []],
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_replace_configs_rejects_bad_tag_categories_shape(): void
|
||||
{
|
||||
$org = Organisation::factory()->create();
|
||||
$schema = FormSchema::factory()->create(['organisation_id' => $org->id]);
|
||||
$field = FormField::factory()->create(['form_schema_id' => $schema->id]);
|
||||
$service = app(FormFieldConfigService::class);
|
||||
|
||||
$this->expectException(UnknownValidationRuleTypeException::class);
|
||||
$service->replaceConfigs($field, [
|
||||
['config_type' => 'tag_categories', 'parameters' => ['categories' => 'not-an-array']],
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_replace_configs_emits_activity_log_on_field_only(): void
|
||||
{
|
||||
$org = Organisation::factory()->create();
|
||||
$schema = FormSchema::factory()->create(['organisation_id' => $org->id]);
|
||||
$field = FormField::factory()->create(['form_schema_id' => $schema->id]);
|
||||
$library = FormFieldLibrary::factory()->create(['organisation_id' => $org->id]);
|
||||
$service = app(FormFieldConfigService::class);
|
||||
|
||||
$service->replaceConfigs($field, [
|
||||
['config_type' => 'storage_disk', 'parameters' => ['disk' => 's3']],
|
||||
]);
|
||||
$service->replaceConfigs($library, [
|
||||
['config_type' => 'storage_disk', 'parameters' => ['disk' => 'local']],
|
||||
]);
|
||||
|
||||
$this->assertNotNull(Activity::query()
|
||||
->where('subject_type', 'form_field')
|
||||
->where('subject_id', $field->id)
|
||||
->where('description', 'field.configs_replaced')
|
||||
->first());
|
||||
$this->assertNull(Activity::query()
|
||||
->where('subject_type', 'form_field_library')
|
||||
->where('description', 'field.configs_replaced')
|
||||
->first());
|
||||
}
|
||||
|
||||
public function test_copy_configs_clones_every_row(): void
|
||||
{
|
||||
$org = Organisation::factory()->create();
|
||||
$library = FormFieldLibrary::factory()->create(['organisation_id' => $org->id]);
|
||||
FormFieldConfig::factory()->forLibrary($library)
|
||||
->ofType(FormFieldConfigType::TagCategories, ['categories' => ['Horeca']])->create();
|
||||
FormFieldConfig::factory()->forLibrary($library)
|
||||
->ofType(FormFieldConfigType::StorageDisk, ['disk' => 'local'])->create();
|
||||
$schema = FormSchema::factory()->create(['organisation_id' => $org->id]);
|
||||
$field = FormField::factory()->create(['form_schema_id' => $schema->id]);
|
||||
|
||||
app(FormFieldConfigService::class)->copyConfigs($library, $field);
|
||||
|
||||
$configs = FormFieldConfig::query()->where('owner_id', $field->id)->get();
|
||||
$this->assertCount(2, $configs);
|
||||
}
|
||||
|
||||
public function test_to_json_shape_nested_object_envelope(): void
|
||||
{
|
||||
$org = Organisation::factory()->create();
|
||||
$schema = FormSchema::factory()->create(['organisation_id' => $org->id]);
|
||||
$field = FormField::factory()->create(['form_schema_id' => $schema->id]);
|
||||
FormFieldConfig::factory()->forField($field)
|
||||
->ofType(FormFieldConfigType::TagCategories, ['categories' => ['Veiligheid']])->create();
|
||||
FormFieldConfig::factory()->forField($field)
|
||||
->ofType(FormFieldConfigType::StorageDisk, ['disk' => 's3'])->create();
|
||||
|
||||
$shape = app(FormFieldConfigService::class)->toJsonShape($field->fresh()->configs);
|
||||
$this->assertSame(['categories' => ['Veiligheid']], $shape['tag_categories']);
|
||||
$this->assertSame(['disk' => 's3'], $shape['storage_disk']);
|
||||
}
|
||||
|
||||
/** @return array{0:Organisation,1:FormField,2:FormFieldLibrary} */
|
||||
private function seedOrgWithConfigs(): array
|
||||
{
|
||||
$org = Organisation::factory()->create();
|
||||
$schema = FormSchema::factory()->create(['organisation_id' => $org->id]);
|
||||
$field = FormField::factory()->create(['form_schema_id' => $schema->id]);
|
||||
$library = FormFieldLibrary::factory()->create(['organisation_id' => $org->id]);
|
||||
FormFieldConfig::factory()->forField($field)->create();
|
||||
FormFieldConfig::factory()->forLibrary($library)->create();
|
||||
|
||||
return [$org, $field, $library];
|
||||
}
|
||||
|
||||
private function withOrgRoute(Organisation $org): void
|
||||
{
|
||||
$route = new Route(['GET'], '/_test', static fn () => null);
|
||||
$route->bind(request());
|
||||
$route->setParameter('organisation', $org);
|
||||
request()->setRouteResolver(static fn () => $route);
|
||||
}
|
||||
}
|
||||
@@ -34,7 +34,11 @@ final class FormFieldValidationRuleBackfillTest extends TestCase
|
||||
// Roll back: backfill + create-table. Brings us to a state where
|
||||
// form_fields.validation_rules exists but form_field_validation_rules
|
||||
// table does not.
|
||||
$this->artisan('migrate:rollback', ['--step' => 2])->assertSuccessful();
|
||||
// Roll back all WS-5b migrations to reach the pre-WS-5b state
|
||||
// (validation_rules JSON column present; no relational tables for
|
||||
// WS-5b). Step count: drop-cols + configs-backfill + create-configs
|
||||
// + validation-rules-backfill + create-validation-rules = 5.
|
||||
$this->artisan('migrate:rollback', ['--step' => 5])->assertSuccessful();
|
||||
$this->assertFalse(Schema::hasTable('form_field_validation_rules'));
|
||||
$this->assertTrue(Schema::hasColumn('form_fields', 'validation_rules'));
|
||||
|
||||
@@ -91,7 +95,11 @@ final class FormFieldValidationRuleBackfillTest extends TestCase
|
||||
|
||||
public function test_tag_categories_and_storage_disk_skipped_for_commit_5(): void
|
||||
{
|
||||
$this->artisan('migrate:rollback', ['--step' => 2])->assertSuccessful();
|
||||
// Roll back all WS-5b migrations to reach the pre-WS-5b state
|
||||
// (validation_rules JSON column present; no relational tables for
|
||||
// WS-5b). Step count: drop-cols + configs-backfill + create-configs
|
||||
// + validation-rules-backfill + create-validation-rules = 5.
|
||||
$this->artisan('migrate:rollback', ['--step' => 5])->assertSuccessful();
|
||||
|
||||
$fieldId = $this->seedFieldWithJson([
|
||||
'field_type' => 'TAG_PICKER',
|
||||
@@ -111,7 +119,11 @@ final class FormFieldValidationRuleBackfillTest extends TestCase
|
||||
|
||||
public function test_required_and_unique_skipped_with_warn(): void
|
||||
{
|
||||
$this->artisan('migrate:rollback', ['--step' => 2])->assertSuccessful();
|
||||
// Roll back all WS-5b migrations to reach the pre-WS-5b state
|
||||
// (validation_rules JSON column present; no relational tables for
|
||||
// WS-5b). Step count: drop-cols + configs-backfill + create-configs
|
||||
// + validation-rules-backfill + create-validation-rules = 5.
|
||||
$this->artisan('migrate:rollback', ['--step' => 5])->assertSuccessful();
|
||||
|
||||
$fieldId = $this->seedFieldWithJson([
|
||||
'field_type' => 'TEXT',
|
||||
@@ -134,7 +146,11 @@ final class FormFieldValidationRuleBackfillTest extends TestCase
|
||||
|
||||
public function test_unknown_top_level_key_fails_migration(): void
|
||||
{
|
||||
$this->artisan('migrate:rollback', ['--step' => 2])->assertSuccessful();
|
||||
// Roll back all WS-5b migrations to reach the pre-WS-5b state
|
||||
// (validation_rules JSON column present; no relational tables for
|
||||
// WS-5b). Step count: drop-cols + configs-backfill + create-configs
|
||||
// + validation-rules-backfill + create-validation-rules = 5.
|
||||
$this->artisan('migrate:rollback', ['--step' => 5])->assertSuccessful();
|
||||
|
||||
$this->seedFieldWithJson([
|
||||
'field_type' => 'TEXT',
|
||||
@@ -147,7 +163,11 @@ final class FormFieldValidationRuleBackfillTest extends TestCase
|
||||
|
||||
public function test_unmapped_field_type_for_min_max_fails_migration(): void
|
||||
{
|
||||
$this->artisan('migrate:rollback', ['--step' => 2])->assertSuccessful();
|
||||
// Roll back all WS-5b migrations to reach the pre-WS-5b state
|
||||
// (validation_rules JSON column present; no relational tables for
|
||||
// WS-5b). Step count: drop-cols + configs-backfill + create-configs
|
||||
// + validation-rules-backfill + create-validation-rules = 5.
|
||||
$this->artisan('migrate:rollback', ['--step' => 5])->assertSuccessful();
|
||||
|
||||
$this->seedFieldWithJson([
|
||||
'field_type' => 'BOOLEAN',
|
||||
@@ -158,22 +178,34 @@ final class FormFieldValidationRuleBackfillTest extends TestCase
|
||||
$this->artisan('migrate');
|
||||
}
|
||||
|
||||
public function test_rollback_reconstructs_canonical_json_on_source_tables(): void
|
||||
public function test_full_wsb_rollback_reconstructs_source_state(): void
|
||||
{
|
||||
$this->artisan('migrate:rollback', ['--step' => 2])->assertSuccessful();
|
||||
// Architect contract: "the forward+back pair is safe when run as a
|
||||
// unit; a partial 'rollback this migration but not its create-table
|
||||
// sibling' state is not supported." This test exercises the
|
||||
// full-back-then-full-forward cycle — rolling back all WS-5b
|
||||
// migrations restores the pre-WS-5b state (columns present on
|
||||
// source tables; validation rules relational table gone).
|
||||
$this->artisan('migrate:rollback', ['--step' => 5])->assertSuccessful();
|
||||
[$numberId] = $this->seedFields();
|
||||
|
||||
$this->artisan('migrate')->assertSuccessful();
|
||||
// Post-migration: rows exist, column dropped.
|
||||
$this->assertSame(
|
||||
2,
|
||||
DB::table('form_field_validation_rules')
|
||||
->where('owner_id', $numberId)
|
||||
->count(),
|
||||
);
|
||||
$this->assertFalse(Schema::hasColumn('form_fields', 'validation_rules'));
|
||||
|
||||
$this->artisan('migrate:rollback', ['--step' => 1])->assertSuccessful();
|
||||
// Only the backfill rolled back — the create-table migration still
|
||||
// applied, so rows remain accessible (until we step back once more).
|
||||
$this->assertTrue(Schema::hasTable('form_field_validation_rules'));
|
||||
// Roll back WS-5b fully → column reappears and carries canonical JSON
|
||||
// reconstructed from the relational rows.
|
||||
$this->artisan('migrate:rollback', ['--step' => 5])->assertSuccessful();
|
||||
$this->assertTrue(Schema::hasColumn('form_fields', 'validation_rules'));
|
||||
|
||||
$field = DB::table('form_fields')->where('id', $numberId)->first();
|
||||
$decoded = json_decode((string) $field->validation_rules, true);
|
||||
// Rollback reconstructs using canonical keys — the legacy `min`/`max`
|
||||
// are intentionally NOT resurrected (post-rename semantic).
|
||||
$this->assertSame(16, $decoded['min_value']);
|
||||
$this->assertSame(99, $decoded['max_value']);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user