Das Widget prüft nur noch, dass der Einstieg existiert; die Auswahl im Editor bietet weiter nur veröffentlichte an. Der Worker kennt keine Anfrage und APP_URL ist unzuverlässig, daher gibt die Web-Anfrage die Adresse der Anfrage in der Verwaltung an die Aufgabe weiter. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
293 lines
12 KiB
PHP
293 lines
12 KiB
PHP
<?php
|
|
|
|
namespace App\Domain\Communication;
|
|
|
|
use App\Jobs\SendInquiryNotification;
|
|
use Illuminate\Database\UniqueConstraintViolationException;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Illuminate\Support\Str;
|
|
use Throwable;
|
|
|
|
/**
|
|
* Zentraler Anfrageservice (ADR-60): jeder öffentliche Anfrage-Einstieg sendet hierher, unabhängig von der Seite.
|
|
*
|
|
* 1. gültige veröffentlichte Konfiguration ermitteln, 2. Token prüfen, 3. Bedingungen auswerten, 4. serverseitig
|
|
* validieren, 5. speichern, 6. erst danach benachrichtigen, 7. Ergebnis melden.
|
|
* Der Browser entscheidet nichts: Werte ausgeblendeter Felder werden verworfen, unbekannte Schlüssel und Auswahlwerte
|
|
* zurückgewiesen.
|
|
*/
|
|
final class InquiryService
|
|
{
|
|
public function __construct(private readonly FormFactory $factory, private readonly FormEvaluator $evaluator) {}
|
|
|
|
/**
|
|
* Die Fassung und das wirksame Formular für einen Besucher. Null, wenn der Einstieg nicht ausgeliefert wird.
|
|
*
|
|
* @return array{form: array<string, mixed>, version: InquiryTemplateVersion}|null
|
|
*/
|
|
public function deliver(InquiryEntry $entry, ?int $versionId = null): ?array
|
|
{
|
|
$entry->loadMissing('template.publishedVersion');
|
|
|
|
if (! $entry->isLive()) {
|
|
return null;
|
|
}
|
|
|
|
$version = $entry->template->publishedVersion;
|
|
|
|
if ($versionId !== null && $versionId !== $version->id) {
|
|
$older = InquiryTemplateVersion::query()->where('template_id', $entry->template_id)->find($versionId);
|
|
$version = $older ?? $version;
|
|
}
|
|
|
|
return ['form' => $this->factory->effective($version->definition, (array) $entry->published_config), 'version' => $version];
|
|
}
|
|
|
|
/**
|
|
* @param array<string, mixed> $payload {values: {...}, token: string, website?: string, source?: string}
|
|
* @return array{reference: string, created: bool}
|
|
*
|
|
* @throws SubmissionException
|
|
*/
|
|
public function submit(InquiryEntry $entry, array $payload): array
|
|
{
|
|
$token = FormToken::read($payload['token'] ?? null);
|
|
|
|
if ($token === null || $token['e'] !== $entry->id) {
|
|
throw new SubmissionException('Das Formular ist abgelaufen. Bitte laden Sie die Seite neu; Ihre Eingaben bleiben dabei nicht erhalten.', [], 419);
|
|
}
|
|
|
|
$age = now()->getTimestamp() - $token['t'];
|
|
|
|
if ($age > config('communication.token_ttl_hours', 24) * 3600) {
|
|
throw new SubmissionException('Das Formular war zu lange geöffnet. Bitte laden Sie die Seite neu.', [], 419);
|
|
}
|
|
|
|
$existing = Inquiry::query()->where('submission_token', hash('sha256', $token['n']))->first();
|
|
|
|
if ($existing !== null) {
|
|
return ['reference' => $existing->reference, 'created' => false];
|
|
}
|
|
|
|
$delivered = $this->deliver($entry, $token['v']);
|
|
|
|
if ($delivered === null) {
|
|
throw new SubmissionException('Dieses Anfrageformular ist zurzeit nicht verfügbar.', [], 410);
|
|
}
|
|
|
|
// Automaten: ausgefülltes Köderfeld oder zu schnelle Absendung. Keine Speicherung, keine Rückmeldung an das Programm.
|
|
$website = $payload['website'] ?? null;
|
|
|
|
if ((is_string($website) && trim($website) !== '') || $age < (int) config('communication.min_fill_seconds', 3)) {
|
|
if (! (is_string($website) && trim($website) !== '')) {
|
|
throw new SubmissionException('Bitte nehmen Sie sich einen Moment Zeit und senden Sie noch einmal.', [], 429);
|
|
}
|
|
|
|
return ['reference' => 'LF-'.now()->format('ymd').'-'.Str::upper(Str::random(5)), 'created' => false];
|
|
}
|
|
|
|
$values = $payload['values'] ?? null;
|
|
|
|
if (! is_array($values) || strlen((string) json_encode($values)) > (int) config('communication.max_payload_chars', 40000)) {
|
|
throw new SubmissionException('Die Eingaben sind ungültig.');
|
|
}
|
|
|
|
$form = $delivered['form'];
|
|
$result = $this->process($form, $values);
|
|
|
|
$source = $payload['source'] ?? null;
|
|
$source = is_string($source) && preg_match('#^/[A-Za-z0-9\-_/.]{0,250}$#', $source) === 1 ? $source : null;
|
|
|
|
try {
|
|
$inquiry = DB::transaction(fn (): Inquiry => Inquiry::query()->create([
|
|
'reference' => $this->reference(),
|
|
'entry_id' => $entry->id,
|
|
'template_version_id' => $delivered['version']->id,
|
|
'submission_token' => hash('sha256', $token['n']),
|
|
'issue_key' => $result['issue']['key'] ?? null,
|
|
'issue_label' => $result['issue']['label'] ?? null,
|
|
'subissue_key' => $result['subissue']['key'] ?? null,
|
|
'subissue_label' => $result['subissue']['label'] ?? null,
|
|
'contact_name' => $result['contact']['name'] ?? null,
|
|
'contact_email' => $result['contact']['email'] ?? null,
|
|
'contact_phone' => $result['contact']['telefon'] ?? null,
|
|
'organisation' => $result['contact']['organisation'] ?? null,
|
|
'message' => $result['contact']['nachricht'] ?? null,
|
|
'answers' => $result['answers'],
|
|
'source_path' => $source,
|
|
'status' => InquiryStatus::Neu->value,
|
|
]));
|
|
} catch (UniqueConstraintViolationException) {
|
|
// Doppelt abgesendet, zwischen Prüfung und Speicherung: dieselbe Anfrage melden.
|
|
$again = Inquiry::query()->where('submission_token', hash('sha256', $token['n']))->firstOrFail();
|
|
|
|
return ['reference' => $again->reference, 'created' => false];
|
|
}
|
|
|
|
// Erst nach der Speicherung benachrichtigen. Ein Fehler hier verliert die Anfrage nie.
|
|
try {
|
|
SendInquiryNotification::dispatch($inquiry->id, url('/verwaltung/anfragen/'.$inquiry->id))->afterCommit();
|
|
} catch (Throwable $e) {
|
|
report($e);
|
|
$inquiry->forceFill(['notification_error' => 'Die Benachrichtigung konnte nicht eingereiht werden: '.Str::limit($e->getMessage(), 300)])->save();
|
|
}
|
|
|
|
return ['reference' => $inquiry->reference, 'created' => true];
|
|
}
|
|
|
|
/**
|
|
* Wertet das Formular für Eingaben aus und prüft sie. Wird auch von der Vorschau verwendet.
|
|
*
|
|
* @param array<string, mixed> $form
|
|
* @param array<string, mixed> $values
|
|
* @return array{answers: list<array<string, mixed>>, contact: array<string, string>, issue: ?array<string, string>, subissue: ?array<string, string>}
|
|
*
|
|
* @throws SubmissionException
|
|
*/
|
|
public function process(array $form, array $values): array
|
|
{
|
|
$known = array_merge(array_keys((array) $form['fields']), ['anliegen', 'unteranliegen']);
|
|
|
|
foreach (array_keys($values) as $key) {
|
|
if (! is_string($key) || ! in_array($key, $known, true)) {
|
|
throw new SubmissionException('Die Eingaben sind ungültig.');
|
|
}
|
|
}
|
|
|
|
$state = $this->evaluator->evaluate($form, $values);
|
|
$errors = [];
|
|
|
|
// Anliegen: Auswahl aus dem zugelassenen Rahmen. Ein abweichender Wert ist eine Manipulation, auch wenn das Feld
|
|
// nicht sichtbar ist (zum Beispiel weil nur ein Anliegen zugelassen ist).
|
|
if ($state['issue_active']) {
|
|
foreach (['anliegen', 'unteranliegen'] as $key) {
|
|
$raw = $values[$key] ?? null;
|
|
$selected = $key === 'anliegen' ? $state['issue'] : $state['subissue'];
|
|
$filled = $raw !== null && $raw !== '';
|
|
|
|
if (! $filled && ($state['required'][$key] ?? false)) {
|
|
$errors[$key] = 'Bitte treffen Sie eine Auswahl.';
|
|
} elseif ($filled && $raw !== $selected) {
|
|
$errors[$key] = 'Bitte wählen Sie einen der angebotenen Werte.';
|
|
}
|
|
}
|
|
}
|
|
|
|
$answers = [];
|
|
$contact = [];
|
|
$steps = [];
|
|
|
|
foreach ((array) $form['steps'] as $step) {
|
|
foreach ($step['items'] as $item) {
|
|
if ($item['kind'] !== 'group') {
|
|
continue;
|
|
}
|
|
|
|
foreach ($item['fields'] as $row) {
|
|
$key = $row['field'];
|
|
$steps[$key] = [$step['title'], $item['label']];
|
|
|
|
if (! ($state['fields'][$key] ?? false)) {
|
|
continue;
|
|
}
|
|
|
|
$field = $form['fields'][$key];
|
|
[$value, $error] = FieldValue::check($field, $values[$key] ?? null, (bool) ($state['required'][$key] ?? false));
|
|
|
|
if ($error !== null) {
|
|
$errors[$key] = $error;
|
|
|
|
continue;
|
|
}
|
|
|
|
if ($value === null) {
|
|
continue;
|
|
}
|
|
|
|
$display = FieldValue::display($field, $value);
|
|
$answers[] = [
|
|
'key' => $key,
|
|
'label' => $field['label'],
|
|
'type' => $field['type'],
|
|
'value' => $value,
|
|
'display' => $display,
|
|
'step' => $steps[$key][0],
|
|
'group' => $steps[$key][1],
|
|
];
|
|
|
|
if ($field['purpose'] !== null) {
|
|
$contact[$field['purpose']] = $display;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
if ($errors !== []) {
|
|
throw new SubmissionException('Bitte prüfen Sie Ihre Angaben.', $errors);
|
|
}
|
|
|
|
$issue = $this->issueEntry($form, $state['issue']);
|
|
$subissue = $issue === null ? null : $this->subissueEntry($form, $state['issue'], $state['subissue']);
|
|
|
|
$name = $contact['name'] ?? trim(($contact['vorname'] ?? '').' '.($contact['nachname'] ?? ''));
|
|
|
|
return [
|
|
'answers' => $answers,
|
|
'contact' => array_filter([
|
|
'name' => $name,
|
|
'email' => $contact['email'] ?? null,
|
|
'telefon' => $contact['telefon'] ?? null,
|
|
'organisation' => $contact['organisation'] ?? null,
|
|
'nachricht' => $contact['nachricht'] ?? null,
|
|
], fn (?string $value): bool => $value !== null && $value !== ''),
|
|
'issue' => $issue,
|
|
'subissue' => $subissue,
|
|
];
|
|
}
|
|
|
|
/**
|
|
* @param array<string, mixed> $form
|
|
* @return ?array{key: string, label: string}
|
|
*/
|
|
private function issueEntry(array $form, ?string $key): ?array
|
|
{
|
|
foreach ((array) $form['issues'] as $issue) {
|
|
if ($issue['key'] === $key) {
|
|
return ['key' => $issue['key'], 'label' => $issue['label']];
|
|
}
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
/**
|
|
* @param array<string, mixed> $form
|
|
* @return ?array{key: string, label: string}
|
|
*/
|
|
private function subissueEntry(array $form, ?string $issue, ?string $key): ?array
|
|
{
|
|
foreach ((array) $form['issues'] as $top) {
|
|
if ($top['key'] !== $issue) {
|
|
continue;
|
|
}
|
|
|
|
foreach ($top['children'] as $child) {
|
|
if ($child['key'] === $key) {
|
|
return ['key' => $child['key'], 'label' => $child['label']];
|
|
}
|
|
}
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
private function reference(): string
|
|
{
|
|
do {
|
|
$reference = 'LF-'.now()->format('ymd').'-'.Str::upper(substr(str_replace(['0', 'O', '1', 'I', 'L'], '', Str::upper(Str::random(12))), 0, 5));
|
|
} while (strlen($reference) < 12 || Inquiry::query()->where('reference', $reference)->exists());
|
|
|
|
return $reference;
|
|
}
|
|
}
|