Phase 6 of S2b. 37 new tests, 820 → 857 passing across the suite. Feature suites (api/tests/Feature/FormBuilder/): - FormSchemaApiTest: CRUD, publish/unpublish, rotate-public-token (with grace window), edit-lock conflict, typed-confirmation delete, 401 on unauthenticated, 403 on outsider. - FormFieldApiTest: create, reorder, binding-change guard (422 w/o force, 200 with force), conditional_logic cycle rejection, 401 unauth. - FormSubmissionApiTest: draft → values → submit stores schema snapshot + version; review records reviewer; delegation creates active row; draft update blocked for non-subject non-delegatee (403). - FormValueSecurityTest: FieldAccessService hides admin-only fields from non-admin; subject-self bypass; admin-only field leaks through neither admin list nor non-admin detail responses (§22.9 intent). - PublicFormApiTest: portal-visible non-admin fields only; unknown token → 404; happy-path submission; expired-previous-token → 410; grace window still allows submission. - FormSchemaWebhookApiTest: url/secret NEVER returned in resources; DeliverFormWebhookJob rejects 10.x private-ip SSRF (response_body_excerpt logs rejection). - FilterRegistryApiTest: response shape includes tags + form_field sources; form_field filter registers. Integration contract (§31.10): - TagPickerSyncListenerTest: 5 cases proving (a) no-op on user_id=null, (b) sync on submit, (c) deferred sync via PersonIdentityService::confirmMatch, (d) organiser_assigned tags preserved on rebuild, (e) idempotent rerun. Fixes discovered while writing tests: - SyncTagPickerSelectionsOnSubmit: removed hardcoded connection='redis' so tests run via sync queue (QUEUE_CONNECTION fallback). - FormSubmissionService: corrected FormSubmissionReviewed / DraftUpdated event signatures to match S1 event classes. - FormSubmission model: added schema_version_at_submit / snapshot / anonymised_at / submission_duration_seconds / auto_save_count to $fillable so bulk operations + factory states populate consistently. - FormSchema: added version, edit_lock_user_id, edit_lock_expires_at to $fillable; factory now sets version=1 explicitly. - FormValueService: public submission path (actor=null) enforces is_portal_visible=true AND is_admin_only=false at the write layer instead of running FieldAccessService against a null user. - MigrationRollbackTest: target the S2a drop migration by filename. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
179 lines
6.0 KiB
PHP
179 lines
6.0 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');
|
|
|
|
DB::transaction(function () use ($slugToValue, $fields, $submission, $actor): 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));
|
|
}
|
|
|
|
$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;
|
|
}
|
|
}
|