feat(forms): add Eloquent models, observer, events, activity-log helpers

Phase 4 of S1.

Models (app/Models/FormBuilder/): FormSchema, FormSchemaSection, FormField,
FormSubmission, FormValue, FormValueOption, FormTemplate, FormFieldLibrary,
FormSchemaWebhook, FormWebhookDelivery, FormSubmissionSectionStatus,
FormSubmissionDelegation. Plus UserProfile at app/Models/ (user-universal).

OrganisationScope applied on: FormSchema, FormTemplate, FormFieldLibrary.
FormSchemaWebhook documents inherited-scope discipline (OrganisationScope's
strategies — organisation_id/event_id/festival_section_id — don't cover
form_schema_id; direct queries would leak across orgs, so must go via
$schema->webhooks()).

User::profile()/getOrCreateProfile(), Event::formSchemas() (morphMany),
Person::formSubmissions() (morphMany).

Morph map enforced in AppServiceProvider with 28 keys covering every model
that appears as activitylog subject/causer. Also updated
OrganisationDashboardService (and its test) to query activitylog via
getMorphClass() instead of FQCN.

Activity log strategy: nuanced explicit calls (logSchemaChange on FormSchema,
logFieldChange on FormField) — no LogsActivity trait. Suppression for bulk
fixtures via App\Support\ActivityLog::suppressed(fn() => ...) which flips
config('activitylog.enabled') around a callback. Both our explicit calls
and spatie's trait on Organisation respect the flag via ActivityLogger::log().

FormValueObserver (app/Observers/FormBuilder/) populates value_indexed/
value_number/value_date/value_bool on save per field.value_storage_hint,
rebuilds form_value_options pivot on multi-value filterable fields, cleans
up on delete. Memoised field cache avoids N+1. Registered in AppServiceProvider.

9 lightweight event classes (app/Events/FormBuilder/) as SerializesModels
containers — submission lifecycle signatures lock in for S2 services, no
listeners yet.

Factories for all models with Dutch fake data (fake('nl_NL')). FormSchema
factory uses defaultSubmissionMode(); FormField factory uses
recommendedValueStorageHint().

Tests: 9 new observer tests (all pass); full suite 910/910 (up from 901).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-04-17 12:35:41 +02:00
parent 6b26a90fa1
commit 85815ccb16
44 changed files with 2157 additions and 2 deletions

View File

@@ -0,0 +1,120 @@
<?php
declare(strict_types=1);
namespace App\Models\FormBuilder;
use App\Enums\FormBuilder\FormFieldDisplayWidth;
use App\Enums\FormBuilder\FormValueStorageHint;
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\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 $fillable = [
'form_schema_id',
'form_schema_section_id',
'library_field_id',
'field_type',
'slug',
'label',
'help_text',
'section',
'options',
'validation_rules',
'is_required',
'is_filterable',
'is_portal_visible',
'is_admin_only',
'is_unique',
'is_pii',
'display_width',
'binding',
'conditional_logic',
'role_restrictions',
'translations',
'value_storage_hint',
'review_required',
'sort_order',
];
/** @var array<string, string> */
protected $casts = [
'options' => 'array',
'validation_rules' => 'array',
'binding' => 'array',
'conditional_logic' => 'array',
'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);
}
/**
* 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.
* NOT logged (noise): label/help_text/sort_order/conditional_logic/
* 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);
}
}

View File

@@ -0,0 +1,68 @@
<?php
declare(strict_types=1);
namespace App\Models\FormBuilder;
use App\Models\Organisation;
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;
final class FormFieldLibrary extends Model
{
use HasFactory;
use HasUlids;
protected $table = 'form_field_library';
public string $organisationScopeColumn = 'organisation_id';
protected static function booted(): void
{
static::addGlobalScope(new OrganisationScope());
}
protected $fillable = [
'organisation_id',
'name',
'slug',
'field_type',
'label',
'help_text',
'options',
'validation_rules',
'default_is_required',
'default_is_filterable',
'default_binding',
'translations',
'description',
'is_active',
];
/** @var array<string, string> */
protected $casts = [
'options' => 'array',
'validation_rules' => 'array',
'default_binding' => 'array',
'translations' => 'array',
'default_is_required' => 'bool',
'default_is_filterable' => 'bool',
'is_system' => 'bool',
'is_active' => 'bool',
'usage_count' => 'int',
];
public function organisation(): BelongsTo
{
return $this->belongsTo(Organisation::class);
}
public function fields(): HasMany
{
return $this->hasMany(FormField::class, 'library_field_id');
}
}

View File

@@ -0,0 +1,150 @@
<?php
declare(strict_types=1);
namespace App\Models\FormBuilder;
use App\Enums\FormBuilder\FormPurpose;
use App\Enums\FormBuilder\FormSchemaSnapshotMode;
use App\Enums\FormBuilder\FormSubmissionMode;
use App\Models\Organisation;
use App\Models\Scopes\OrganisationScope;
use App\Models\User;
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\MorphTo;
use Illuminate\Database\Eloquent\SoftDeletes;
/**
* Activity log strategy: explicit calls via logSchemaChange() no LogsActivity
* trait (would produce noise). See ARCH-FORM-BUILDER.md §17.1 and S1 Phase 4b.
*/
final class FormSchema extends Model
{
use HasFactory;
use HasUlids;
use SoftDeletes;
public string $organisationScopeColumn = 'organisation_id';
protected static function booted(): void
{
static::addGlobalScope(new OrganisationScope());
}
protected $fillable = [
'organisation_id',
'owner_type',
'owner_id',
'name',
'slug',
'purpose',
'custom_purpose_slug',
'description',
'is_published',
'submission_mode',
'public_token',
'public_token_previous',
'public_token_rotated_at',
'submission_deadline',
'locale',
'settings',
'snapshot_mode',
'freeze_on_submit',
'retention_days',
'consent_version',
'section_level_submit',
'auto_save_enabled',
'max_submissions',
'created_by_user_id',
'last_updated_by_user_id',
];
/** @var array<string, string> */
protected $casts = [
'purpose' => FormPurpose::class,
'submission_mode' => FormSubmissionMode::class,
'snapshot_mode' => FormSchemaSnapshotMode::class,
'is_published' => 'bool',
'freeze_on_submit' => 'bool',
'section_level_submit' => 'bool',
'auto_save_enabled' => 'bool',
'settings' => 'array',
'submission_deadline' => 'datetime',
'public_token_rotated_at' => 'datetime',
'edit_lock_expires_at' => 'datetime',
'version' => 'int',
'retention_days' => 'int',
'max_submissions' => 'int',
];
public function organisation(): BelongsTo
{
return $this->belongsTo(Organisation::class);
}
public function owner(): MorphTo
{
return $this->morphTo();
}
public function fields(): HasMany
{
return $this->hasMany(FormField::class);
}
public function sections(): HasMany
{
return $this->hasMany(FormSchemaSection::class);
}
public function submissions(): HasMany
{
return $this->hasMany(FormSubmission::class);
}
public function webhooks(): HasMany
{
return $this->hasMany(FormSchemaWebhook::class);
}
public function createdBy(): BelongsTo
{
return $this->belongsTo(User::class, 'created_by_user_id');
}
public function lastUpdatedBy(): BelongsTo
{
return $this->belongsTo(User::class, 'last_updated_by_user_id');
}
public function editLockUser(): BelongsTo
{
return $this->belongsTo(User::class, 'edit_lock_user_id');
}
/**
* Nuanced activity log (ARCH §17.1; S1 Phase 4b). Callers choose which
* events are worth logging e.g. created/deleted/restored, published
* toggled, purpose changed, freeze_on_submit toggled, retention_days
* changed, consent_version changed, public_token rotated, snapshot_mode
* changed. NOT logged (noise): name/description/slug, settings, locale.
*
* 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 logSchemaChange(string $event, array $properties = []): void
{
activity()
->performedOn($this)
->withProperties($properties)
->log($event);
}
}

View File

@@ -0,0 +1,60 @@
<?php
declare(strict_types=1);
namespace App\Models\FormBuilder;
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\SoftDeletes;
/**
* Activity log strategy: log only on create/delete (ARCH §17.1, S1 Phase 4b).
*/
final class FormSchemaSection extends Model
{
use HasFactory;
use HasUlids;
use SoftDeletes;
protected $fillable = [
'form_schema_id',
'slug',
'name',
'description',
'sort_order',
'submit_independent',
'depends_on_section_id',
'required_for_schema_submit',
];
/** @var array<string, string> */
protected $casts = [
'submit_independent' => 'bool',
'required_for_schema_submit' => 'bool',
'sort_order' => 'int',
];
public function schema(): BelongsTo
{
return $this->belongsTo(FormSchema::class, 'form_schema_id');
}
public function dependsOnSection(): BelongsTo
{
return $this->belongsTo(self::class, 'depends_on_section_id');
}
public function fields(): HasMany
{
return $this->hasMany(FormField::class);
}
public function submissionStatuses(): HasMany
{
return $this->hasMany(FormSubmissionSectionStatus::class);
}
}

View File

@@ -0,0 +1,54 @@
<?php
declare(strict_types=1);
namespace App\Models\FormBuilder;
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;
/**
* Scope discipline: organisation isolation is enforced via the parent
* FormSchema. This model does NOT carry a direct organisation_id column,
* and OrganisationScope's column strategies (organisation_id / event_id /
* festival_section_id) do not cover form_schema_id extending the scope
* to a new strategy is out of scope for S1.
*
* NEVER query FormSchemaWebhook::query() without an eager constraint:
* always go through $schema->webhooks() or join on form_schema_id. Direct
* queries will leak across organisations.
*/
final class FormSchemaWebhook extends Model
{
use HasFactory;
use HasUlids;
protected $fillable = [
'form_schema_id',
'name',
'trigger_event',
'url',
'secret',
'is_active',
];
/** @var array<string, string> */
protected $casts = [
'url' => 'encrypted',
'secret' => 'encrypted',
'is_active' => 'bool',
];
public function schema(): BelongsTo
{
return $this->belongsTo(FormSchema::class, 'form_schema_id');
}
public function deliveries(): HasMany
{
return $this->hasMany(FormWebhookDelivery::class);
}
}

View File

@@ -0,0 +1,102 @@
<?php
declare(strict_types=1);
namespace App\Models\FormBuilder;
use App\Enums\FormBuilder\FormSubmissionReviewStatus;
use App\Enums\FormBuilder\FormSubmissionStatus;
use App\Models\User;
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\MorphTo;
use Illuminate\Database\Eloquent\SoftDeletes;
/**
* No direct activity-log hooks on this model: lifecycle events fire from the
* FormSubmissionService (arriving in S2) per ARCH §17.1.
*/
final class FormSubmission extends Model
{
use HasFactory;
use HasUlids;
use SoftDeletes;
protected $fillable = [
'form_schema_id',
'subject_type',
'subject_id',
'submitted_by_user_id',
'public_submitter_name',
'public_submitter_email',
'public_submitter_ip',
'public_submitter_ip_anonymised_at',
'status',
'review_status',
'reviewed_by_user_id',
'reviewed_at',
'review_notes',
'submitted_at',
'schema_snapshot',
'is_test',
'submitted_in_locale',
'opened_at',
'first_interacted_at',
'idempotency_key',
];
/** @var array<string, string> */
protected $casts = [
'status' => FormSubmissionStatus::class,
'review_status' => FormSubmissionReviewStatus::class,
'schema_snapshot' => 'array',
'is_test' => 'bool',
'submitted_at' => 'datetime',
'reviewed_at' => 'datetime',
'anonymised_at' => 'datetime',
'opened_at' => 'datetime',
'first_interacted_at' => 'datetime',
'public_submitter_ip_anonymised_at' => 'datetime',
'schema_version_at_submit' => 'int',
'submission_duration_seconds' => 'int',
'auto_save_count' => 'int',
];
public function schema(): BelongsTo
{
return $this->belongsTo(FormSchema::class, 'form_schema_id');
}
public function subject(): MorphTo
{
return $this->morphTo();
}
public function submittedBy(): BelongsTo
{
return $this->belongsTo(User::class, 'submitted_by_user_id');
}
public function reviewedBy(): BelongsTo
{
return $this->belongsTo(User::class, 'reviewed_by_user_id');
}
public function values(): HasMany
{
return $this->hasMany(FormValue::class);
}
public function sectionStatuses(): HasMany
{
return $this->hasMany(FormSubmissionSectionStatus::class);
}
public function delegations(): HasMany
{
return $this->hasMany(FormSubmissionDelegation::class);
}
}

View File

@@ -0,0 +1,47 @@
<?php
declare(strict_types=1);
namespace App\Models\FormBuilder;
use App\Models\User;
use Illuminate\Database\Eloquent\Concerns\HasUlids;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
final class FormSubmissionDelegation extends Model
{
use HasFactory;
use HasUlids;
protected $fillable = [
'form_submission_id',
'delegated_to_user_id',
'delegated_by_user_id',
'granted_at',
'revoked_at',
'message',
];
/** @var array<string, string> */
protected $casts = [
'granted_at' => 'datetime',
'revoked_at' => 'datetime',
];
public function submission(): BelongsTo
{
return $this->belongsTo(FormSubmission::class, 'form_submission_id');
}
public function delegatedTo(): BelongsTo
{
return $this->belongsTo(User::class, 'delegated_to_user_id');
}
public function delegatedBy(): BelongsTo
{
return $this->belongsTo(User::class, 'delegated_by_user_id');
}
}

View File

@@ -0,0 +1,46 @@
<?php
declare(strict_types=1);
namespace App\Models\FormBuilder;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
final class FormSubmissionSectionStatus extends Model
{
use HasFactory;
protected $fillable = [
'form_submission_id',
'form_schema_section_id',
'status',
'submitted_at',
'reviewed_by_user_id',
'reviewed_at',
'review_notes',
];
/** @var array<string, string> */
protected $casts = [
'submitted_at' => 'datetime',
'reviewed_at' => 'datetime',
];
public function submission(): BelongsTo
{
return $this->belongsTo(FormSubmission::class, 'form_submission_id');
}
public function section(): BelongsTo
{
return $this->belongsTo(FormSchemaSection::class, 'form_schema_section_id');
}
public function reviewedBy(): BelongsTo
{
return $this->belongsTo(User::class, 'reviewed_by_user_id');
}
}

View File

@@ -0,0 +1,49 @@
<?php
declare(strict_types=1);
namespace App\Models\FormBuilder;
use App\Enums\FormBuilder\FormPurpose;
use App\Models\Organisation;
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;
final class FormTemplate extends Model
{
use HasFactory;
use HasUlids;
public string $organisationScopeColumn = 'organisation_id';
protected static function booted(): void
{
static::addGlobalScope(new OrganisationScope());
}
protected $fillable = [
'organisation_id',
'name',
'slug',
'purpose',
'description',
'schema_snapshot',
'is_active',
];
/** @var array<string, string> */
protected $casts = [
'purpose' => FormPurpose::class,
'schema_snapshot' => 'array',
'is_active' => 'bool',
'is_system' => 'bool',
];
public function organisation(): BelongsTo
{
return $this->belongsTo(Organisation::class);
}
}

View File

@@ -0,0 +1,54 @@
<?php
declare(strict_types=1);
namespace App\Models\FormBuilder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
/**
* EAV storage row. Int PK for fast joins (ARCH §4.4). Typed columns are
* populated by FormValueObserver based on field.value_storage_hint.
*/
final class FormValue extends Model
{
use HasFactory;
protected $fillable = [
'form_submission_id',
'form_field_id',
'value',
'value_indexed',
'value_number',
'value_date',
'value_bool',
'value_anonymised',
];
/** @var array<string, string> */
protected $casts = [
'value' => 'array',
'value_number' => 'decimal:4',
'value_date' => 'date',
'value_bool' => 'bool',
'value_anonymised' => 'bool',
];
public function submission(): BelongsTo
{
return $this->belongsTo(FormSubmission::class, 'form_submission_id');
}
public function field(): BelongsTo
{
return $this->belongsTo(FormField::class, 'form_field_id');
}
public function options(): HasMany
{
return $this->hasMany(FormValueOption::class);
}
}

View File

@@ -0,0 +1,43 @@
<?php
declare(strict_types=1);
namespace App\Models\FormBuilder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
/**
* Filter pivot for multi-value fields (MULTISELECT, CHECKBOX_LIST, TAG_PICKER).
* Rows rebuilt by FormValueObserver on each save. No timestamps ephemeral,
* always regenerated from form_values.value.
*/
final class FormValueOption extends Model
{
use HasFactory;
public $timestamps = false;
protected $fillable = [
'form_value_id',
'form_field_id',
'form_submission_id',
'option_value',
];
public function value(): BelongsTo
{
return $this->belongsTo(FormValue::class, 'form_value_id');
}
public function field(): BelongsTo
{
return $this->belongsTo(FormField::class, 'form_field_id');
}
public function submission(): BelongsTo
{
return $this->belongsTo(FormSubmission::class, 'form_submission_id');
}
}

View File

@@ -0,0 +1,60 @@
<?php
declare(strict_types=1);
namespace App\Models\FormBuilder;
use App\Enums\FormBuilder\FormWebhookDeliveryStatus;
use Illuminate\Database\Eloquent\Concerns\HasUlids;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
/**
* No Eloquent timestamps: this model carries its own lifecycle columns
* (last_attempt_at, next_retry_at, delivered_at, failed_permanently_at).
*/
final class FormWebhookDelivery extends Model
{
use HasFactory;
use HasUlids;
public $timestamps = false;
protected $fillable = [
'form_schema_webhook_id',
'form_submission_id',
'trigger_event',
'status',
'attempts',
'last_attempt_at',
'response_status',
'response_body_excerpt',
'next_retry_at',
'delivered_at',
'failed_permanently_at',
'payload_snapshot',
];
/** @var array<string, string> */
protected $casts = [
'status' => FormWebhookDeliveryStatus::class,
'payload_snapshot' => 'array',
'last_attempt_at' => 'datetime',
'next_retry_at' => 'datetime',
'delivered_at' => 'datetime',
'failed_permanently_at' => 'datetime',
'attempts' => 'int',
'response_status' => 'int',
];
public function webhook(): BelongsTo
{
return $this->belongsTo(FormSchemaWebhook::class, 'form_schema_webhook_id');
}
public function submission(): BelongsTo
{
return $this->belongsTo(FormSubmission::class, 'form_submission_id');
}
}