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,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();
}
}