feat(form-builder): add core services (schema, field, submission, value, field-access, locale, tag-sync, filter, webhook, anonymisation)

S2b Phase 1 per ARCH-FORM-BUILDER.md §20.2. Ten services + supporting
exceptions, jobs, and the organisations.default_locale column needed by
FormLocaleResolver. All services log via spatie/laravel-activitylog, write
operations are transactional, queued jobs are idempotent.

- FormSchemaService: CRUD, slug, version bump, duplicate, edit-lock,
  public_token rotation (7-day grace window), typed-confirmation delete.
- FormFieldService: CRUD, reorder, insertFromLibrary, binding-change guard
  (§6.5), conditional_logic + section cycle detection (§8, §4.8.1),
  is_filterable toggle triggers BackfillFormValueIndexedJob (§7.2, §22.10).
- FormSubmissionService: createDraft with idempotency, saveDraft (auto-save),
  submit with schema snapshot + signature hash computation (§9), review,
  delegate/revoke, soft delete. Fires S1 domain events (§17.1).
- FormValueService: bulk upsert with FieldAccessService RBAC (§24.2),
  Pattern A/C entity mirror writes (§6.1, §6.6) with cross-entity graceful
  skip for person.user_id=null.
- FieldAccessService: canRead/canWrite/filterVisibleFields honouring
  role_restrictions + subject-self (§18.3, §24.1).
- FormLocaleResolver: submitter → schema → org.default_locale → 'nl' (§16.2).
- FormTagSyncService: rebuildForPerson — replaces legacy TagSyncService
  deleted in S2a (§31.10).
- FilterQueryBuilder: generic filter applier for entity_column / tags /
  form_field sources (§7.4–§7.5).
- FormWebhookDispatcher + DeliverFormWebhookJob: HMAC-signed delivery with
  SSRF protection, exponential backoff {1m,5m,30m,2h,8h}, max 5 attempts,
  dead-letter on exhaustion (§17.5).
- FormSubmissionAnonymisationService: per-field anonymisation with separate
  activity log entries (§13.3, §23.4).

MigrationRollbackTest: pin the S2a drop migration by filename so future
migrations don't shift the step offset.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-04-17 20:47:39 +02:00
parent a3ca596362
commit b3eab6e0c8
19 changed files with 2006 additions and 3 deletions

View File

@@ -0,0 +1,260 @@
<?php
declare(strict_types=1);
namespace App\Services\FormBuilder;
use App\Enums\FormBuilder\FormPurpose;
use App\Enums\FormBuilder\FormSubmissionStatus;
use App\Exceptions\FormBuilder\DestructiveConfirmationRequiredException;
use App\Exceptions\FormBuilder\EditLockConflictException;
use App\Models\FormBuilder\FormField;
use App\Models\FormBuilder\FormSchema;
use App\Models\FormBuilder\FormSchemaSection;
use App\Models\FormBuilder\FormSubmission;
use App\Models\Organisation;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
/**
* Schema CRUD + lifecycle per ARCH §4.1, §14, §18.1.
*/
final class FormSchemaService
{
public function create(Organisation $organisation, array $data, User $actor): FormSchema
{
return DB::transaction(function () use ($organisation, $data, $actor): FormSchema {
$purpose = $this->resolvePurpose($data['purpose'] ?? null);
$data['organisation_id'] = $organisation->id;
$data['slug'] = $this->ensureUniqueSlug($organisation, $data['slug'] ?? Str::slug($data['name'] ?? 'formulier'));
$data['purpose'] = $purpose->value;
$data['submission_mode'] ??= $purpose->defaultSubmissionMode()->value;
$data['version'] = 1;
$data['created_by_user_id'] = $actor->id;
$data['last_updated_by_user_id'] = $actor->id;
/** @var FormSchema $schema */
$schema = FormSchema::create($data);
$schema->logSchemaChange('schema.created', ['purpose' => $purpose->value]);
return $schema->refresh();
});
}
public function update(FormSchema $schema, array $data, User $actor): FormSchema
{
return DB::transaction(function () use ($schema, $data, $actor): FormSchema {
if (isset($data['slug']) && $data['slug'] !== $schema->slug) {
$data['slug'] = $this->ensureUniqueSlug($schema->organisation, $data['slug'], $schema->id);
}
$before = $schema->toArray();
$schema->fill($data);
if ($this->isStructuralChange($schema)) {
$schema->version = (int) $schema->version + 1;
}
$schema->last_updated_by_user_id = $actor->id;
$schema->save();
$schema->logSchemaChange('schema.updated', [
'old_version' => $before['version'] ?? null,
'new_version' => $schema->version,
]);
return $schema->refresh();
});
}
public function duplicate(FormSchema $source, User $actor, ?string $nameOverride = null): FormSchema
{
return DB::transaction(function () use ($source, $actor, $nameOverride): FormSchema {
$name = $nameOverride ?? ($source->name.' (kopie)');
$copy = $source->replicate([
'public_token', 'public_token_previous', 'public_token_rotated_at',
'edit_lock_user_id', 'edit_lock_expires_at',
]);
$copy->name = $name;
$copy->slug = $this->ensureUniqueSlug($source->organisation, Str::slug($name));
$copy->version = 1;
$copy->is_published = false;
$copy->created_by_user_id = $actor->id;
$copy->last_updated_by_user_id = $actor->id;
$copy->save();
// Copy sections (id mapping) then fields (pointing at new section ids).
$sectionIdMap = [];
foreach ($source->sections as $section) {
$newSection = $section->replicate();
$newSection->form_schema_id = $copy->id;
$newSection->save();
$sectionIdMap[$section->id] = $newSection->id;
}
foreach ($source->fields as $field) {
$newField = $field->replicate();
$newField->form_schema_id = $copy->id;
if ($field->form_schema_section_id && isset($sectionIdMap[$field->form_schema_section_id])) {
$newField->form_schema_section_id = $sectionIdMap[$field->form_schema_section_id];
}
$newField->save();
}
$copy->logSchemaChange('schema.duplicated', ['source_schema_id' => $source->id]);
return $copy->refresh();
});
}
public function publish(FormSchema $schema, User $actor): FormSchema
{
$schema->is_published = true;
$schema->last_updated_by_user_id = $actor->id;
$schema->save();
$schema->logSchemaChange('schema.published');
return $schema->refresh();
}
public function unpublish(FormSchema $schema, User $actor): FormSchema
{
$schema->is_published = false;
$schema->last_updated_by_user_id = $actor->id;
$schema->save();
$schema->logSchemaChange('schema.unpublished');
return $schema->refresh();
}
public function rotatePublicToken(FormSchema $schema, User $actor, int $graceDays = 7): FormSchema
{
return DB::transaction(function () use ($schema, $actor, $graceDays): FormSchema {
$previous = $schema->public_token;
$schema->public_token = (string) Str::ulid();
$schema->public_token_previous = $previous;
$schema->public_token_rotated_at = now();
$schema->last_updated_by_user_id = $actor->id;
$schema->save();
$schema->logSchemaChange('schema.public_token_rotated', [
'grace_days' => $graceDays,
'previous_token_present' => $previous !== null,
]);
return $schema->refresh();
});
}
public function acquireEditLock(FormSchema $schema, User $user, int $ttlMinutes = 10): FormSchema
{
return DB::transaction(function () use ($schema, $user, $ttlMinutes): FormSchema {
$now = now();
$holderId = $schema->edit_lock_user_id;
$expiresAt = $schema->edit_lock_expires_at;
if ($holderId !== null && $holderId !== $user->id && $expiresAt !== null && $expiresAt->greaterThan($now)) {
throw new EditLockConflictException(
User::query()->find($holderId),
$expiresAt,
);
}
$schema->edit_lock_user_id = $user->id;
$schema->edit_lock_expires_at = $now->copy()->addMinutes($ttlMinutes);
$schema->save();
return $schema->refresh();
});
}
public function releaseEditLock(FormSchema $schema, User $user): FormSchema
{
if ($schema->edit_lock_user_id !== null && $schema->edit_lock_user_id !== $user->id && ! $user->hasRole('org_admin')) {
throw new EditLockConflictException(
User::query()->find($schema->edit_lock_user_id),
$schema->edit_lock_expires_at,
);
}
$schema->edit_lock_user_id = null;
$schema->edit_lock_expires_at = null;
$schema->save();
return $schema->refresh();
}
public function delete(FormSchema $schema, User $actor, ?string $confirmedName = null): void
{
$hasSubmissions = FormSubmission::query()
->where('form_schema_id', $schema->id)
->exists();
if ($hasSubmissions) {
if ($confirmedName !== $schema->name) {
throw DestructiveConfirmationRequiredException::forName($schema->name);
}
}
DB::transaction(function () use ($schema, $actor): void {
$schema->last_updated_by_user_id = $actor->id;
$schema->save();
$schema->logSchemaChange('schema.deleted');
$schema->delete();
});
}
public function bumpVersion(FormSchema $schema): void
{
$schema->version = (int) $schema->version + 1;
$schema->save();
}
public function hasSubmittedSubmissions(FormSchema $schema): bool
{
return FormSubmission::query()
->where('form_schema_id', $schema->id)
->where('status', FormSubmissionStatus::SUBMITTED->value)
->exists();
}
private function resolvePurpose(mixed $purpose): FormPurpose
{
if ($purpose instanceof FormPurpose) {
return $purpose;
}
return FormPurpose::from((string) $purpose);
}
private function ensureUniqueSlug(?Organisation $organisation, string $slug, ?string $excludeId = null): string
{
$orgId = $organisation?->id;
if ($orgId === null) {
return $slug;
}
$base = Str::slug($slug);
$candidate = $base;
$i = 2;
while (FormSchema::withoutGlobalScopes()
->where('organisation_id', $orgId)
->where('slug', $candidate)
->when($excludeId !== null, fn ($q) => $q->where('id', '!=', $excludeId))
->exists()
) {
$candidate = $base.'-'.$i;
$i++;
}
return $candidate;
}
private function isStructuralChange(FormSchema $schema): bool
{
return $schema->isDirty(['purpose', 'submission_mode', 'locale', 'freeze_on_submit', 'snapshot_mode', 'section_level_submit', 'consent_version']);
}
}