Files
crewli/api/app/Models/FormBuilder/FormField.php
bert.hausmans e7c9482474 refactor(form-field): drop form_fields.options + form_field_library.options
Final WS-5d cleanup. The JSON columns that have been unread since
commit 3 are now physically dropped on both source tables. Their
canonical rich-shape lives in form_field_options, accessed
exclusively through the morphMany relation.

Defensive sweep: any lingering translations.{locale}.options key in
either source table's translations bag is stripped. Commit 2's
backfill should already have done so exhaustively; this is
belt-and-braces.

Rollback re-creates the columns as nullable JSON but leaves them
empty. Pair with commit 2's rollback to restore the pre-WS-5d data
shape on every owner row.

The commit-3 getOptionsAttribute accessor-bridge on FormField +
FormFieldLibrary is removed — Eloquent's getAttribute() resolution
now naturally falls through to the morphMany relation since there's
no underlying column to shadow it. New regression test
FormFieldOptionsAccessTest asserts $field->options resolves to an
Eloquent Collection of FormFieldOption instances and lazy-loads in
exactly 2 queries (1 parent + 1 lazy-load options) on a fresh fetch
without with() preload. Same trio for FormFieldLibrary.

Migration step-count tests in WS-5a/b/c bumped by 1 to account for
the new drop_form_field_options_json_columns migration on the
rollback stack.

Documentation:
  - SCHEMA.md v2.6: form_field_options table documented; options row
    removed from form_fields and form_field_library; morphMany
    relations updated; cross-references to ARCH-FORM-BUILDER §17.6
    and addendum §Q3 WS-5d Uitvoering added on both source-table
    docblocks.
  - ARCH-FORM-BUILDER.md v1.8: new §17.6 "Field options (relational)"
    mirrors the §17.4 / §17.5 relational-sibling structure with
    sub-sections 17.6.1 rationale, 17.6.2 table + catalogue, 17.6.3
    service / scope / cascade / activity log, 17.6.4 snapshot
    embedding, 17.6.5 external API contract. Existing Webhooks
    section renumbered from §17.6 to §17.7.
  - ARCH-CONSOLIDATION-ADDENDUM-2026-04-24.md: "Uitvoering — WS-5d
    (2026-04-27)" section added. Eight paragraphs covering the
    snapshot atomic rewrite, strict-fail backfill dispatch, dual
    activity-log emit, four-sibling base-class extraction warrant,
    commit 0 dead-code precondition, the temporary getOptionsAttribute
    accessor-bridge pattern (with reusability note for future
    JSON→relational refactors), the dev-seeder vergoedingstype RADIO
    normalisation (drift correction explicitly distinguished from the
    parallel apps/app RegistrationFieldTemplate description domain),
    and the WS-5 family completion note.
  - BACKLOG.md: FORM-BUILDER-LIBRARY-AUDIT-LOG entry extended to four
    services (adds library.options_replaced); new
    FORM-BUILDER-MORPH-SCOPE-BASE-CLASS entry added as the WS-5d
    follow-up now that all four concrete morph-scope siblings exist.

Tests: 1193 → 1208 green (+15 across commits 3+4+5; this commit alone:
+2 from the regression test).

This completes the WS-5 family.

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

165 lines
5.0 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Models\FormBuilder;
use App\Enums\FormBuilder\FormFieldDisplayWidth;
use App\Enums\FormBuilder\FormValueStorageHint;
use App\Models\Scopes\OrganisationScope;
use Illuminate\Database\Eloquent\Concerns\HasUlids;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Database\Eloquent\SoftDeletes;
/**
* Activity log strategy: explicit calls via logFieldChange() — no LogsActivity
* trait. Logged events: create/delete/restore, field_type change, binding
* change, is_pii/is_filterable toggle, structural options change.
* See ARCH-FORM-BUILDER.md §17.1 and S1 Phase 4b.
*
* field_type is stored as string (not DB enum) so CustomFieldTypeRegistry
* (ARCH §17.2) can extend it at runtime.
*/
final class FormField extends Model
{
use HasFactory;
use HasUlids;
use SoftDeletes;
protected static function booted(): void
{
static::addGlobalScope(new OrganisationScope());
}
/** @return array{via: class-string, fk: string} */
public static function tenantScopeStrategy(): array
{
return ['via' => FormSchema::class, 'fk' => 'form_schema_id'];
}
protected $fillable = [
'form_schema_id',
'form_schema_section_id',
'library_field_id',
'field_type',
'slug',
'label',
'help_text',
'section',
'is_required',
'is_filterable',
'is_portal_visible',
'is_admin_only',
'is_unique',
'is_pii',
'display_width',
'role_restrictions',
'translations',
'value_storage_hint',
'review_required',
'sort_order',
];
/** @var array<string, string> */
protected $casts = [
'role_restrictions' => 'array',
'translations' => 'array',
'is_required' => 'bool',
'is_filterable' => 'bool',
'is_portal_visible' => 'bool',
'is_admin_only' => 'bool',
'is_unique' => 'bool',
'is_pii' => 'bool',
'review_required' => 'bool',
'display_width' => FormFieldDisplayWidth::class,
'value_storage_hint' => FormValueStorageHint::class,
'sort_order' => 'int',
];
public function schema(): BelongsTo
{
return $this->belongsTo(FormSchema::class, 'form_schema_id');
}
public function section(): BelongsTo
{
return $this->belongsTo(FormSchemaSection::class, 'form_schema_section_id');
}
public function libraryField(): BelongsTo
{
return $this->belongsTo(FormFieldLibrary::class, 'library_field_id');
}
public function values(): HasMany
{
return $this->hasMany(FormValue::class);
}
public function bindings(): MorphMany
{
return $this->morphMany(FormFieldBinding::class, 'owner');
}
public function validationRules(): MorphMany
{
return $this->morphMany(FormFieldValidationRule::class, 'owner');
}
public function configs(): MorphMany
{
return $this->morphMany(FormFieldConfig::class, 'owner');
}
public function options(): MorphMany
{
return $this->morphMany(FormFieldOption::class, 'owner')
->orderBy('sort_order');
}
public function conditionalLogicGroups(): HasMany
{
return $this->hasMany(FormFieldConditionalLogicGroup::class, 'form_field_id');
}
/**
* The tree root: the group with `parent_group_id IS NULL`. Fields
* without any conditional logic return null. Only one root is
* supported per field — enforced by the service layer's `replaceLogic`.
*/
public function rootConditionalLogicGroup(): ?FormFieldConditionalLogicGroup
{
return $this->conditionalLogicGroups()
->whereNull('parent_group_id')
->first();
}
/**
* Nuanced activity log (ARCH §17.1; S1 Phase 4b). Callers choose which
* events are worth logging — e.g. created/deleted/restored, field_type
* changed (value storage changes), binding changed, is_pii toggled,
* is_filterable toggled (triggers backfill), structural options changes.
* Conditional-logic changes emit `field.conditional_logic_replaced`
* via FormFieldConditionalLogicService (ARCH §8; WS-5c commit 2).
* NOT logged (noise): label/help_text/sort_order/translations.
*
* Bulk-fixture suppression: the activitylog.enabled config key is the
* kill-switch. Seeders and one-shot commands wrap themselves in
* App\Support\ActivityLog::suppressed(...). activity()->log() becomes
* a silent no-op while disabled, so no guard is needed here.
*
* @param array<string, mixed> $properties
*/
public function logFieldChange(string $event, array $properties = []): void
{
activity()
->performedOn($this)
->withProperties($properties)
->log($event);
}
}