feat(form-builder): form_field_bindings table + polymorphic owner + cascade observer

WS-5a commit 1 of 4 per ARCH-CONSOLIDATION-ADDENDUM-2026-04-24 Q3.

Creates the relational home for what was form_fields.binding JSON and
form_field_library.default_binding JSON. Owner discriminator is polymorphic
morph (owner_type/owner_id) — the pattern the rest of WS-5 (5b validation_rules,
5d options) will reuse.

Migration backfills rows from both JSON sources in a single transaction and
is genuinely reversible (rollback reconstructs the JSON). Old columns remain
in place until commit 3 has switched all readers.

Pattern B (binding=null) is represented by absence of row. mode enum covers
entity_owned / mirrored only.

Cascade on owner delete via observer — bindings are physical state, not
historical audit. FormFieldBindingScope enforces multi-tenancy via UNION over
both owner chains (form_field → schema → org OR form_field_library → org) —
Q2's declarative tenantScopeStrategy() can't walk morph parents.

Tests: migration forward/back, morph relation, cascade observer, scope
isolation, enum coverage.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-04-24 18:43:11 +02:00
parent 76090b934e
commit af8a9da038
17 changed files with 1081 additions and 0 deletions

View File

@@ -0,0 +1,13 @@
<?php
declare(strict_types=1);
namespace App\Enums\FormBuilder;
enum FormFieldBindingMergeStrategy: string
{
case Overwrite = 'overwrite';
case Append = 'append';
case Replace = 'replace';
case FirstWriteWins = 'first_write_wins';
}

View File

@@ -0,0 +1,11 @@
<?php
declare(strict_types=1);
namespace App\Enums\FormBuilder;
enum FormFieldBindingMode: string
{
case EntityOwned = 'entity_owned';
case Mirrored = 'mirrored';
}

View File

@@ -12,6 +12,7 @@ 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;
/**
@@ -107,6 +108,11 @@ final class FormField extends Model
return $this->hasMany(FormValue::class);
}
public function bindings(): MorphMany
{
return $this->morphMany(FormFieldBinding::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,70 @@
<?php
declare(strict_types=1);
namespace App\Models\FormBuilder;
use App\Enums\FormBuilder\FormFieldBindingMergeStrategy;
use App\Enums\FormBuilder\FormFieldBindingMode;
use App\Models\Scopes\FormFieldBindingScope;
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 what was `form_fields.binding` and
* `form_field_library.default_binding` JSON. Polymorphic owner morph
* aliases `form_field` and `form_field_library`. See ARCH-FORM-BUILDER
* §6.7 and ARCH-CONSOLIDATION-ADDENDUM-2026-04-24 §Q3.
*
* Pattern B (no binding) is represented by the absence of a row. Only
* Pattern A (entity_owned) and Pattern C (mirrored) create rows.
*/
final class FormFieldBinding extends Model
{
use HasFactory;
use HasUlids;
protected $table = 'form_field_bindings';
protected static function booted(): void
{
static::addGlobalScope(new FormFieldBindingScope());
}
protected $fillable = [
'owner_type',
'owner_id',
'target_entity',
'target_attribute',
'mode',
'sync_direction',
'merge_strategy',
'trust_level',
'is_identity_key',
];
/** @var array<string, string> */
protected $casts = [
'mode' => FormFieldBindingMode::class,
'merge_strategy' => FormFieldBindingMergeStrategy::class,
'trust_level' => 'int',
'is_identity_key' => 'bool',
];
public function owner(): MorphTo
{
return $this->morphTo('owner', 'owner_type', 'owner_id');
}
public function isEntityOwned(): bool
{
return $this->mode === FormFieldBindingMode::EntityOwned;
}
public function isMirrored(): bool
{
return $this->mode === FormFieldBindingMode::Mirrored;
}
}

View File

@@ -11,6 +11,7 @@ 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;
final class FormFieldLibrary extends Model
{
@@ -65,4 +66,9 @@ final class FormFieldLibrary extends Model
{
return $this->hasMany(FormField::class, 'library_field_id');
}
public function bindings(): MorphMany
{
return $this->morphMany(FormFieldBinding::class, 'owner');
}
}

View File

@@ -0,0 +1,106 @@
<?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;
/**
* Multi-tenant isolation for `form_field_bindings`. The table has a
* polymorphic owner that points at either `form_field` or
* `form_field_library`; `OrganisationScope` (Q2 FK-chain resolver) can't
* walk a morph parent, so this scope does the equivalent UNION walk:
*
* 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 = ?
* )
*
* Organisation context resolution mirrors `OrganisationScope` explicit
* override via constructor, then the `organisation` / `event` route
* parameter fallbacks. CLI, queues, and unauthenticated flows skip the
* scope (consistent with OrganisationScope).
*
* Escape hatch: callers that need cross-tenant reads use
* `FormFieldBinding::withoutGlobalScope(FormFieldBindingScope::class)`.
*/
final class FormFieldBindingScope 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

@@ -0,0 +1,29 @@
<?php
declare(strict_types=1);
namespace App\Observers\FormBuilder;
use App\Models\FormBuilder\FormField;
use App\Models\FormBuilder\FormFieldLibrary;
use Illuminate\Support\Facades\DB;
/**
* Cascade deletion of `form_field_bindings` rows when their polymorphic
* owner is deleted. Bindings represent current state (not historical
* intent) they are physically deleted even when the owner is only
* soft-deleted, which matches the Q3 decision that bindings have no
* soft-delete semantic of their own.
*/
final class FormFieldBindingsCascadeObserver
{
public function deleted(FormField|FormFieldLibrary $owner): void
{
$ownerType = $owner instanceof FormField ? 'form_field' : 'form_field_library';
DB::table('form_field_bindings')
->where('owner_type', $ownerType)
->where('owner_id', $owner->getKey())
->delete();
}
}

View File

@@ -48,6 +48,7 @@ use App\Models\VolunteerAvailability;
use App\Events\FormBuilder\FormSubmissionSubmitted;
use App\Listeners\FormBuilder\SyncTagPickerSelectionsOnSubmit;
use App\Listeners\FormBuilder\TriggerPersonIdentityMatchOnFormSubmit;
use App\Observers\FormBuilder\FormFieldBindingsCascadeObserver;
use App\Observers\FormBuilder\FormSubmissionObserver;
use App\Observers\FormBuilder\FormValueObserver;
use App\Observers\PersonObserver;
@@ -94,6 +95,11 @@ class AppServiceProvider extends ServiceProvider
FormValue::observe(FormValueObserver::class);
\App\Models\FormBuilder\FormSubmission::observe(FormSubmissionObserver::class);
// Cascade binding rows on owner delete (WS-5a). Bindings are physical
// state; deleted on soft-delete as well as hard-delete of the owner.
FormField::observe(FormFieldBindingsCascadeObserver::class);
FormFieldLibrary::observe(FormFieldBindingsCascadeObserver::class);
// ARCH §31.10 — FORM-02 TAG_PICKER sync listener.
\Illuminate\Support\Facades\Event::listen(
FormSubmissionSubmitted::class,