Files
crewli/api/app/Models/FormBuilder/FormField.php
bert.hausmans bb9242fd6e refactor(form-field): resources + snapshot + validator read form_field_options
Atomic reader switch. All call paths that previously read
form_fields.options / form_field_library.options from the JSON column
now read through FormFieldOptionService::toJsonShape() via the
morphMany relation:

  - FormFieldResource + FormFieldLibraryResource +
    PublicFormSchemaResource emit the rich-shape array
  - FilterRegistryController emits rich shape uniformly (no flat-array
    carve-out for filter-UI compatibility — preflight scan confirmed
    zero portal/app consumers, S5 territory)
  - FormFieldRuleBuilder plucks values from the relation for in:options
    rule construction
  - FormSubmissionService::buildSnapshot writes rich-shape options into
    snapshots and strips translations.{locale}.options from each field's
    translations bag (defensive — commit 2 backfill already did the
    bulk strip)
  - Four FormFieldRequest variants accept array-of-spec-objects,
    validate shape in after() via FormFieldOptionService::assertSpecsValid,
    and hand off to FormFieldOptionService::replaceOptions for writes
  - FormFieldService::create + update extract option specs from the
    request data and route through the service after the FormField row
    is persisted

FormField and FormFieldLibrary $casts no longer include 'options'; the
JSON column is no longer cast. Options removed from $fillable on both
models so ::create() / ::fill() / mass assignment can no longer touch
the legacy column. Both models gain a getOptionsAttribute() accessor
that resolves $model->options to the eager-loaded morphMany collection
— required because Eloquent's getAttribute() prefers a real DB column
over a relation method, and the JSON column lives on the table until
WS-5d commit 5 drops it.

Activity log — dual emit per §6.7 / §17.4.2 / §17.6.3:
  - field.updated carries old.options / new.options diff via
    toJsonShape() reconstruction, byte-equal JSON compare to avoid
    cosmetic false positives. Field updates that don't touch options
    omit the key entirely
  - field.options_replaced emits inside replaceOptions() on FormField
    subject only; library subject writes silent (mirrors the WS-5b /
    WS-5c convention)

JSON columns (form_fields.options, form_field_library.options) remain
present but unread — column drops land atomically in commit 5.

Two pre-existing test fixtures that seeded options via the JSON column
(FormFieldApiTest + PublicFormValidationTest) migrated to the
spec-array path: FormField::factory()->withOptions([...]) where the
options live on the field, or explicit spec-array request bodies for
HTTP tests.

Tests: 1193 → 1206 green (+13 tests / +28 assertions).

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

187 lines
5.9 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');
}
/**
* 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<int, FormFieldOption>
*/
public function getOptionsAttribute(): \Illuminate\Database\Eloquent\Collection
{
if (! $this->relationLoaded('options')) {
$this->load('options');
}
/** @var \Illuminate\Database\Eloquent\Collection<int, FormFieldOption> $relation */
$relation = $this->getRelation('options');
return $relation;
}
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);
}
}