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:
173
api/app/Services/FormBuilder/FormValueService.php
Normal file
173
api/app/Services/FormBuilder/FormValueService.php
Normal file
@@ -0,0 +1,173 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Services\FormBuilder;
|
||||
|
||||
use App\Enums\FormBuilder\FormFieldType;
|
||||
use App\Models\FormBuilder\FormField;
|
||||
use App\Models\FormBuilder\FormSchema;
|
||||
use App\Models\FormBuilder\FormSubmission;
|
||||
use App\Models\FormBuilder\FormValue;
|
||||
use App\Models\User;
|
||||
use Illuminate\Auth\Access\AuthorizationException;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
/**
|
||||
* Writes form values with per-field RBAC (FieldAccessService) and pattern
|
||||
* A/C entity mirror writes (ARCH §6.1, §6.6). The FormValueObserver handles
|
||||
* typed-column + pivot rebuilding — the service only persists the JSON value.
|
||||
*/
|
||||
final class FormValueService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly FieldAccessService $fieldAccess,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $slugToValue
|
||||
*/
|
||||
public function upsertMany(FormSubmission $submission, array $slugToValue, ?User $actor): void
|
||||
{
|
||||
$schema = $submission->schema;
|
||||
$fields = FormField::query()
|
||||
->where('form_schema_id', $schema->id)
|
||||
->whereIn('slug', array_keys($slugToValue))
|
||||
->get()
|
||||
->keyBy('slug');
|
||||
|
||||
DB::transaction(function () use ($slugToValue, $fields, $submission, $actor): void {
|
||||
foreach ($slugToValue as $slug => $raw) {
|
||||
$field = $fields->get($slug);
|
||||
if ($field === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (! $this->fieldAccess->canWrite($actor, $field, $submission)) {
|
||||
throw new AuthorizationException(sprintf('Not allowed to write field "%s".', $slug));
|
||||
}
|
||||
|
||||
$this->writeValue($submission, $field, $raw);
|
||||
$this->writeEntityMirror($submission, $field, $raw);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private function writeValue(FormSubmission $submission, FormField $field, mixed $raw): void
|
||||
{
|
||||
$payload = $this->normalisePayload($field, $raw);
|
||||
|
||||
/** @var FormValue|null $value */
|
||||
$value = FormValue::query()
|
||||
->where('form_submission_id', $submission->id)
|
||||
->where('form_field_id', $field->id)
|
||||
->first();
|
||||
|
||||
if ($value === null) {
|
||||
$value = new FormValue;
|
||||
$value->form_submission_id = $submission->id;
|
||||
$value->form_field_id = $field->id;
|
||||
}
|
||||
|
||||
$value->setRelation('field', $field);
|
||||
$value->value = $payload;
|
||||
$value->value_anonymised = false;
|
||||
$value->save();
|
||||
}
|
||||
|
||||
private function normalisePayload(FormField $field, mixed $raw): mixed
|
||||
{
|
||||
$multi = in_array($field->field_type, [
|
||||
FormFieldType::MULTISELECT->value,
|
||||
FormFieldType::CHECKBOX_LIST->value,
|
||||
FormFieldType::TAG_PICKER->value,
|
||||
FormFieldType::AVAILABILITY_PICKER->value,
|
||||
FormFieldType::SECTION_PRIORITY->value,
|
||||
FormFieldType::TABLE_ROWS->value,
|
||||
], true);
|
||||
|
||||
if ($multi) {
|
||||
return is_array($raw) ? array_values($raw) : [];
|
||||
}
|
||||
|
||||
return $raw;
|
||||
}
|
||||
|
||||
private function writeEntityMirror(FormSubmission $submission, FormField $field, mixed $raw): void
|
||||
{
|
||||
$binding = $field->binding;
|
||||
if (! is_array($binding) || ($binding['mode'] ?? null) === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
$mode = (string) $binding['mode'];
|
||||
if (! in_array($mode, ['entity_owned', 'mirrored'], true)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$entity = (string) ($binding['entity'] ?? '');
|
||||
$column = (string) ($binding['column'] ?? '');
|
||||
if ($entity === '' || $column === '') {
|
||||
return;
|
||||
}
|
||||
|
||||
$registry = config('form_binding.'.$entity);
|
||||
if (! is_array($registry) || ! isset($registry[$column]) || ! ($registry[$column]['writable'] ?? false)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$target = $this->resolveEntityTarget($submission, $entity);
|
||||
if ($target === null) {
|
||||
// Cross-entity Pattern C (person → user_profile) may have null user_id.
|
||||
Log::info('form-builder.mirror.skipped', [
|
||||
'submission_id' => $submission->id,
|
||||
'field_id' => $field->id,
|
||||
'entity' => $entity,
|
||||
'column' => $column,
|
||||
'reason' => 'target_not_resolvable',
|
||||
]);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$scalar = is_scalar($raw) ? $raw : null;
|
||||
$target->{$column} = $scalar;
|
||||
$target->save();
|
||||
}
|
||||
|
||||
private function resolveEntityTarget(FormSubmission $submission, string $entity): ?\Illuminate\Database\Eloquent\Model
|
||||
{
|
||||
$subjectType = $submission->subject_type;
|
||||
$subjectId = $submission->subject_id;
|
||||
if ($subjectId === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($subjectType === $entity) {
|
||||
$map = config('form_subjects');
|
||||
$model = $map[$entity]['model'] ?? null;
|
||||
if ($model === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $model::withoutGlobalScopes()->find($subjectId);
|
||||
}
|
||||
|
||||
// Cross-entity: person → user_profile via person.user_id
|
||||
if ($entity === 'user_profile' && $subjectType === 'person') {
|
||||
$person = \App\Models\Person::withoutGlobalScopes()->find($subjectId);
|
||||
if ($person === null || $person->user_id === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return \App\Models\UserProfile::firstOrCreate(['user_id' => $person->user_id]);
|
||||
}
|
||||
|
||||
if ($entity === 'user_profile' && $subjectType === 'user') {
|
||||
return \App\Models\UserProfile::firstOrCreate(['user_id' => $subjectId]);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user