Formulare, WordPress-Import und E-Mail-Versand
Some checks failed
CI / PHP 8.3 / mariadb:10.6 (pull_request) Successful in 2m0s
CI / PHP 8.4 / mariadb:10.6 (pull_request) Successful in 2m7s
CI / PHP 8.3 / mariadb:11.4 (pull_request) Successful in 2m11s
CI / PHP 8.4 / mariadb:11.4 (pull_request) Successful in 2m7s
CI / PHP 8.3 / mysql:8.0 (pull_request) Failing after 2m52s
CI / PHP 8.4 / mysql:8.0 (pull_request) Failing after 3m2s
CI / PHP 8.3 / mysql:8.4 (pull_request) Failing after 2m31s
CI / PHP 8.4 / mysql:8.4 (pull_request) Failing after 2m27s
CI / Build-Artefakte aktuell (pull_request) Successful in 53s

- Formular-Plugin: Baukasten mit 13 Feldtypen, Bedingungen, Vorbelegung
  aus dem Profil, Datei-Uploads (geschützt), anonyme Formulare, „nur einmal“,
  Einsendeschluss, Sichtbarkeit, Löschfrist; Einsendungen im Backend und per
  Mail (optional ohne Angaben, Kopie an die Person); Rechte je Formular und
  Rolle für Ansehen/Export und Löschen; CSV für Excel; Pagebuilder-Block
- WordPress-Import (Plugin): WXR-Datei einlesen, Kategorien/Personen zuordnen,
  Beiträge mit Status, Datum, Beitragsbild und Bildern im Text übernehmen,
  optional Seiten mit Hierarchie; in Portionen, wiederholbar ohne Doppelungen
- E-Mail-Versand im Admin (SMTP, verschlüsseltes Passwort, Test-Mail)
- Speichertest unabhängig vom Verbrauch der Test-Suite

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Friederich Loheide 2026-09-26 09:20:54 +00:00
parent f3987e8386
commit 11123fecc0
118 changed files with 4446 additions and 169 deletions

View file

@ -0,0 +1,57 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('forms', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->string('slug', 120)->unique();
$table->text('description')->nullable();
$table->json('fields');
$table->json('settings')->nullable();
$table->boolean('is_open')->default(true);
$table->timestamp('closes_at')->nullable();
$table->foreignId('created_by')->nullable()->constrained('users')->nullOnDelete();
$table->timestamps();
});
Schema::create('form_submissions', function (Blueprint $table) {
$table->id();
$table->foreignId('form_id')->constrained('forms')->cascadeOnDelete();
// Bei anonymen Formularen leer; „nur einmal ausfüllen“ prüft dann user_hash.
$table->foreignId('user_id')->nullable()->constrained('users')->nullOnDelete();
$table->string('user_hash', 64)->nullable();
$table->json('data');
$table->timestamp('read_at')->nullable();
$table->timestamps();
$table->index(['form_id', 'created_at']);
$table->index(['form_id', 'user_hash']);
$table->index(['form_id', 'user_id']);
});
Schema::create('form_files', function (Blueprint $table) {
$table->id();
$table->foreignId('submission_id')->constrained('form_submissions')->cascadeOnDelete();
$table->string('field', 80);
$table->string('name');
$table->string('path');
$table->string('mime', 150)->nullable();
$table->unsignedBigInteger('size')->default(0);
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('form_files');
Schema::dropIfExists('form_submissions');
Schema::dropIfExists('forms');
}
};

View file

@ -0,0 +1,13 @@
{
"slug": "forms",
"name": "Formulare",
"version": "1.0.0",
"description": "Formulare zusammenstellen – Anträge, Anmeldungen, Umfragen, Meldungen. Ergebnisse per E-Mail und im Backend, Zugriff je Formular und Rolle.",
"author": "Inhaus",
"namespace": "Inhaus\\Plugins\\Forms\\",
"class": "Inhaus\\Plugins\\Forms\\FormsPlugin",
"requires": {
"core": ">=0.6.0",
"php": ">=8.3"
}
}

View file

@ -0,0 +1,21 @@
<script setup>
import { inject } from 'vue';
import FormRenderer from '../components/FormRenderer.vue';
defineProps({ block: { type: Object, required: true } });
const editing = inject('pagebuilder:editing', false);
</script>
<template>
<section v-if="block.props" class="rounded-lg border bg-card p-5 @3xl:p-8">
<template v-if="block.data.show_title">
<h3 class="text-xl font-semibold tracking-tight">{{ block.props.title }}</h3>
<p v-if="block.props.description" class="mt-2 mb-6 text-sm leading-relaxed whitespace-pre-line text-muted-foreground">{{ block.props.description }}</p>
</template>
<div :class="{ 'pointer-events-none opacity-80': editing }">
<FormRenderer :key="block.props.id" :form="block.props" />
</div>
</section>
<p v-else-if="editing" class="rounded-lg border border-dashed p-4 text-sm text-muted-foreground">Bitte rechts ein Formular auswählen.</p>
</template>

View file

@ -0,0 +1,199 @@
<script setup>
import { computed } from 'vue';
import { useForm, usePage } from '@inertiajs/vue3';
import { CircleCheck, EyeOff, LoaderCircle, Paperclip, Send, X } from '@lucide/vue';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import NativeSelect from '@/components/NativeSelect.vue';
/**
* Stellt ein Formular dar (Formularseite und Pagebuilder-Block).
* Bedingungen werden hier für die Anzeige und auf dem Server für die Prüfung ausgewertet.
*/
const props = defineProps({
form: { type: Object, required: true },
compact: { type: Boolean, default: false },
});
const page = usePage();
const inputTypes = ['text', 'textarea', 'email', 'phone', 'number', 'date', 'select', 'radio', 'checkboxes', 'checkbox', 'file'];
function initial(field) {
const prefilled = props.form.prefill?.[field.key];
if (field.type === 'checkboxes' || field.type === 'file') return [];
if (field.type === 'checkbox') return false;
return prefilled ?? '';
}
const data = useForm({
answers: Object.fromEntries(props.form.fields.filter((f) => inputTypes.includes(f.type)).map((f) => [f.key, initial(f)])),
});
const submitted = computed(() => page.props.flash?.form_submitted === props.form.id);
function isVisible(field, depth = 0) {
if (!field.condition || depth > 10) return true;
const other = props.form.fields.find((f) => f.key === field.condition.field);
if (!other || !isVisible(other, depth + 1)) return false;
const raw = data.answers[field.condition.field];
const values = (Array.isArray(raw) ? raw : raw === true ? ['1'] : raw === false || raw === '' || raw == null ? [] : [String(raw)]).map(String);
const expected = field.condition.value ?? '';
switch (field.condition.operator) {
case 'not_equals': return !values.includes(expected);
case 'filled': return values.length > 0;
case 'empty': return values.length === 0;
default: return values.includes(expected);
}
}
const visibleFields = computed(() => props.form.fields.filter((field) => isVisible(field)));
function error(field) {
return data.errors[`answers.${field.key}`] ?? Object.entries(data.errors).find(([key]) => key.startsWith(`answers.${field.key}.`))?.[1];
}
function toggleOption(field, option) {
const values = new Set(data.answers[field.key]);
values.has(option) ? values.delete(option) : values.add(option);
data.answers[field.key] = [...values];
}
function addFiles(field, event) {
const files = [...(event.target.files ?? [])];
data.answers[field.key] = field.multiple ? [...data.answers[field.key], ...files].slice(0, 10) : files.slice(0, 1);
event.target.value = '';
}
function removeFile(field, index) {
data.answers[field.key] = data.answers[field.key].filter((_, i) => i !== index);
}
function submit() {
const visibleKeys = new Set(visibleFields.value.map((f) => f.key));
data.transform((values) => ({
answers: Object.fromEntries(Object.entries(values.answers).filter(([key]) => visibleKeys.has(key))),
})).post(props.form.url, {
forceFormData: true,
preserveScroll: true,
onSuccess: () => {
if (page.props.flash?.form_submitted === props.form.id) data.reset();
},
});
}
const formatSize = (bytes) => (bytes > 1024 * 1024 ? `${(bytes / 1024 / 1024).toFixed(1).replace('.', ',')} MB` : `${Math.max(1, Math.round(bytes / 1024))} KB`);
const fieldId = (field) => `f${props.form.id}-${field.key}`;
</script>
<template>
<div v-if="submitted" class="flex gap-3 rounded-lg border border-emerald-200 bg-emerald-50 p-5 text-emerald-950 dark:border-emerald-900 dark:bg-emerald-950/40 dark:text-emerald-100" role="status">
<CircleCheck class="mt-0.5 size-5 shrink-0 text-emerald-600" />
<div>
<p class="font-medium whitespace-pre-line">{{ form.confirmation }}</p>
<p v-if="form.send_copy" class="mt-1 text-sm opacity-80">Eine Kopie Ihrer Angaben ist per E-Mail unterwegs.</p>
</div>
</div>
<p v-else-if="form.already_submitted" class="rounded-lg border bg-muted px-5 py-4 text-sm">Sie haben dieses Formular bereits ausgefüllt. Vielen Dank!</p>
<p v-else-if="!form.open" class="rounded-lg border bg-muted px-5 py-4 text-sm">Dieses Formular nimmt keine Einsendungen mehr an.</p>
<form v-else class="grid gap-5 @xl:grid-cols-2" novalidate @submit.prevent="submit">
<p v-if="form.anonymous" class="flex items-start gap-2 rounded-md bg-muted px-3 py-2 text-[13px] text-muted-foreground @xl:col-span-2">
<EyeOff class="mt-0.5 size-4 shrink-0" /> Anonym: Ihr Name und Ihre E-Mail-Adresse werden nicht gespeichert.
</p>
<p v-if="data.errors.form" class="rounded-md bg-destructive/10 px-3 py-2 text-sm text-destructive @xl:col-span-2">{{ data.errors.form }}</p>
<template v-for="field in visibleFields" :key="field.key">
<h3 v-if="field.type === 'heading'" class="pt-2 text-lg font-semibold @xl:col-span-2">{{ field.text }}</h3>
<p v-else-if="field.type === 'paragraph'" class="text-sm leading-relaxed whitespace-pre-line text-muted-foreground @xl:col-span-2">{{ field.text }}</p>
<div v-else class="grid content-start gap-1.5" :class="field.width === 'half' ? '' : '@xl:col-span-2'">
<template v-if="field.type === 'checkbox'">
<label :for="fieldId(field)" class="flex items-start gap-2.5 text-sm">
<input :id="fieldId(field)" v-model="data.answers[field.key]" type="checkbox" class="mt-0.5 size-4 shrink-0 accent-[var(--brand)]" :aria-invalid="!!error(field)" />
<span>{{ field.label }}<span v-if="field.required" class="text-destructive"> *</span></span>
</label>
</template>
<template v-else>
<component :is="['radio', 'checkboxes'].includes(field.type) ? 'span' : 'label'" :for="fieldId(field)" class="text-[13px] font-medium" :id="`${fieldId(field)}-label`">
{{ field.label }}<span v-if="field.required" class="text-destructive"> *</span>
</component>
<Textarea v-if="field.type === 'textarea'" :id="fieldId(field)" v-model="data.answers[field.key]" :rows="field.rows ?? 4" :maxlength="field.max" :aria-invalid="!!error(field)" />
<NativeSelect v-else-if="field.type === 'select'" :id="fieldId(field)" v-model="data.answers[field.key]" :options="field.options.map((o) => ({ value: o, label: o }))" placeholder="Bitte wählen …" />
<div v-else-if="field.type === 'radio' || field.type === 'checkboxes'" class="grid gap-1.5" role="group" :aria-labelledby="`${fieldId(field)}-label`">
<label v-for="option in field.options" :key="option" class="flex items-center gap-2.5 text-sm">
<input
v-if="field.type === 'radio'"
v-model="data.answers[field.key]"
type="radio"
:name="fieldId(field)"
:value="option"
class="size-4 accent-[var(--brand)]"
/>
<input
v-else
type="checkbox"
:checked="data.answers[field.key].includes(option)"
class="size-4 accent-[var(--brand)]"
@change="toggleOption(field, option)"
/>
{{ option }}
</label>
</div>
<div v-else-if="field.type === 'file'" class="grid gap-2">
<ul v-if="data.answers[field.key].length" class="grid gap-1">
<li v-for="(file, index) in data.answers[field.key]" :key="index" class="flex items-center gap-2 rounded-md border bg-card px-3 py-1.5 text-sm">
<Paperclip class="size-4 shrink-0 text-muted-foreground" />
<span class="min-w-0 flex-1 truncate">{{ file.name }}</span>
<span class="text-xs text-muted-foreground">{{ formatSize(file.size) }}</span>
<button type="button" class="grid size-6 place-items-center rounded hover:bg-accent" :aria-label="`${file.name} entfernen`" @click="removeFile(field, index)"><X class="size-3.5" /></button>
</li>
</ul>
<label v-if="field.multiple || !data.answers[field.key].length" class="flex h-10 cursor-pointer items-center justify-center gap-2 rounded-md border border-dashed text-sm text-muted-foreground hover:border-brand-300 hover:text-foreground">
<Paperclip class="size-4" /> {{ field.multiple ? 'Dateien auswählen' : 'Datei auswählen' }}
<input :id="fieldId(field)" type="file" class="sr-only" :accept="field.accept" :multiple="field.multiple" @change="addFiles(field, $event)" />
</label>
</div>
<Input
v-else
:id="fieldId(field)"
v-model="data.answers[field.key]"
:type="{ email: 'email', phone: 'tel', number: 'number', date: 'date' }[field.type] ?? 'text'"
:placeholder="field.placeholder"
:maxlength="field.type === 'text' ? field.max : undefined"
:min="field.type === 'number' ? field.min : undefined"
:max="field.type === 'number' ? field.max : undefined"
:aria-invalid="!!error(field)"
/>
</template>
<p v-if="error(field)" class="text-[13px] text-destructive">{{ error(field) }}</p>
<p v-else-if="field.help" class="text-[13px] text-muted-foreground">
{{ field.help }}<template v-if="field.type === 'file' && field.max_size"> (höchstens {{ field.max_size }} MB)</template>
</p>
</div>
</template>
<div class="flex items-center gap-4 border-t pt-5 @xl:col-span-2">
<Button type="submit" :disabled="data.processing">
<LoaderCircle v-if="data.processing" class="animate-spin" />
<Send v-else />
{{ form.submit_label }}
</Button>
<span class="text-xs text-muted-foreground">* Pflichtfeld</span>
</div>
</form>
</template>

View file

@ -0,0 +1,33 @@
<script setup>
import { Link } from '@inertiajs/vue3';
import { ChevronRight, ClipboardList } from '@lucide/vue';
import EmptyState from '@/components/EmptyState.vue';
import AppLayout from '@/layouts/AppLayout.vue';
import { formatDate } from '@/lib/format';
defineProps({
forms: { type: Array, required: true },
});
</script>
<template>
<AppLayout title="Formulare">
<div class="mb-6">
<h1 class="text-2xl font-semibold tracking-tight">Formulare</h1>
<p class="mt-1 text-sm text-muted-foreground">Anträge, Anmeldungen und Meldungen – direkt online ausfüllen.</p>
</div>
<div v-if="forms.length" class="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
<Link v-for="form in forms" :key="form.id" :href="form.url" class="group flex gap-4 rounded-lg border bg-card p-5 hover:border-brand-300">
<span class="grid size-10 shrink-0 place-items-center rounded-lg bg-brand-soft text-brand-text"><ClipboardList class="size-5" /></span>
<span class="min-w-0 flex-1">
<span class="block font-semibold group-hover:underline">{{ form.title }}</span>
<span v-if="form.description" class="mt-1 line-clamp-2 block text-sm text-muted-foreground">{{ form.description }}</span>
<span v-if="form.closes_at" class="mt-2 block text-xs text-muted-foreground">Bis {{ formatDate(form.closes_at) }}</span>
</span>
<ChevronRight class="mt-2.5 size-4 shrink-0 text-muted-foreground" />
</Link>
</div>
<div v-else class="rounded-lg border bg-card"><EmptyState :icon="ClipboardList" title="Keine Formulare" text="Derzeit sind keine Formulare für Sie freigegeben." /></div>
</AppLayout>
</template>

View file

@ -0,0 +1,29 @@
<script setup>
import { Link } from '@inertiajs/vue3';
import { ArrowLeft, CalendarClock } from '@lucide/vue';
import AppLayout from '@/layouts/AppLayout.vue';
import { formatDate } from '@/lib/format';
import FormRenderer from '../components/FormRenderer.vue';
defineProps({
form: { type: Object, required: true },
});
</script>
<template>
<AppLayout :title="form.title">
<div class="mx-auto max-w-3xl">
<Link href="/formulare" class="mb-6 inline-flex items-center gap-1.5 text-sm font-medium text-muted-foreground hover:text-foreground">
<ArrowLeft class="size-4" /> Alle Formulare
</Link>
<h1 class="text-3xl font-semibold tracking-tight">{{ form.title }}</h1>
<p v-if="form.description" class="mt-3 leading-relaxed whitespace-pre-line text-muted-foreground">{{ form.description }}</p>
<p v-if="form.closes_at && form.open" class="mt-3 inline-flex items-center gap-1.5 text-[13px] text-muted-foreground">
<CalendarClock class="size-4" /> Einsendeschluss: {{ formatDate(form.closes_at) }}
</p>
<div class="@container mt-8 rounded-lg border bg-card p-5 sm:p-8">
<FormRenderer :form="form" />
</div>
</div>
</AppLayout>
</template>

View file

@ -0,0 +1,6 @@
<x-filament-panels::page>
@if ($this->record->isAnonymous())
<p class="text-sm text-gray-500">Anonymes Formular – Namen werden nicht gespeichert.</p>
@endif
{{ $this->table }}
</x-filament-panels::page>

View file

@ -0,0 +1,37 @@
<!doctype html>
<html lang="de">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width"></head>
<body style="margin:0;background:#f4f5f7;font-family:-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif;color:#1a1d21">
<div style="max-width:640px;margin:0 auto;padding:24px">
<p style="margin:0 0 16px;font-size:13px;color:#5f6670">{{ $portalName }}</p>
<div style="background:#fff;border:1px solid #e3e5e8;border-radius:8px;padding:24px">
<h1 style="margin:0 0 4px;font-size:20px">{{ $form->title }}</h1>
<p style="margin:0 0 20px;font-size:14px;color:#5f6670">
@if ($copy)
Vielen Dank! Hier eine Kopie Ihrer Angaben vom {{ $submission->created_at->timezone(config('app.timezone'))->format('d.m.Y, H:i') }} Uhr.
@else
Eingegangen am {{ $submission->created_at->timezone(config('app.timezone'))->format('d.m.Y, H:i') }} Uhr
– {{ $person ? 'von '.$person->name.' ('.$person->email.')' : 'anonym' }}.
@endif
</p>
@if ($answers !== null)
<table style="width:100%;border-collapse:collapse;font-size:14px">
@foreach ($answers as $answer)
<tr>
<td style="padding:8px 12px 8px 0;border-top:1px solid #e3e5e8;vertical-align:top;color:#5f6670;width:40%">{{ $answer['label'] }}</td>
<td style="padding:8px 0;border-top:1px solid #e3e5e8;vertical-align:top;white-space:pre-line">{{ $answer['value'] !== '' ? $answer['value'] : '–' }}</td>
</tr>
@endforeach
</table>
@else
<p style="font-size:14px">Die Angaben sind aus Datenschutzgründen nicht in dieser E-Mail enthalten.</p>
@endif
@if ($resultsUrl)
<p style="margin:24px 0 0"><a href="{{ $resultsUrl }}" style="display:inline-block;background:#1a1d21;color:#fff;text-decoration:none;padding:10px 16px;border-radius:6px;font-size:14px">Ergebnisse im Portal öffnen</a></p>
@endif
</div>
</div>
</body>
</html>

View file

@ -0,0 +1,14 @@
<?php
use Illuminate\Support\Facades\Route;
use Inhaus\Plugins\Forms\Http\Controllers\FormController;
use Inhaus\Plugins\Forms\Http\Controllers\FormResultsController;
Route::middleware('auth')->group(function () {
Route::get('/formulare', [FormController::class, 'index'])->name('forms.index');
Route::get('/formulare/{form:slug}', [FormController::class, 'show'])->name('forms.show');
Route::post('/formulare/{form:slug}', [FormController::class, 'submit'])->middleware('throttle:20,1')->name('forms.submit');
Route::get('/formulare/dateien/{file}', [FormResultsController::class, 'file'])->name('forms.file');
Route::get('/admin/formulare/{form}/export', [FormResultsController::class, 'export'])->name('forms.export');
});

View file

@ -0,0 +1,256 @@
<?php
namespace Inhaus\Plugins\Forms\Filament\Resources\Forms;
use App\Filament\Components\AudienceSection;
use App\Filament\Components\RoleGrantSelect;
use BackedEnum;
use Filament\Actions\Action;
use Filament\Actions\DeleteAction;
use Filament\Actions\EditAction;
use Filament\Forms\Components\Builder;
use Filament\Forms\Components\Builder\Block;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TagsInput;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Fieldset;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Tabs;
use Filament\Schemas\Components\Tabs\Tab;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\IconColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Inhaus\Plugins\Forms\Filament\Resources\Forms\Pages\CreateForm;
use Inhaus\Plugins\Forms\Filament\Resources\Forms\Pages\EditForm;
use Inhaus\Plugins\Forms\Filament\Resources\Forms\Pages\FormResults;
use Inhaus\Plugins\Forms\Filament\Resources\Forms\Pages\ListForms;
use Inhaus\Plugins\Forms\FormFields;
use Inhaus\Plugins\Forms\Models\Form;
use Inhaus\Plugins\Forms\Models\FormSubmission;
use UnitEnum;
class FormResource extends Resource
{
protected static ?string $model = Form::class;
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedClipboardDocumentList;
protected static string|UnitEnum|null $navigationGroup = 'Inhalte';
protected static ?int $navigationSort = 5;
protected static ?string $modelLabel = 'Formular';
protected static ?string $pluralModelLabel = 'Formulare';
protected static ?string $slug = 'formulare';
protected static ?string $recordTitleAttribute = 'title';
public static function form(Schema $schema): Schema
{
return $schema->columns(1)->components([
Tabs::make()->persistTabInQueryString()->tabs([
Tab::make('Felder')->icon(Heroicon::OutlinedQueueList)->schema([
TextInput::make('title')->label('Titel')->required()->maxLength(200),
Textarea::make('description')->label('Einleitung')->rows(2)->maxLength(2000),
Builder::make('fields')
->label('Felder')
->blocks(static::fieldBlocks())
->addActionLabel('Feld hinzufügen')
->blockPickerColumns(3)
->blockNumbers(false)
->collapsible()
->collapsed(fn (string $operation) => $operation === 'edit')
->cloneable()
->reorderableWithButtons()
->minItems(1)
->default([]),
]),
Tab::make('Einstellungen')->icon(Heroicon::OutlinedCog6Tooth)->columns(2)->schema([
Toggle::make('is_open')->label('Nimmt Einsendungen an')->default(true),
DateTimePicker::make('closes_at')->label('Einsendeschluss')->native(false)->seconds(false)->displayFormat('d.m.Y H:i'),
TextInput::make('settings.submit_label')->label('Beschriftung des Absende-Knopfs')->placeholder('Absenden')->maxLength(60),
Toggle::make('settings.once_per_user')->label('Jede Person nur einmal')->inline(false),
Textarea::make('settings.confirmation')->label('Bestätigung nach dem Absenden')->placeholder('Vielen Dank! Ihre Angaben sind eingegangen.')->rows(2)->maxLength(1000)->columnSpanFull(),
Toggle::make('settings.anonymous')->label('Anonym')
->helperText('Name und E-Mail-Adresse werden nicht gespeichert und nicht mitgeschickt – z. B. für Umfragen oder vertrauliche Meldungen an die MAV.')
->columnSpanFull(),
TextInput::make('settings.retention_days')->label('Einsendungen automatisch löschen nach')->numeric()->minValue(1)->maxValue(3650)->suffix('Tagen')
->helperText('Leer = nicht automatisch löschen.'),
]),
Tab::make('Benachrichtigung')->icon(Heroicon::OutlinedEnvelope)->schema([
TagsInput::make('settings.notify_emails')->label('E-Mail an')->placeholder('personal@firma.de')
->nestedRecursiveRules(['email'])
->helperText('Bei jeder Einsendung. Auch Funktionspostfächer möglich.'),
Toggle::make('settings.notify_viewers')->label('Alle mit Zugriff auf die Ergebnisse benachrichtigen (E-Mail und Glocke im Portal)'),
Toggle::make('settings.mail_answers')->label('Angaben in die E-Mail aufnehmen')->default(true)
->helperText('Aus, wenn die Angaben vertraulich sind – die E-Mail enthält dann nur einen Link zu den Ergebnissen.'),
Toggle::make('settings.send_copy')->label('Kopie an die ausfüllende Person'),
]),
Tab::make('Zugriff')->icon(Heroicon::OutlinedLockClosed)->schema([
Section::make('Ergebnisse')
->description('Welche Rollen die Einsendungen dieses Formulars sehen – z. B. nur die Personalabteilung.')
->columns(3)
->visible(fn () => auth()->user()->can('forms.manage') || auth()->user()->can('roles.manage'))
->schema([
RoleGrantSelect::make('result_viewers', 'Ansehen und exportieren', 'forms.results', 'form'),
RoleGrantSelect::make('result_deleters', 'Löschen', 'forms.results.delete', 'form'),
RoleGrantSelect::make('editors', 'Formular bearbeiten', 'forms.edit', 'form'),
]),
AudienceSection::make('form', 'Wer das Formular ausfüllen darf. Leer lassen = alle.'),
]),
]),
]);
}
/**
* @return list<Block>
*/
public static function fieldBlocks(): array
{
$common = fn (array $extra = [], bool $prefill = false) => [
TextInput::make('label')->label('Bezeichnung')->required()->maxLength(200)->live(onBlur: true)->columnSpan(2),
Toggle::make('required')->label('Pflichtfeld')->inline(false),
...$extra,
TextInput::make('help')->label('Hinweis unter dem Feld')->maxLength(300)->columnSpan(2),
Select::make('width')->label('Breite')->options(['full' => 'Volle Breite', 'half' => 'Halbe Breite'])->default('full')->native(false),
...($prefill ? [Select::make('prefill')->label('Vorbelegen mit')->options(fn () => FormFields::prefillOptions())->placeholder('–')->native(false)] : []),
static::conditionFieldset(),
TextInput::make('key')->label('Technischer Schlüssel')->helperText('Für Export und Bedingungen. Leer = aus der Bezeichnung.')->maxLength(60)->alphaDash(),
];
$options = TagsInput::make('options')->label('Auswahlmöglichkeiten')->placeholder('Eintrag eingeben und Enter')->required()->reorderable()->columnSpanFull();
return [
Block::make('text')->label(static::blockLabel('text'))->icon(Heroicon::OutlinedPencil)->columns(3)
->schema($common([TextInput::make('placeholder')->label('Platzhalter')->maxLength(100), TextInput::make('max')->label('Höchstlänge')->numeric()->minValue(1)->maxValue(255)], prefill: true)),
Block::make('textarea')->label(static::blockLabel('textarea'))->icon(Heroicon::OutlinedBars3BottomLeft)->columns(3)
->schema($common([TextInput::make('rows')->label('Zeilen')->numeric()->minValue(2)->maxValue(20)->default(4), TextInput::make('max')->label('Höchstlänge')->numeric()->minValue(1)->maxValue(10000)])),
Block::make('email')->label(static::blockLabel('email'))->icon(Heroicon::OutlinedAtSymbol)->columns(3)->schema($common(prefill: true)),
Block::make('phone')->label(static::blockLabel('phone'))->icon(Heroicon::OutlinedPhone)->columns(3)->schema($common(prefill: true)),
Block::make('number')->label(static::blockLabel('number'))->icon(Heroicon::OutlinedHashtag)->columns(3)
->schema($common([TextInput::make('min')->label('Mindestens')->numeric(), TextInput::make('max')->label('Höchstens')->numeric()])),
Block::make('date')->label(static::blockLabel('date'))->icon(Heroicon::OutlinedCalendarDays)->columns(3)->schema($common()),
Block::make('select')->label(static::blockLabel('select'))->icon(Heroicon::OutlinedChevronUpDown)->columns(3)->schema($common([$options])),
Block::make('radio')->label(static::blockLabel('radio'))->icon(Heroicon::OutlinedStop)->columns(3)->schema($common([$options])),
Block::make('checkboxes')->label(static::blockLabel('checkboxes'))->icon(Heroicon::OutlinedCheckCircle)->columns(3)
->schema($common([$options, TextInput::make('min')->label('Mindestens … auswählen')->numeric()->minValue(0), TextInput::make('max')->label('Höchstens … auswählen')->numeric()->minValue(1)])),
Block::make('checkbox')->label(static::blockLabel('checkbox'))->icon(Heroicon::OutlinedCheck)->columns(3)
->schema($common()),
Block::make('file')->label(static::blockLabel('file'))->icon(Heroicon::OutlinedPaperClip)->columns(3)
->schema($common([
Select::make('accept')->label('Erlaubte Dateien')->options(['documents' => 'Dokumente (PDF, Office …)', 'images' => 'Bilder', 'any' => 'Dokumente und Bilder'])->default('any')->native(false),
TextInput::make('max_size')->label('Höchstgröße')->numeric()->minValue(1)->maxValue(50)->default(10)->suffix('MB'),
Toggle::make('multiple')->label('Mehrere Dateien (bis 10)')->inline(false),
])),
Block::make('heading')->label(static::blockLabel('heading'))->icon(Heroicon::OutlinedH2)
->schema([TextInput::make('text')->label('Text')->required()->maxLength(200), static::conditionFieldset()]),
Block::make('paragraph')->label(static::blockLabel('paragraph'))->icon(Heroicon::OutlinedInformationCircle)
->schema([Textarea::make('text')->label('Text')->required()->rows(3)->maxLength(3000), static::conditionFieldset()]),
];
}
/**
* Titel eines Feldes im Baukasten: Typ und Bezeichnung (auch zugeklappt lesbar).
*/
private static function blockLabel(string $type): \Closure
{
return function (?array $state) use ($type) {
$text = $state['label'] ?? $state['text'] ?? null;
$suffix = ($state['required'] ?? false) ? ' *' : '';
$conditional = filled($state['condition_field'] ?? null) ? ' (bedingt)' : '';
return FormFields::TYPES[$type].($text ? ': '.mb_strimwidth((string) $text, 0, 70, '…') : '').$suffix.$conditional;
};
}
private static function conditionFieldset(): Fieldset
{
return Fieldset::make('Nur anzeigen, wenn …')->columns(3)->columnSpanFull()->schema([
Select::make('condition_field')->label('Feld')->placeholder('– immer anzeigen –')->native(false)
->options(function (Get $get) {
// Alle Eingabefelder des Formulars (Bezeichnung → Schlüssel).
$fields = FormFields::normalize((array) $get('../../../fields'));
return collect($fields)->reject(fn ($f) => in_array($f['type'], FormFields::LAYOUT_TYPES, true))
->mapWithKeys(fn ($f) => [$f['data']['key'] => ($f['data']['label'] ?? $f['data']['key'])])->all();
})
->live(),
Select::make('condition_operator')->label('Bedingung')->native(false)->default('equals')
->options(['equals' => 'ist gleich', 'not_equals' => 'ist nicht', 'contains' => 'enthält (Mehrfachauswahl)', 'filled' => 'ist ausgefüllt', 'empty' => 'ist leer'])
->visible(fn (Get $get) => filled($get('condition_field'))),
TextInput::make('condition_value')->label('Wert')->maxLength(200)
->visible(fn (Get $get) => filled($get('condition_field')) && ! in_array($get('condition_operator'), ['filled', 'empty'], true))
->helperText('Bei Kontrollkästchen: 1 für „angehakt“.'),
]);
}
/**
* Sichtbar sind Formulare, die man bearbeiten oder deren Ergebnisse man sehen darf.
*/
public static function getEloquentQuery(): EloquentBuilder
{
$user = auth()->user();
if (! $user || $user->can('forms.manage')) {
return parent::getEloquentQuery();
}
$ids = collect([$user->permissions()->ids('forms.edit', 'form'), $user->permissions()->ids('forms.results', 'form')]);
// Streng vergleichen: eine ID-Liste ist nicht „alle“.
return $ids->contains(fn ($value) => $value === true)
? parent::getEloquentQuery()
: parent::getEloquentQuery()->whereIn('id', $ids->flatten()->unique()->values()->all());
}
public static function table(Table $table): Table
{
return $table
->defaultSort('title')
->columns([
TextColumn::make('title')->label('Titel')->searchable()->weight('medium')
->description(fn (Form $record) => $record->url()),
TextColumn::make('submissions_count')->label('Einsendungen')->counts('submissions')->sortable()
->badge()->color(fn (Form $record) => static::unread($record) ? 'primary' : 'gray')
->formatStateUsing(fn ($state, Form $record) => ($unread = static::unread($record)) ? "{$state} ({$unread} neu)" : $state),
IconColumn::make('is_open')->label('Offen')->boolean(),
IconColumn::make('settings.anonymous')->label('Anonym')->boolean()->trueIcon(Heroicon::OutlinedEyeSlash)->falseIcon(false),
TextColumn::make('closes_at')->label('Einsendeschluss')->dateTime('d.m.Y H:i')->placeholder('–'),
])
->recordActions([
Action::make('results')->label('Ergebnisse')->icon(Heroicon::OutlinedTableCells)
->url(fn (Form $record) => static::getUrl('results', ['record' => $record]))
->visible(fn (Form $record) => auth()->user()->can('viewResults', $record)),
EditAction::make()->visible(fn (Form $record) => auth()->user()->can('update', $record)),
DeleteAction::make()->modalDescription('Das Formular und alle Einsendungen samt Dateien werden gelöscht.'),
])
->recordUrl(fn (Form $record) => auth()->user()->can('update', $record)
? static::getUrl('edit', ['record' => $record])
: static::getUrl('results', ['record' => $record]));
}
private static function unread(Form $form): int
{
return once(fn () => FormSubmission::query()->whereNull('read_at')->selectRaw('form_id, count(*) as c')->groupBy('form_id')->pluck('c', 'form_id')->all())[$form->id] ?? 0;
}
public static function getPages(): array
{
return [
'index' => ListForms::route('/'),
'create' => CreateForm::route('/neu'),
'edit' => EditForm::route('/{record}/bearbeiten'),
'results' => FormResults::route('/{record}/ergebnisse'),
];
}
}

View file

@ -0,0 +1,16 @@
<?php
namespace Inhaus\Plugins\Forms\Filament\Resources\Forms\Pages;
use Filament\Resources\Pages\CreateRecord;
use Inhaus\Plugins\Forms\Filament\Resources\Forms\FormResource;
class CreateForm extends CreateRecord
{
protected static string $resource = FormResource::class;
protected function mutateFormDataBeforeCreate(array $data): array
{
return [...$data, 'created_by' => auth()->id()];
}
}

View file

@ -0,0 +1,26 @@
<?php
namespace Inhaus\Plugins\Forms\Filament\Resources\Forms\Pages;
use Filament\Actions\Action;
use Filament\Actions\DeleteAction;
use Filament\Resources\Pages\EditRecord;
use Filament\Support\Icons\Heroicon;
use Inhaus\Plugins\Forms\Filament\Resources\Forms\FormResource;
class EditForm extends EditRecord
{
protected static string $resource = FormResource::class;
protected function getHeaderActions(): array
{
return [
Action::make('view')->label('Ansehen')->icon(Heroicon::OutlinedEye)->color('gray')
->url(fn () => $this->record->url())->openUrlInNewTab(),
Action::make('results')->label('Ergebnisse')->icon(Heroicon::OutlinedTableCells)->color('gray')
->url(fn () => FormResource::getUrl('results', ['record' => $this->record]))
->visible(fn () => auth()->user()->can('viewResults', $this->record)),
DeleteAction::make()->modalDescription('Das Formular und alle Einsendungen samt Dateien werden gelöscht.'),
];
}
}

View file

@ -0,0 +1,141 @@
<?php
namespace Inhaus\Plugins\Forms\Filament\Resources\Forms\Pages;
use App\Support\Audit;
use Filament\Actions\Action;
use Filament\Actions\BulkAction;
use Filament\Actions\DeleteAction;
use Filament\Resources\Pages\Concerns\InteractsWithRecord;
use Filament\Resources\Pages\Page;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Concerns\InteractsWithTable;
use Filament\Tables\Contracts\HasTable;
use Filament\Tables\Filters\TernaryFilter;
use Filament\Tables\Table;
use Illuminate\Support\Collection;
use Illuminate\Support\HtmlString;
use Illuminate\Support\Str;
use Inhaus\Plugins\Forms\Filament\Resources\Forms\FormResource;
use Inhaus\Plugins\Forms\FormFields;
use Inhaus\Plugins\Forms\Models\Form;
use Inhaus\Plugins\Forms\Models\FormSubmission;
/**
* Einsendungen eines Formulars – nur für Rollen mit „Ergebnisse ansehen“ für dieses Formular.
*/
class FormResults extends Page implements HasTable
{
use InteractsWithRecord;
use InteractsWithTable;
protected static string $resource = FormResource::class;
protected string $view = 'forms::filament.results';
public function mount(int|string $record): void
{
$this->record = $this->resolveRecord($record);
abort_unless(auth()->user()->can('viewResults', $this->record), 403);
}
public function getTitle(): string
{
return 'Ergebnisse: '.$this->record->title;
}
public function getBreadcrumbs(): array
{
return [FormResource::getUrl() => 'Formulare', 'Ergebnisse'];
}
public function table(Table $table): Table
{
/** @var Form $form */
$form = $this->record;
$inputs = array_slice(FormFields::inputs($form), 0, 4, true);
$canDelete = auth()->user()->can('deleteResults', $form);
return $table
->query(FormSubmission::query()->where('form_id', $form->id)->with(['user:id,name,email', 'files']))
->defaultSort('created_at', 'desc')
->columns([
TextColumn::make('created_at')->label('Eingegangen')->dateTime('d.m.Y H:i')->sortable()
->weight(fn (FormSubmission $s) => $s->read_at ? null : 'bold')
->description(fn (FormSubmission $s) => $s->read_at ? null : 'neu'),
TextColumn::make('user.name')->label('Person')->placeholder('anonym')->searchable()->visible(! $form->isAnonymous()),
...collect($inputs)->map(fn ($label, $key) => TextColumn::make('answer_'.$key)
->label(Str::limit($label, 30))
->state(fn (FormSubmission $s) => Str::limit($s->display($key), 60))
->wrap())->values()->all(),
])
->filters([
TernaryFilter::make('read_at')->label('Gelesen')->nullable()->trueLabel('Gelesen')->falseLabel('Neu'),
])
->recordActions([
Action::make('view')->label('Ansehen')->icon(Heroicon::OutlinedEye)
->modalHeading(fn (FormSubmission $s) => 'Einsendung vom '.$s->created_at->format('d.m.Y, H:i').' Uhr')
->modalContent(fn (FormSubmission $s) => $this->details($s))
->modalSubmitAction(false)
->modalCancelActionLabel('Schließen')
->mountUsing(fn (FormSubmission $s) => $s->read_at ?? $s->forceFill(['read_at' => now()])->save()),
DeleteAction::make()->visible($canDelete)->after(fn (FormSubmission $s) => Audit::log('forms.submission_deleted', ['form' => $form->id, 'submission' => $s->id])),
])
->toolbarActions([
BulkAction::make('markRead')->label('Als gelesen markieren')->icon(Heroicon::OutlinedCheck)
->action(fn (Collection $records) => FormSubmission::query()->whereIn('id', $records->modelKeys())->whereNull('read_at')->update(['read_at' => now()]))
->deselectRecordsAfterCompletion(),
BulkAction::make('delete')->label('Löschen')->icon(Heroicon::OutlinedTrash)->color('danger')->requiresConfirmation()
->visible($canDelete)
->action(function (Collection $records) use ($form) {
$records->each->delete();
Audit::log('forms.submissions_deleted', ['form' => $form->id, 'count' => $records->count()]);
})
->deselectRecordsAfterCompletion(),
])
->emptyStateHeading('Noch keine Einsendungen')
->emptyStateIcon(Heroicon::OutlinedInboxStack);
}
protected function getHeaderActions(): array
{
return [
Action::make('export')->label('Als CSV exportieren')->icon(Heroicon::OutlinedArrowDownTray)
->url(fn () => route('forms.export', $this->record)),
Action::make('edit')->label('Formular bearbeiten')->icon(Heroicon::OutlinedPencilSquare)->color('gray')
->url(fn () => FormResource::getUrl('edit', ['record' => $this->record]))
->visible(fn () => auth()->user()->can('update', $this->record)),
];
}
private function details(FormSubmission $submission): HtmlString
{
$rows = '';
if (! $this->record->isAnonymous()) {
$rows .= self::row('Person', e($submission->user ? $submission->user->name.' ('.$submission->user->email.')' : 'gelöschtes Konto'));
}
foreach ($submission->data as $key => $answer) {
if (($answer['type'] ?? null) === 'file') {
$value = collect($submission->files->where('field', $key))
->map(fn ($file) => '<a href="'.e($file->url()).'" style="color: rgb(var(--primary-600, 37 99 235)); text-decoration: underline">'.e($file->name).'</a>')
->implode('<br>') ?: '–';
} else {
$value = nl2br(e($submission->display($key) ?: '–'));
}
$rows .= self::row(e($answer['label']), $value);
}
return new HtmlString('<table style="width: 100%; border-collapse: collapse; font-size: 0.875rem">'.$rows.'</table>');
}
private static function row(string $label, string $value): string
{
$cell = 'padding: 0.5rem 0; border-top: 1px solid rgba(127, 127, 127, 0.2); vertical-align: top;';
return '<tr><th style="'.$cell.' width: 40%; padding-right: 1rem; text-align: left; font-weight: 500; opacity: 0.7">'.$label.'</th><td style="'.$cell.'">'.$value.'</td></tr>';
}
}

View file

@ -0,0 +1,17 @@
<?php
namespace Inhaus\Plugins\Forms\Filament\Resources\Forms\Pages;
use Filament\Actions\CreateAction;
use Filament\Resources\Pages\ListRecords;
use Inhaus\Plugins\Forms\Filament\Resources\Forms\FormResource;
class ListForms extends ListRecords
{
protected static string $resource = FormResource::class;
protected function getHeaderActions(): array
{
return [CreateAction::make()->label('Formular anlegen')];
}
}

View file

@ -0,0 +1,295 @@
<?php
namespace Inhaus\Plugins\Forms;
use App\Models\User;
use App\Support\ProfileFields;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Rules\File;
use Inhaus\Plugins\Forms\Models\Form;
/**
* Felder eines Formulars: Typen, Bedingungen, Validierung und Aufbereitung.
*
* Gespeichert wird das Format des Formularbaukastens im Admin:
* [['type' => 'text', 'data' => ['label' => 'Name', 'key' => 'name', 'required' => true, …]], …]
*/
class FormFields
{
public const TYPES = [
'text' => 'Textzeile',
'textarea' => 'Mehrzeiliger Text',
'email' => 'E-Mail-Adresse',
'phone' => 'Telefonnummer',
'number' => 'Zahl',
'date' => 'Datum',
'select' => 'Auswahlliste',
'radio' => 'Einfachauswahl',
'checkboxes' => 'Mehrfachauswahl',
'checkbox' => 'Kontrollkästchen (Ja/Nein)',
'file' => 'Datei-Upload',
'heading' => 'Zwischenüberschrift',
'paragraph' => 'Hinweistext',
];
/** Nur Gestaltung, kein Eingabefeld. */
public const LAYOUT_TYPES = ['heading', 'paragraph'];
public const FILE_TYPES = [
'documents' => ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'odt', 'ods', 'ppt', 'pptx', 'txt', 'csv', 'rtf'],
'images' => ['jpg', 'jpeg', 'png', 'webp', 'gif', 'heic'],
'any' => ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'odt', 'ods', 'ppt', 'pptx', 'txt', 'csv', 'rtf', 'jpg', 'jpeg', 'png', 'webp', 'gif', 'heic', 'zip', 'msg', 'eml'],
];
public const PREFILL = [
'name' => 'Name',
'first_name' => 'Vorname',
'last_name' => 'Nachname',
'email' => 'E-Mail-Adresse',
'phone' => 'Telefon',
'mobile' => 'Mobil',
'job_title' => 'Funktion',
'department' => 'Abteilung',
'location' => 'Standort',
];
/**
* Schlüssel ergänzen und eindeutig machen, unbekannte Typen entfernen.
*
* @param array<mixed> $fields
* @return list<array{type: string, data: array<string, mixed>}>
*/
public static function normalize(array $fields): array
{
$result = [];
$used = [];
foreach (array_values($fields) as $index => $field) {
$type = $field['type'] ?? null;
if (! is_array($field) || ! isset(self::TYPES[$type])) {
continue;
}
$data = is_array($field['data'] ?? null) ? $field['data'] : [];
$base = Str::slug((string) (($data['key'] ?? '') ?: ($data['label'] ?? $data['text'] ?? '') ?: $type.'-'.($index + 1)), '_', 'de') ?: $type;
$base = mb_substr($base, 0, 60);
$key = $base;
for ($i = 2; in_array($key, $used, true); $i++) {
$key = $base.'_'.$i;
}
$used[] = $key;
$data['key'] = $key;
$result[] = ['type' => $type, 'data' => $data];
}
return $result;
}
/**
* Beschreibung für das Formular im Portal (ohne interne Einstellungen).
*
* @return list<array<string, mixed>>
*/
public static function forFrontend(Form $form): array
{
return array_map(function (array $field) {
$d = $field['data'];
return array_filter([
'type' => $field['type'],
'key' => $d['key'],
'label' => $d['label'] ?? null,
'text' => $d['text'] ?? null,
'help' => $d['help'] ?? null,
'placeholder' => $d['placeholder'] ?? null,
'required' => (bool) ($d['required'] ?? false),
'options' => array_values(array_filter(array_map('strval', (array) ($d['options'] ?? [])), 'strlen')) ?: null,
'width' => $d['width'] ?? 'full',
'min' => $d['min'] ?? null,
'max' => $d['max'] ?? null,
'rows' => $d['rows'] ?? null,
'multiple' => (bool) ($d['multiple'] ?? false),
'accept' => isset($d['accept']) ? implode(',', array_map(fn ($ext) => '.'.$ext, self::FILE_TYPES[$d['accept']] ?? self::FILE_TYPES['any'])) : null,
'max_size' => $d['max_size'] ?? null,
'condition' => filled($d['condition_field'] ?? null) ? [
'field' => $d['condition_field'],
'operator' => $d['condition_operator'] ?? 'equals',
'value' => (string) ($d['condition_value'] ?? ''),
] : null,
], fn ($value) => $value !== null && $value !== false && $value !== '');
}, $form->fields ?? []);
}
/**
* Vorbelegung aus dem Profil der Person.
*
* @return array<string, mixed>
*/
public static function prefill(Form $form, User $user): array
{
$values = [];
foreach ($form->fields ?? [] as $field) {
$source = $field['data']['prefill'] ?? null;
if (! $source) {
continue;
}
$values[$field['data']['key']] = str_starts_with($source, 'custom.')
? (string) (($user->custom_fields ?? [])[substr($source, 7)] ?? '')
: (string) ($user->{$source} ?? '');
}
return $values;
}
/**
* @return array<string, string>
*/
public static function prefillOptions(): array
{
return self::PREFILL + collect(app(ProfileFields::class)->options())->mapWithKeys(fn ($label, $key) => ['custom.'.$key => $label])->all();
}
/**
* Ist das Feld bei diesen Antworten sichtbar? (Bedingungen, auch verkettet)
*
* @param array<string, mixed> $answers
*/
public static function visible(Form $form, array $field, array $answers, int $depth = 0): bool
{
$d = $field['data'];
if (blank($d['condition_field'] ?? null) || $depth > 10) {
return true;
}
$other = collect($form->fields)->first(fn ($f) => $f['data']['key'] === $d['condition_field']);
if (! $other || ! self::visible($form, $other, $answers, $depth + 1)) {
return false;
}
$value = $answers[$d['condition_field']] ?? null;
$expected = (string) ($d['condition_value'] ?? '');
$values = array_map('strval', is_array($value) ? $value : ($value === null || $value === '' ? [] : [$value === true ? '1' : (string) $value]));
return match ($d['condition_operator'] ?? 'equals') {
'not_equals' => ! in_array($expected, $values, true),
'contains' => in_array($expected, $values, true),
'filled' => $values !== [] && $values !== ['0'],
'empty' => $values === [] || $values === ['0'],
default => in_array($expected, $values, true),
};
}
/**
* Validierungsregeln für die sichtbaren Felder.
*
* @param array<string, mixed> $answers
* @return array{0: array<string, mixed>, 1: array<string, string>, 2: array<string, string>}
*/
public static function rules(Form $form, array $answers): array
{
$rules = [];
$attributes = [];
$messages = [];
foreach ($form->fields ?? [] as $field) {
if (in_array($field['type'], self::LAYOUT_TYPES, true) || ! self::visible($form, $field, $answers)) {
continue;
}
$d = $field['data'];
$name = 'answers.'.$d['key'];
$required = (bool) ($d['required'] ?? false);
$attributes[$name] = $d['label'] ?? $d['key'];
$options = array_values(array_filter(array_map('strval', (array) ($d['options'] ?? [])), 'strlen'));
$max = isset($d['max']) && $d['max'] !== '' ? (int) $d['max'] : null;
$min = isset($d['min']) && $d['min'] !== '' ? (int) $d['min'] : null;
$rules[$name] = match ($field['type']) {
'text' => [$required ? 'required' : 'nullable', 'string', 'max:'.($max ?: 255)],
'textarea' => [$required ? 'required' : 'nullable', 'string', 'max:'.($max ?: 10000)],
'email' => [$required ? 'required' : 'nullable', 'email', 'max:255'],
'phone' => [$required ? 'required' : 'nullable', 'string', 'max:50', 'regex:/^[0-9+()\/\-.\s]{3,50}$/'],
'number' => [$required ? 'required' : 'nullable', 'numeric', ...($min !== null ? ['min:'.$min] : []), ...($max !== null ? ['max:'.$max] : [])],
'date' => [$required ? 'required' : 'nullable', 'date'],
'select', 'radio' => [$required ? 'required' : 'nullable', 'string', Rule::in($options)],
'checkboxes' => [$required ? 'required' : 'nullable', 'array', ...($min ? ['min:'.$min] : []), ...($max ? ['max:'.$max] : [])],
'checkbox' => $required ? ['accepted'] : ['nullable', 'boolean'],
'file' => [$required ? 'required' : 'nullable', 'array', 'max:'.(($d['multiple'] ?? false) ? 10 : 1)],
};
if ($field['type'] === 'checkbox') {
$messages[$name.'.accepted'] = 'Bitte bestätigen.';
}
if ($field['type'] === 'checkboxes') {
$rules[$name.'.*'] = ['string', Rule::in($options)];
}
if ($field['type'] === 'file') {
$rules[$name.'.*'] = [File::types(self::FILE_TYPES[$d['accept'] ?? 'any'] ?? self::FILE_TYPES['any'])->max(min(50, max(1, (int) ($d['max_size'] ?? 10))) * 1024)];
$attributes[$name.'.*'] = $attributes[$name];
}
}
return [$rules, $attributes, $messages];
}
/**
* Antworten zum Speichern aufbereiten – nur sichtbare Felder.
*
* @param array<string, mixed> $answers validierte Eingaben
* @return array{0: array<string, array{label: string, type: string, value: mixed}>, 1: array<string, list<UploadedFile>>}
*/
public static function collect(Form $form, array $answers): array
{
$data = [];
$files = [];
foreach ($form->fields ?? [] as $field) {
if (in_array($field['type'], self::LAYOUT_TYPES, true) || ! self::visible($form, $field, $answers)) {
continue;
}
$key = $field['data']['key'];
$value = $answers[$key] ?? null;
if ($field['type'] === 'file') {
$files[$key] = array_values(array_filter((array) $value, fn ($f) => $f instanceof UploadedFile));
$value = [];
} elseif ($field['type'] === 'checkbox') {
$value = (bool) $value;
} elseif ($field['type'] === 'checkboxes') {
$value = array_values(array_map('strval', (array) $value));
} elseif ($value !== null) {
$value = trim((string) $value);
}
$data[$key] = ['label' => (string) ($field['data']['label'] ?? $key), 'type' => $field['type'], 'value' => $value];
}
return [$data, $files];
}
/**
* Eingabefelder (ohne Gestaltungselemente): Schlüssel => Bezeichnung.
*
* @return array<string, string>
*/
public static function inputs(Form $form): array
{
return collect($form->fields ?? [])
->reject(fn ($f) => in_array($f['type'], self::LAYOUT_TYPES, true))
->mapWithKeys(fn ($f) => [$f['data']['key'] => (string) ($f['data']['label'] ?? $f['data']['key'])])
->all();
}
}

View file

@ -0,0 +1,36 @@
<?php
namespace Inhaus\Plugins\Forms;
use App\Models\User;
use Inhaus\Plugins\Forms\Models\Form;
/**
* Daten eines Formulars für das Portal (Seite und Pagebuilder-Block).
*/
final class FormPresenter
{
/**
* @return array<string, mixed>
*/
public static function present(Form $form, User $user): array
{
$once = (bool) $form->setting('once_per_user');
return [
'id' => $form->id,
'title' => $form->title,
'description' => $form->description,
'url' => $form->url(),
'fields' => FormFields::forFrontend($form),
'prefill' => FormFields::prefill($form, $user),
'submit_label' => $form->setting('submit_label') ?: 'Absenden',
'confirmation' => $form->setting('confirmation') ?: 'Vielen Dank! Ihre Angaben sind eingegangen.',
'anonymous' => $form->isAnonymous(),
'send_copy' => (bool) $form->setting('send_copy'),
'open' => $form->acceptsSubmissions(),
'closes_at' => $form->closes_at?->toIso8601String(),
'already_submitted' => $once && $form->alreadySubmittedBy($user),
];
}
}

View file

@ -0,0 +1,50 @@
<?php
namespace Inhaus\Plugins\Forms;
use App\Models\User;
use App\Pagebuilder\Blocks;
use App\Pagebuilder\BlockType;
use App\Pagebuilder\Field;
use App\Plugins\Plugin;
use App\Support\Abilities;
use App\Support\Navigation;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Schedule;
use Inhaus\Plugins\Forms\Models\Form;
use Inhaus\Plugins\Forms\Policies\FormPolicy;
class FormsPlugin extends Plugin
{
public function register(): void
{
$this->app->make(Navigation::class)->add('forms', 'Formulare', '/formulare', active: ['forms.index', 'forms.show'], sort: 60);
$abilities = $this->app->make(Abilities::class);
$abilities->define('forms.manage', 'Formulare: alle Formulare und Ergebnisse verwalten', 'Formulare');
$abilities->define('forms.edit', 'Formular bearbeiten', 'Formulare', resource: 'form');
$abilities->define('forms.results', 'Ergebnisse ansehen und exportieren', 'Formulare', resource: 'form');
$abilities->define('forms.results.delete', 'Ergebnisse löschen', 'Formulare', resource: 'form');
$abilities->resourceType('form', 'Formular', fn () => Form::query()->orderBy('title')->pluck('title', 'id')->all());
Gate::policy(Form::class, FormPolicy::class);
$this->app->make(Blocks::class)->add(BlockType::make('forms.form', 'Formular', 'clipboard-list', 'dynamic', 'forms::FormBlock')
->description('Ein Formular direkt auf der Seite ausfüllen lassen.')
->fields([
Field::select('form', 'Formular', fn () => Form::query()->orderBy('title')->pluck('title', 'id')->mapWithKeys(fn ($t, $id) => [(string) $id => $t])->all()),
Field::toggle('show_title', 'Titel und Beschreibung anzeigen', true),
])
->resolveUsing(function (array $data, ?User $user) {
$form = $data['form'] ? Form::query()->find($data['form']) : null;
return $form && $user && $form->isVisibleTo($user) ? FormPresenter::present($form, $user) : null;
}));
}
public function boot(): void
{
// Löschfristen: alte Einsendungen samt Dateien entfernen.
Schedule::call(fn () => app(Retention::class)->purge())->dailyAt('03:15')->name('forms-retention')->withoutOverlapping(30);
}
}

View file

@ -0,0 +1,72 @@
<?php
namespace Inhaus\Plugins\Forms\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Inertia\Inertia;
use Inertia\Response;
use Inhaus\Plugins\Forms\FormFields;
use Inhaus\Plugins\Forms\FormPresenter;
use Inhaus\Plugins\Forms\Models\Form;
use Inhaus\Plugins\Forms\Submissions;
class FormController extends Controller
{
public function index(Request $request): Response
{
$forms = Form::query()->visibleTo($request->user())
->where('is_open', true)
->where(fn ($q) => $q->whereNull('closes_at')->orWhere('closes_at', '>', now()))
->orderBy('title')
->get(['id', 'title', 'slug', 'description', 'closes_at']);
return Inertia::render('forms::Index', [
'forms' => $forms->map(fn (Form $form) => [
'id' => $form->id,
'title' => $form->title,
'description' => $form->description,
'url' => $form->url(),
'closes_at' => $form->closes_at?->toIso8601String(),
]),
]);
}
public function show(Request $request, Form $form): Response
{
abort_unless($form->isVisibleTo($request->user()), 404);
return Inertia::render('forms::Show', [
'form' => FormPresenter::present($form, $request->user()),
]);
}
public function submit(Request $request, Form $form, Submissions $submissions): RedirectResponse
{
$user = $request->user();
abort_unless($form->isVisibleTo($user), 404);
if (! $form->acceptsSubmissions()) {
return back()->withErrors(['form' => 'Dieses Formular nimmt keine Einsendungen mehr an.']);
}
if ($form->setting('once_per_user') && $form->alreadySubmittedBy($user)) {
return back()->withErrors(['form' => 'Sie haben dieses Formular bereits ausgefüllt.']);
}
$answers = (array) $request->input('answers', []);
foreach ($request->allFiles()['answers'] ?? [] as $key => $files) {
$answers[$key] = is_array($files) ? $files : [$files];
}
[$rules, $attributes, $messages] = FormFields::rules($form, $answers);
$validated = Validator::make(['answers' => $answers], $rules, $messages, $attributes)->validate();
$submissions->store($form, $user, $validated['answers'] ?? []);
return back()->with('form_submitted', $form->id);
}
}

View file

@ -0,0 +1,78 @@
<?php
namespace Inhaus\Plugins\Forms\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Support\Audit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Inhaus\Plugins\Forms\FormFields;
use Inhaus\Plugins\Forms\Models\Form;
use Inhaus\Plugins\Forms\Models\FormFile;
use Symfony\Component\HttpFoundation\StreamedResponse;
class FormResultsController extends Controller
{
public function file(FormFile $file): StreamedResponse
{
Gate::authorize('viewResults', $file->submission->form);
return Storage::disk(FormFile::DISK)->download($file->path, $file->name, [
'Content-Type' => $file->mime ?: 'application/octet-stream',
'X-Content-Type-Options' => 'nosniff',
'Cache-Control' => 'private, no-store',
]);
}
/**
* CSV für Excel: UTF-8 mit BOM, Semikolon als Trenner.
*/
public function export(Request $request, Form $form): StreamedResponse
{
Gate::authorize('viewResults', $form);
Audit::log('forms.exported', ['form' => $form->id, 'title' => $form->title]);
$columns = FormFields::inputs($form);
$anonymous = $form->isAnonymous();
return response()->streamDownload(function () use ($form, $columns, $anonymous) {
$out = fopen('php://output', 'w');
fwrite($out, "\xEF\xBB\xBF");
$known = $columns;
// Felder, die es nur noch in älteren Einsendungen gibt, hinten anhängen.
$form->submissions()->select(['id', 'data'])->chunkById(500, function ($chunk) use (&$known) {
foreach ($chunk as $submission) {
foreach ($submission->data as $key => $answer) {
$known[$key] ??= $answer['label'];
}
}
});
fputcsv($out, ['Eingegangen am', ...($anonymous ? [] : ['Name', 'E-Mail']), ...array_values($known)], ';', '"', '');
$form->submissions()->with('user:id,name,email')->orderBy('id')->chunkById(500, function ($chunk) use ($out, $known, $anonymous) {
foreach ($chunk as $submission) {
fputcsv($out, [
$submission->created_at->timezone(config('app.timezone'))->format('d.m.Y H:i'),
...($anonymous ? [] : [$submission->user?->name ?? '', $submission->user?->email ?? '']),
...array_map(fn ($key) => self::cell($submission->display($key)), array_keys($known)),
], ';', '"', '');
}
});
fclose($out);
}, Str::slug($form->title).'-'.now()->format('Y-m-d').'.csv', ['Content-Type' => 'text/csv; charset=UTF-8']);
}
/**
* Schutz vor Formel-Einschleusung in Tabellenprogrammen.
*/
private static function cell(string $value): string
{
return preg_match('/^[=+\-@\t\r]/', $value) ? "'".$value : $value;
}
}

View file

@ -0,0 +1,54 @@
<?php
namespace Inhaus\Plugins\Forms\Mail;
use App\Models\User;
use App\Support\Branding;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;
use Inhaus\Plugins\Forms\Models\Form;
use Inhaus\Plugins\Forms\Models\FormSubmission;
/**
* Benachrichtigung über eine Einsendung – an die Empfänger des Formulars oder
* als Kopie an die Person selbst. Dateien werden nicht angehängt, sondern nur
* nach Anmeldung abrufbar verlinkt.
*/
class FormSubmitted extends Mailable implements ShouldQueue
{
use Queueable;
use SerializesModels;
public function __construct(
public Form $form,
public FormSubmission $submission,
public ?User $person,
public bool $copy,
) {}
public function envelope(): Envelope
{
return new Envelope(
subject: ($this->copy ? 'Ihre Angaben: ' : 'Neue Einsendung: ').$this->form->title,
replyTo: ! $this->copy && $this->person ? [$this->person->email] : [],
);
}
public function content(): Content
{
$includeAnswers = $this->copy || $this->form->setting('mail_answers', true);
return new Content(view: 'forms::mail.submitted', with: [
'portalName' => app(Branding::class)->portalName(),
'answers' => $includeAnswers ? collect($this->submission->data)->map(fn ($answer, $key) => [
'label' => $answer['label'],
'value' => $this->submission->display($key),
])->values()->all() : null,
'resultsUrl' => $this->copy ? null : url('/admin/formulare/'.$this->form->id.'/ergebnisse'),
]);
}
}

View file

@ -0,0 +1,116 @@
<?php
namespace Inhaus\Plugins\Forms\Models;
use App\Models\User;
use App\Support\Permissions\Audiences;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Str;
use Inhaus\Plugins\Forms\FormFields;
/**
* Ein Formular. „fields“ ist die Liste der Felder aus dem Formularbaukasten
* (siehe FormFields), „settings“ Benachrichtigung, Anonymität, Löschfrist u. a.
*/
#[Fillable(['title', 'slug', 'description', 'fields', 'settings', 'is_open', 'closes_at', 'created_by'])]
class Form extends Model
{
protected static function booted(): void
{
static::saving(function (Form $form) {
if (blank($form->slug)) {
$base = Str::slug($form->title, language: 'de') ?: 'formular';
$slug = $base;
for ($i = 2; static::query()->where('slug', $slug)->whereKeyNot($form->id)->exists(); $i++) {
$slug = "{$base}-{$i}";
}
$form->slug = $slug;
}
$form->fields = FormFields::normalize((array) $form->fields);
});
static::deleting(fn (Form $form) => $form->submissions()->with('files')->get()->each->delete());
}
protected function casts(): array
{
return [
'fields' => 'array',
'settings' => 'array',
'is_open' => 'boolean',
'closes_at' => 'datetime',
];
}
/**
* @return array{0: string, 1: int}
*/
public function permissionResource(): array
{
return ['form', $this->id];
}
/**
* @return HasMany<FormSubmission, $this>
*/
public function submissions(): HasMany
{
return $this->hasMany(FormSubmission::class);
}
public function setting(string $key, mixed $default = null): mixed
{
return $this->settings[$key] ?? $default;
}
public function isAnonymous(): bool
{
return (bool) $this->setting('anonymous', false);
}
public function acceptsSubmissions(): bool
{
return $this->is_open && ($this->closes_at === null || $this->closes_at->isFuture());
}
public function url(): string
{
return '/formulare/'.$this->slug;
}
/**
* Kennung für „nur einmal ausfüllen“, ohne bei anonymen Formularen die Person zu speichern.
*/
public function userHash(User $user): string
{
return hash_hmac('sha256', $this->id.':'.$user->id, (string) config('app.key'));
}
public function alreadySubmittedBy(User $user): bool
{
return $this->submissions()
->where(fn ($q) => $q->where('user_hash', $this->userHash($user))->orWhere('user_id', $user->id))
->exists();
}
/**
* @param Builder<Form> $query
*/
public function scopeVisibleTo(Builder $query, ?User $user): void
{
if (! $user?->can('forms.manage')) {
Audiences::constrain($query, 'form', 'forms.id', $user);
}
}
public function isVisibleTo(?User $user): bool
{
return $user?->can('forms.manage') || Audiences::allows('form', $this->id, $user);
}
}

View file

@ -0,0 +1,36 @@
<?php
namespace Inhaus\Plugins\Forms\Models;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Facades\Storage;
/**
* Hochgeladene Datei zu einem Formular. Liegt außerhalb von public/; ausgeliefert
* nur an Personen mit Zugriff auf die Ergebnisse des Formulars.
*/
#[Fillable(['submission_id', 'field', 'name', 'path', 'mime', 'size'])]
class FormFile extends Model
{
public const DISK = 'local';
protected static function booted(): void
{
static::deleted(fn (FormFile $file) => Storage::disk(self::DISK)->delete($file->path));
}
/**
* @return BelongsTo<FormSubmission, $this>
*/
public function submission(): BelongsTo
{
return $this->belongsTo(FormSubmission::class, 'submission_id');
}
public function url(): string
{
return route('forms.file', $this);
}
}

View file

@ -0,0 +1,74 @@
<?php
namespace Inhaus\Plugins\Forms\Models;
use App\Models\User;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Carbon;
/**
* Ein ausgefülltes Formular. „data“ enthält je Feld Bezeichnung, Typ und Wert –
* so bleiben Ergebnisse lesbar, auch wenn das Formular später geändert wird.
*/
#[Fillable(['form_id', 'user_id', 'user_hash', 'data', 'read_at'])]
class FormSubmission extends Model
{
protected static function booted(): void
{
static::deleting(fn (FormSubmission $submission) => $submission->files->each->delete());
}
protected function casts(): array
{
return ['data' => 'array', 'read_at' => 'datetime'];
}
/**
* @return BelongsTo<Form, $this>
*/
public function form(): BelongsTo
{
return $this->belongsTo(Form::class);
}
/**
* @return BelongsTo<User, $this>
*/
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
/**
* @return HasMany<FormFile, $this>
*/
public function files(): HasMany
{
return $this->hasMany(FormFile::class, 'submission_id');
}
/**
* Wert als Text (Listen mit Komma, Ja/Nein, Dateinamen).
*/
public function display(string $key): string
{
$answer = $this->data[$key] ?? null;
if ($answer === null) {
return '';
}
$value = $answer['value'] ?? null;
return match (true) {
($answer['type'] ?? null) === 'checkbox' => $value ? 'Ja' : 'Nein',
($answer['type'] ?? null) === 'file' => implode(', ', array_column((array) $value, 'name')),
($answer['type'] ?? null) === 'date' && is_string($value) && preg_match('/^\d{4}-\d{2}-\d{2}$/', $value) => Carbon::parse($value)->format('d.m.Y'),
is_array($value) => implode(', ', $value),
default => (string) $value,
};
}
}

View file

@ -0,0 +1,53 @@
<?php
namespace Inhaus\Plugins\Forms\Policies;
use App\Models\User;
use Inhaus\Plugins\Forms\Models\Form;
/**
* „Formulare verwalten“ gilt für alle Formulare. Je Formular vergibt man
* „Bearbeiten“, „Ergebnisse ansehen“ und „Ergebnisse löschen“ an Rollen –
* z. B. sieht nur die Personalabteilung die Anträge auf Fortbildung.
*/
class FormPolicy
{
public function viewAny(User $user): bool
{
$permissions = $user->permissions();
return $user->can('forms.manage')
|| $permissions->ids('forms.edit', 'form') !== []
|| $permissions->ids('forms.results', 'form') !== [];
}
public function create(User $user): bool
{
return $user->can('forms.manage');
}
public function update(User $user, Form $form): bool
{
return $user->can('forms.manage') || $user->can('forms.edit', ['form', $form->id]);
}
public function delete(User $user, Form $form): bool
{
return $user->can('forms.manage');
}
public function viewResults(User $user, Form $form): bool
{
return $user->can('forms.manage') || $user->can('forms.results', ['form', $form->id]);
}
public function deleteResults(User $user, Form $form): bool
{
return $user->can('forms.manage') || $user->can('forms.results.delete', ['form', $form->id]);
}
public function submit(User $user, Form $form): bool
{
return $form->acceptsSubmissions() && $form->isVisibleTo($user);
}
}

View file

@ -0,0 +1,32 @@
<?php
namespace Inhaus\Plugins\Forms;
use Inhaus\Plugins\Forms\Models\Form;
/**
* Löscht Einsendungen, deren Aufbewahrungsfrist abgelaufen ist (Einstellung je Formular).
*/
class Retention
{
public function purge(): int
{
$deleted = 0;
foreach (Form::query()->get() as $form) {
$days = (int) $form->setting('retention_days', 0);
if ($days <= 0) {
continue;
}
$form->submissions()->with('files')->where('created_at', '<', now()->subDays($days))
->chunkById(100, function ($submissions) use (&$deleted) {
$submissions->each->delete();
$deleted += $submissions->count();
});
}
return $deleted;
}
}

View file

@ -0,0 +1,118 @@
<?php
namespace Inhaus\Plugins\Forms;
use App\Models\User;
use App\Notifications\PortalNotification;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Str;
use Inhaus\Plugins\Forms\Mail\FormSubmitted;
use Inhaus\Plugins\Forms\Models\Form;
use Inhaus\Plugins\Forms\Models\FormFile;
use Inhaus\Plugins\Forms\Models\FormSubmission;
use Throwable;
/**
* Speichert eine Einsendung und verschickt die Benachrichtigungen.
*/
class Submissions
{
/**
* @param array<string, mixed> $answers validierte Eingaben
*/
public function store(Form $form, User $user, array $answers): FormSubmission
{
[$data, $uploads] = FormFields::collect($form, $answers);
$anonymous = $form->isAnonymous();
$submission = DB::transaction(function () use ($form, $user, $data, $uploads, $anonymous) {
$submission = $form->submissions()->create([
'user_id' => $anonymous ? null : $user->id,
'user_hash' => $form->setting('once_per_user') ? $form->userHash($user) : null,
'data' => $data,
]);
foreach ($uploads as $key => $files) {
$stored = [];
foreach ($files as $upload) {
$name = Str::limit(preg_replace('/[^\pL\pN ._()\-]+/u', '_', $upload->getClientOriginalName()) ?: 'datei', 180, '');
$file = $submission->files()->create([
'field' => $key,
'name' => $name,
'path' => $upload->storeAs('forms/'.$form->id, Str::random(40).'.'.strtolower($upload->getClientOriginalExtension() ?: 'bin'), FormFile::DISK),
'mime' => $upload->getMimeType(),
'size' => $upload->getSize(),
]);
$stored[] = ['id' => $file->id, 'name' => $name, 'size' => $file->size];
}
$data[$key]['value'] = $stored;
}
$submission->update(['data' => $data]);
return $submission;
});
$this->notify($form, $submission, $user);
return $submission;
}
private function notify(Form $form, FormSubmission $submission, User $user): void
{
$recipients = collect((array) $form->setting('notify_emails', []))
->map(fn ($email) => strtolower(trim((string) $email)))
->filter(fn ($email) => filter_var($email, FILTER_VALIDATE_EMAIL));
$viewers = $form->setting('notify_viewers') ? $this->resultViewers($form) : collect();
try {
foreach ($recipients->merge($viewers->pluck('email'))->unique() as $email) {
Mail::to($email)->queue(new FormSubmitted($form, $submission, $form->isAnonymous() ? null : $user, copy: false));
}
if ($form->setting('send_copy')) {
Mail::to($user->email)->queue(new FormSubmitted($form, $submission, $user, copy: true));
}
} catch (Throwable $e) {
// Die Einsendung ist gespeichert – ein Versandfehler darf sie nicht verwerfen.
Log::error("Formular {$form->id}: Benachrichtigung fehlgeschlagen: ".$e->getMessage());
}
if ($viewers->isNotEmpty()) {
Notification::send($viewers, new PortalNotification(
'Neue Einsendung: '.$form->title,
$form->isAnonymous() ? 'Anonyme Einsendung' : 'Von '.$user->name,
route('filament.admin.resources.formulare.results', ['record' => $form]),
'file-check',
));
}
}
/**
* Personen mit Zugriff auf die Ergebnisse dieses Formulars.
*
* @return Collection<int, User>
*/
public function resultViewers(Form $form): Collection
{
$roleIds = DB::table('grants')
->where(function ($q) use ($form) {
$q->whereIn('ability', ['*', 'forms.manage'])->whereNull('resource_type');
$q->orWhere(fn ($q) => $q->where('ability', 'forms.results')->where('resource_type', 'form')
->where(fn ($q) => $q->whereNull('resource_id')->orWhere('resource_id', $form->id)));
})
->pluck('role_id');
return User::query()->active()
->whereIn('id', DB::table('role_user')->whereIn('role_id', $roleIds)->select('user_id'))
->limit(100)
->get();
}
}