Files
crewli/api/app/Services/FormBuilder/FormValueService.php
bert.hausmans 63d08c8bde feat(form-builder): public draft/save/submit split + sub-endpoints + validation
S2c D2, D3, D4, D8 — the meat of the public API rewrite.

Draft / save / submit split (D4):
- POST /public/forms/{public_token}/submissions
    Creates a draft. idempotency_key is now REQUIRED; second POST with
    the same key returns the existing draft (HTTP 200 vs 201 for fresh).
    UniqueConstraintViolationException caught for race-safe replay.
- PUT /public/forms/{public_token}/submissions/{submission_id}
    Auto-save. Partial updates only — each PUT writes just the
    slugs in the body. Status stays 'draft'; auto_save_count++.
- POST /public/forms/{public_token}/submissions/{submission_id}/submit
    Final submission. Merges body values with already-saved values,
    runs strict rule set against the merged map, then calls
    FormSubmissionService::submit which fires the lifecycle events
    (tag sync, identity match). Rate-limited per IP per token per hour.

Access rules: submission must belong to the resolved schema; status
must be 'draft' (409 SUBMISSION_ALREADY_SUBMITTED otherwise); schema
still accepting submissions.

Sub-endpoints (D2, D3):
- GET /public/forms/{public_token}/time-slots
    Volunteer-only, festival-aware (parent + children). Reads straight
    from TimeSlot model — no org-coupled service to extract from. Out:
    {id, name, date, start_time, end_time, duration_hours, event_id,
    event_name}.
- GET /public/forms/{public_token}/sections
    show_in_registration=true, type=standard, deduplicated by name
    across festival children.

Dynamic per-field validation (D8):
- FormFieldRuleBuilder builds Laravel rule arrays from form_fields.
  strict() enforces is_required + in:options + type rules (email,
  url, numeric, date, boolean, phone regex); relaxed() is the
  auto-save variant that drops required-ness.
- StartPublicDraftRequest (required idempotency_key),
  SavePublicDraftRequest (relaxed rules, values optional),
  SubmitPublicSubmissionRequest (relaxed rules at body level — the
  controller merges the body with saved values and runs the strict
  validator on the full map so submit with an empty body still
  passes when everything was auto-saved).
- FormValueService backs the request layer up with deeper enforcement
  of validation_rules JSON (min/max/regex) + is_unique. Throws
  FieldValidationException (422) which renders via the D6 envelope.

PublicFormTokenResolver centralises the grace-window logic; every
public endpoint resolves through it so the standardised exceptions
bubble uniformly.

Routes: 6 total under /public/forms/ (up from 2). Tests:
PublicFormApiTest's existing submit test retrofitted to the three-step
flow; 857 tests still green.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-17 22:56:20 +02:00

239 lines
8.4 KiB
PHP

<?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');
$fieldErrors = [];
DB::transaction(function () use ($slugToValue, $fields, $submission, $actor, &$fieldErrors): void {
foreach ($slugToValue as $slug => $raw) {
$field = $fields->get($slug);
if ($field === null) {
continue;
}
if ($actor === null) {
// Public submission path: portal-visible non-admin fields only.
if (! (bool) $field->is_portal_visible || (bool) $field->is_admin_only) {
throw new AuthorizationException(sprintf('Not allowed to write field "%s" on public submission.', $slug));
}
} elseif (! $this->fieldAccess->canWrite($actor, $field, $submission)) {
throw new AuthorizationException(sprintf('Not allowed to write field "%s".', $slug));
}
$errors = $this->validateAgainstFieldRules($field, $raw, $submission);
if ($errors !== []) {
$fieldErrors[$slug] = $errors;
continue;
}
$this->writeValue($submission, $field, $raw);
$this->writeEntityMirror($submission, $field, $raw);
}
});
if ($fieldErrors !== []) {
throw new \App\Exceptions\FormBuilder\FieldValidationException($fieldErrors);
}
}
/**
* Backstop enforcement of form_fields.validation_rules JSON per
* S2c D8. The FormFieldRuleBuilder already surfaces min/max/regex
* shortcuts at the request layer; this is where the deeper checks
* (is_unique, validation_rules.unique) live.
*
* @return array<int, string>
*/
private function validateAgainstFieldRules(FormField $field, mixed $raw, FormSubmission $submission): array
{
$errors = [];
$rules = is_array($field->validation_rules) ? $field->validation_rules : [];
if ($raw === null || $raw === '' || $raw === []) {
return $errors;
}
if (isset($rules['min']) && is_numeric($rules['min']) && is_numeric($raw) && (float) $raw < (float) $rules['min']) {
$errors[] = sprintf('Minimum is %s.', (string) $rules['min']);
}
if (isset($rules['max']) && is_numeric($rules['max']) && is_numeric($raw) && (float) $raw > (float) $rules['max']) {
$errors[] = sprintf('Maximum is %s.', (string) $rules['max']);
}
if (isset($rules['regex']) && is_string($rules['regex']) && is_string($raw)
&& @preg_match($rules['regex'], $raw) !== 1) {
$errors[] = 'Value does not match the expected format.';
}
$unique = (bool) $field->is_unique || (bool) ($rules['unique'] ?? false);
if ($unique) {
$scalar = is_scalar($raw) ? (string) $raw : null;
if ($scalar !== null) {
$exists = \App\Models\FormBuilder\FormValue::query()
->where('form_field_id', $field->id)
->where('value_indexed', $scalar)
->where('form_submission_id', '!=', $submission->id)
->whereHas('submission', fn ($q) => $q->where('status', \App\Enums\FormBuilder\FormSubmissionStatus::SUBMITTED->value))
->exists();
if ($exists) {
$errors[] = 'This value is already in use for another submission.';
}
}
}
return $errors;
}
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;
}
}