feat(form-builder): form_field_validation_rules table + polymorphic owner + scope + cascade

This commit is contained in:
2026-04-24 22:01:36 +02:00
parent 87fc964ead
commit fedaed1b32
17 changed files with 798 additions and 37 deletions

View File

@@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
namespace App\Enums\FormBuilder;
/**
* Canonical catalogue of validation rule types stored relationally in
* `form_field_validation_rules` (ARCH-FORM-BUILDER §17.4). One case per
* legacy top-level key in the pre-WS-5b `validation_rules` JSON, minus
* the non-validation entries (`tag_categories`, `storage_disk` moved
* to `form_field_configs` under ARCH §17.5) and the column-duplicates
* (`required`, `unique` source of truth is `is_required` / `is_unique`
* on the parent row).
*
* Per-case `parameters` shape is enforced at the service layer, not by
* the enum see `FormFieldValidationRuleService::assertSpecValid()`.
*/
enum FormFieldValidationRuleType: string
{
case MinLength = 'min_length';
case MaxLength = 'max_length';
case MinValue = 'min_value';
case MaxValue = 'max_value';
case Regex = 'regex';
case EmailFormat = 'email_format';
case UrlFormat = 'url_format';
case PhoneE164 = 'phone_e164';
case AllowedMimeTypes = 'allowed_mime_types';
case MaxFileSize = 'max_file_size';
case MinSelected = 'min_selected';
case MaxSelected = 'max_selected';
case DateMin = 'date_min';
case DateMax = 'date_max';
case Callback = 'callback';
}

View File

@@ -111,6 +111,11 @@ final class FormField extends Model
return $this->morphMany(FormFieldBinding::class, 'owner');
}
public function validationRules(): MorphMany
{
return $this->morphMany(FormFieldValidationRule::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

@@ -69,4 +69,9 @@ final class FormFieldLibrary extends Model
{
return $this->morphMany(FormFieldBinding::class, 'owner');
}
public function validationRules(): MorphMany
{
return $this->morphMany(FormFieldValidationRule::class, 'owner');
}
}

View File

@@ -0,0 +1,55 @@
<?php
declare(strict_types=1);
namespace App\Models\FormBuilder;
use App\Enums\FormBuilder\FormFieldValidationRuleType;
use App\Models\Scopes\FormFieldValidationRuleScope;
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.validation_rules` and
* `form_field_library.validation_rules` JSON. Polymorphic owner morph
* aliases `form_field` and `form_field_library`. See ARCH-FORM-BUILDER
* §17.4 and ARCH-CONSOLIDATION-ADDENDUM-2026-04-24 §Q3.
*
* One row per (owner, rule_type). `parameters` JSON holds the rule-type-
* specific configuration (e.g. `{ "value": 3 }` for `min_length`, or
* `{ "mime_types": [...] }` for `allowed_mime_types`). Parameter shape
* validation lives in `FormFieldValidationRuleService`, not on the model.
*/
final class FormFieldValidationRule extends Model
{
use HasFactory;
use HasUlids;
protected $table = 'form_field_validation_rules';
protected static function booted(): void
{
static::addGlobalScope(new FormFieldValidationRuleScope());
}
protected $fillable = [
'owner_type',
'owner_id',
'rule_type',
'parameters',
'error_message_key',
];
/** @var array<string, string> */
protected $casts = [
'rule_type' => FormFieldValidationRuleType::class,
'parameters' => 'array',
];
public function owner(): MorphTo
{
return $this->morphTo('owner', 'owner_type', 'owner_id');
}
}

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;
/**
* Multi-tenant isolation for `form_field_validation_rules`. Sibling to
* `FormFieldBindingScope` the two share the same UNION shape over the
* polymorphic owner's two possible parents (`form_field form_schema
* organisation_id` `form_field_library organisation_id`).
*
* Duplicate code with `FormFieldBindingScope` is acknowledged; base-class
* extraction is deferred to WS-5d per the architect addendum Q3 decision:
* premature abstraction from two is still premature, and WS-5d adds a
* third sibling that will make what truly varies visible.
*
* Organisation context resolution mirrors `OrganisationScope` explicit
* override via constructor, then `organisation` / `event` route parameter
* fallbacks. CLI, queues, and unauthenticated flows skip the scope.
*
* Escape hatch:
* `FormFieldValidationRule::withoutGlobalScope(FormFieldValidationRuleScope::class)`.
*/
final class FormFieldValidationRuleScope 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

@@ -1,29 +0,0 @@
<?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

@@ -0,0 +1,49 @@
<?php
declare(strict_types=1);
namespace App\Observers\FormBuilder;
use App\Models\FormBuilder\FormField;
use App\Models\FormBuilder\FormFieldLibrary;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
/**
* Cascades physical deletion of child rows in the three relational tables
* that hang off `form_fields` / `form_field_library`:
*
* - `form_field_bindings` (WS-5a)
* - `form_field_validation_rules` (WS-5b)
* - `form_field_configs` (WS-5b expansion; added in commit 5)
*
* Children represent current state (not historical intent) physically
* deleted even when the owner is only soft-deleted, per addendum Q3: no
* child table in this family carries a soft-delete semantic of its own.
*
* Renamed from `FormFieldBindingsCascadeObserver` during WS-5b commit 1.
* The `Schema::hasTable` guard on the validation-rules cleanup keeps the
* observer safe when this code runs against a database where commit 1's
* migration has not yet been applied (e.g. during the migration step
* itself, where the observer is registered before the table exists).
*/
final class FormFieldChildTablesCascadeObserver
{
public function deleted(FormField|FormFieldLibrary $owner): void
{
$ownerType = $owner instanceof FormField ? 'form_field' : 'form_field_library';
$ownerId = $owner->getKey();
DB::table('form_field_bindings')
->where('owner_type', $ownerType)
->where('owner_id', $ownerId)
->delete();
if (Schema::hasTable('form_field_validation_rules')) {
DB::table('form_field_validation_rules')
->where('owner_type', $ownerType)
->where('owner_id', $ownerId)
->delete();
}
}
}

View File

@@ -48,7 +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\FormFieldChildTablesCascadeObserver;
use App\Observers\FormBuilder\FormSubmissionObserver;
use App\Observers\FormBuilder\FormValueObserver;
use App\Observers\PersonObserver;
@@ -95,10 +95,12 @@ 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);
// Cascade binding / validation-rule / config rows on owner delete.
// Children are physical state; deleted on soft-delete as well as
// hard-delete of the owner (WS-5a bindings, WS-5b validation rules
// + configs).
FormField::observe(FormFieldChildTablesCascadeObserver::class);
FormFieldLibrary::observe(FormFieldChildTablesCascadeObserver::class);
// ARCH §31.10 — FORM-02 TAG_PICKER sync listener.
\Illuminate\Support\Facades\Event::listen(